@numero-uno-jpn/rstats 1.12.0 → 1.14.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 (84) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/README.ja.md +6 -6
  3. package/README.md +6 -6
  4. package/dist/causal/balance.d.ts +30 -18
  5. package/dist/causal/balance.js +74 -26
  6. package/dist/causal/weightit.d.ts +159 -0
  7. package/dist/causal/weightit.js +491 -0
  8. package/dist/causal.js +2 -2
  9. package/dist/chunks/{chunk-3QOW56EJ.js → chunk-2426YL2X.js} +2 -2
  10. package/dist/chunks/{chunk-JG26HC2H.js → chunk-3746VXPM.js} +2 -2
  11. package/dist/chunks/{chunk-XQSYV3IZ.js → chunk-3DA7CMFN.js} +2 -2
  12. package/dist/chunks/{chunk-O6OMXX5U.js → chunk-3XUHCWLU.js} +1 -1
  13. package/dist/chunks/chunk-4O6XLQBN.js +2 -0
  14. package/dist/chunks/{chunk-CKBUE4FV.js → chunk-62Y36UKH.js} +2 -2
  15. package/dist/chunks/{chunk-NGDBJR3K.js → chunk-6HUTVWPO.js} +2 -2
  16. package/dist/chunks/chunk-6VY3XNAF.js +2 -0
  17. package/dist/chunks/{chunk-7K2LMKZR.js → chunk-7BBIQY4W.js} +2 -2
  18. package/dist/chunks/chunk-7FGVMDJE.js +3 -0
  19. package/dist/chunks/{chunk-2P42OXYW.js → chunk-7VMGP2U7.js} +2 -2
  20. package/dist/chunks/{chunk-YKCZF4ES.js → chunk-A5DZG7FH.js} +2 -2
  21. package/dist/chunks/{chunk-7FXBOYIH.js → chunk-AONDWNMF.js} +2 -2
  22. package/dist/chunks/{chunk-SKQHW2GD.js → chunk-AQHG7BEZ.js} +2 -2
  23. package/dist/chunks/{chunk-NAACMR7H.js → chunk-B6NPCYFO.js} +2 -2
  24. package/dist/chunks/{chunk-WUNTM7PJ.js → chunk-BCXYAILN.js} +2 -2
  25. package/dist/chunks/{chunk-QT32BMYA.js → chunk-CKUBQW2A.js} +2 -2
  26. package/dist/chunks/chunk-D25AVVVI.js +2 -0
  27. package/dist/chunks/{chunk-CHKBDZC4.js → chunk-DZQWGBTW.js} +2 -2
  28. package/dist/chunks/{chunk-HF3QOIZX.js → chunk-EDRBKZ3C.js} +2 -2
  29. package/dist/chunks/{chunk-SZR5HAMB.js → chunk-EWNJT27V.js} +2 -2
  30. package/dist/chunks/{chunk-3QSYPBUM.js → chunk-F6KKW5YN.js} +2 -2
  31. package/dist/chunks/{chunk-T5TE5KCP.js → chunk-FPJ2CWLK.js} +2 -2
  32. package/dist/chunks/{chunk-WSDLT4AR.js → chunk-H5GBKP57.js} +1 -1
  33. package/dist/chunks/{chunk-4B7NEJCE.js → chunk-I2OTBVRK.js} +2 -2
  34. package/dist/chunks/{chunk-ZK7FW5UX.js → chunk-IXFWR3LH.js} +2 -2
  35. package/dist/chunks/chunk-JCGCJT7T.js +2 -0
  36. package/dist/chunks/{chunk-L54WIMTZ.js → chunk-KITNZUYC.js} +2 -2
  37. package/dist/chunks/chunk-MCEZRRQO.js +2 -0
  38. package/dist/chunks/{chunk-UPFMYDF7.js → chunk-MJHFGGPU.js} +2 -2
  39. package/dist/chunks/{chunk-4GRV66HW.js → chunk-MXOBCQQP.js} +2 -2
  40. package/dist/chunks/{chunk-WACTNIKS.js → chunk-NA7EDZ4Q.js} +2 -2
  41. package/dist/chunks/{chunk-SLMS3FQD.js → chunk-PHDTVTKV.js} +1 -1
  42. package/dist/chunks/{chunk-ZHAT6244.js → chunk-QLKZ2OFQ.js} +2 -2
  43. package/dist/chunks/{chunk-MAFZ5FGL.js → chunk-SDIIGAY5.js} +2 -2
  44. package/dist/chunks/{chunk-4U65I4J2.js → chunk-SEKOIW43.js} +2 -2
  45. package/dist/chunks/{chunk-52KGBGFL.js → chunk-TGXUU5NB.js} +1 -1
  46. package/dist/chunks/chunk-VWCCPBBG.js +2 -0
  47. package/dist/chunks/chunk-XXH5OIUO.js +2 -0
  48. package/dist/chunks/{chunk-MJ7IY7AF.js → chunk-Y7VD43TO.js} +2 -2
  49. package/dist/chunks/{chunk-5AR4V7MW.js → chunk-YLUF4WTL.js} +2 -2
  50. package/dist/chunks/{chunk-ULQXNAI6.js → chunk-ZJJJDLRL.js} +2 -2
  51. package/dist/chunks/chunk-ZWSHIUBZ.js +2 -0
  52. package/dist/descriptive.js +2 -2
  53. package/dist/distributions.js +2 -2
  54. package/dist/entries/causal.d.ts +1 -0
  55. package/dist/entries/causal.js +1 -0
  56. package/dist/entries/regression.d.ts +1 -0
  57. package/dist/entries/regression.js +2 -0
  58. package/dist/entries/tests.d.ts +2 -0
  59. package/dist/entries/tests.js +2 -0
  60. package/dist/linalg.js +2 -2
  61. package/dist/mixed.js +2 -2
  62. package/dist/models/multinom.d.ts +250 -0
  63. package/dist/models/multinom.js +520 -0
  64. package/dist/models/survfitCoxph.d.ts +95 -0
  65. package/dist/models/survfitCoxph.js +223 -0
  66. package/dist/models/survival.d.ts +9 -2
  67. package/dist/models/survival.js +15 -11
  68. package/dist/models/svyglm.d.ts +77 -0
  69. package/dist/models/svyglm.js +102 -0
  70. package/dist/multivariate.js +2 -2
  71. package/dist/numerics.js +2 -2
  72. package/dist/regression.js +3 -3
  73. package/dist/rstats.js +17 -17
  74. package/dist/special.js +2 -2
  75. package/dist/tests.js +15 -15
  76. package/dist/timeseries.js +2 -2
  77. package/package.json +1 -1
  78. package/dist/chunks/chunk-7UI4PW32.js +0 -2
  79. package/dist/chunks/chunk-CMTCPLIA.js +0 -2
  80. package/dist/chunks/chunk-DWVTVOQS.js +0 -2
  81. package/dist/chunks/chunk-FFMMKXMK.js +0 -2
  82. package/dist/chunks/chunk-MUYGPZ37.js +0 -3
  83. package/dist/chunks/chunk-NQT7ZWL6.js +0 -2
  84. package/dist/chunks/chunk-PYFASERO.js +0 -2
@@ -0,0 +1,491 @@
1
+ // Inverse probability of treatment weighting: WeightIt's weightit (methods glm, cbps, ipt and ebal for a binary
2
+ // treatment), trim and the weight summary of summary.weightit. The behaviour is in oracle/weightit-behaviour.md, from the
3
+ // packages' documentation and published output; Imai & Ratkovic (2014) for the just-identified covariate balancing
4
+ // propensity score, Graham, Pinto & Egel (2012) for inverse probability tilting, Hainmueller (2012) for entropy
5
+ // balancing, Li, Morgan & Zaslavsky (2018) for the overlap weights. Written for rStats.js (no ported code).
6
+ //
7
+ // The balance conditions of cbps, ipt and ebal are solved by Newton's method to machine precision, where R's optimisers
8
+ // stop at their tolerance (oracle/weightit-behaviour.md, Choices 2): the weights agree with R's to about 1e-8 relative.
9
+ import { glm } from "../models/glm.js";
10
+ import { compareCodePoints } from "../models/modelFrame.js";
11
+ import { quantile } from "../descriptive/quantile.js";
12
+ import { pnorm, dnorm } from "../distributions/normal.js";
13
+ import { plogis } from "../distributions/logistic.js";
14
+ import { reported, reportWarnings, unreported } from "../internal/warnings.js";
15
+ import { rescaled } from "./scale.js";
16
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
17
+ import { checkOptions } from "../internal/checkOptions.js";
18
+ const WEIGHTIT_KEYS = ["method", "link", "estimand", "stabilize"];
19
+ const TRIM_WEIGHTS_KEYS = ["at", "lower", "treat"];
20
+ const EPS = Number.EPSILON;
21
+ function treatment(tr) {
22
+ return tr.map((t, i) => {
23
+ if (t === true || t === 1)
24
+ return 1;
25
+ if (t === false || t === 0)
26
+ return 0;
27
+ throw new RangeError(`'tr' must be 0 or 1 (element ${i + 1})`);
28
+ });
29
+ }
30
+ /** The model matrix without its intercept: one column per numeric covariate, k - 1 indicator columns per factor */
31
+ export function covariateColumns(covariates, n) {
32
+ const names = [], columns = [], factors = {};
33
+ for (const [name, col] of Object.entries(covariates)) {
34
+ if (col.length !== n)
35
+ throw new RangeError(`covariate '${name}' must have the length of 'tr'`);
36
+ if (col.every((v) => typeof v === "number")) {
37
+ const v = col;
38
+ if (v.some((x) => !Number.isFinite(x)))
39
+ throw new RangeError(`covariate '${name}' has missing or infinite values`);
40
+ names.push(name);
41
+ columns.push(v.slice());
42
+ continue;
43
+ }
44
+ if (!col.every((v) => typeof v === "string"))
45
+ throw new TypeError(`covariate '${name}' must be all numbers or all strings`);
46
+ const v = col;
47
+ const levels = [...new Set(v)].sort(compareCodePoints);
48
+ factors[name] = levels;
49
+ for (const lv of levels.slice(1)) {
50
+ names.push(name + lv);
51
+ columns.push(v.map((s) => (s === lv ? 1 : 0)));
52
+ }
53
+ }
54
+ return { names, columns, factors };
55
+ }
56
+ /** Columns centred at their mean and divided by their largest deviation: with an intercept in the model, the balance
57
+ * conditions (and so the weights and scores) are unchanged by this affine map, and Newton's method is well scaled */
58
+ function standardised(columns) {
59
+ return columns.map((c) => {
60
+ const m = c.reduce((a, v) => a + v, 0) / c.length;
61
+ const s = c.reduce((a, v) => Math.max(a, Math.abs(v - m)), 0);
62
+ return c.map((v) => (s > 0 ? (v - m) / s : 0));
63
+ });
64
+ }
65
+ /**
66
+ * The columns that are not constant nor combinations of the intercept and earlier columns (Gram-Schmidt with R's qr
67
+ * tolerance 1e-7 on the relative residual norm): those R's model fit keeps, the others being aliased
68
+ */
69
+ function independent(columns) {
70
+ const n = columns[0]?.length ?? 0;
71
+ const basis = [new Array(n).fill(1 / Math.sqrt(n))];
72
+ const kept = [];
73
+ for (const c of columns) {
74
+ const norm0 = Math.sqrt(c.reduce((a, v) => a + v * v, 0));
75
+ const r = c.slice();
76
+ for (let pass = 0; pass < 2; pass++)
77
+ for (const q of basis) {
78
+ const dot = r.reduce((a, v, i) => a + v * q[i], 0);
79
+ for (let i = 0; i < n; i++)
80
+ r[i] -= dot * q[i];
81
+ }
82
+ const norm = Math.sqrt(r.reduce((a, v) => a + v * v, 0));
83
+ if (!(norm > 1e-7 * norm0))
84
+ continue;
85
+ basis.push(r.map((v) => v / norm));
86
+ kept.push(c);
87
+ }
88
+ return kept;
89
+ }
90
+ /** Solves A x = b (Gaussian elimination with partial pivoting); null when A is singular */
91
+ function solve(A, b) {
92
+ const p = b.length;
93
+ const M = A.map((r, i) => [...r, b[i]]);
94
+ let scale = 0;
95
+ for (const r of A)
96
+ for (const v of r)
97
+ scale = Math.max(scale, Math.abs(v));
98
+ for (let k = 0; k < p; k++) {
99
+ let piv = k;
100
+ for (let i = k + 1; i < p; i++)
101
+ if (Math.abs(M[i][k]) > Math.abs(M[piv][k]))
102
+ piv = i;
103
+ if (!(Math.abs(M[piv][k]) > 1e-13 * scale))
104
+ return null;
105
+ [M[k], M[piv]] = [M[piv], M[k]];
106
+ for (let i = k + 1; i < p; i++) {
107
+ const f = M[i][k] / M[k][k];
108
+ if (f !== 0)
109
+ for (let j = k; j <= p; j++)
110
+ M[i][j] -= f * M[k][j];
111
+ }
112
+ }
113
+ const x = new Array(p).fill(0);
114
+ for (let i = p - 1; i >= 0; i--) {
115
+ let s = M[i][p];
116
+ for (let j = i + 1; j < p; j++)
117
+ s -= M[i][j] * x[j];
118
+ x[i] = s / M[i][i];
119
+ }
120
+ return x;
121
+ }
122
+ /** Rows of [1, z...] for every unit */
123
+ function design(z, n) {
124
+ return Array.from({ length: n }, (_, i) => [1, ...z.map((c) => c[i])]);
125
+ }
126
+ /**
127
+ * Exponential tilting: beta with sum over `rows` of exp(x_i beta) x_i = target (x with its intercept), the minimum of the
128
+ * convex sum exp(x_i beta) - target' beta. Returns the linear predictor of every unit, and whether it converged.
129
+ */
130
+ function tilt(X, rows, target) {
131
+ const p = target.length;
132
+ const beta = new Array(p).fill(0);
133
+ beta[0] = Math.log(target[0] / rows.length);
134
+ const objective = (b) => {
135
+ let s = 0;
136
+ for (const i of rows)
137
+ s += Math.exp(X[i].reduce((a, v, j) => a + v * b[j], 0));
138
+ return s - target.reduce((a, t, j) => a + t * b[j], 0);
139
+ };
140
+ let f = objective(beta);
141
+ let converged = false;
142
+ const tol = 1e-13 * Math.max(1, Math.abs(target[0]));
143
+ for (let it = 0; it < 200; it++) {
144
+ const g = target.map((t) => -t);
145
+ const H = Array.from({ length: p }, () => new Array(p).fill(0));
146
+ for (const i of rows) {
147
+ const x = X[i];
148
+ const e = Math.exp(x.reduce((a, v, j) => a + v * beta[j], 0));
149
+ for (let j = 0; j < p; j++) {
150
+ g[j] += e * x[j];
151
+ for (let k = 0; k <= j; k++)
152
+ H[j][k] += e * x[j] * x[k];
153
+ }
154
+ }
155
+ for (let j = 0; j < p; j++)
156
+ for (let k = j + 1; k < p; k++)
157
+ H[j][k] = H[k][j];
158
+ const gmax = Math.max(...g.map(Math.abs));
159
+ if (gmax <= tol) {
160
+ converged = true;
161
+ break;
162
+ }
163
+ const step = solve(H, g.map((v) => -v));
164
+ if (step === null || step.some((v) => !Number.isFinite(v)))
165
+ break;
166
+ // near the minimum the decrease (about g' H^-1 g / 2) falls below the rounding of the objective: a rise within that
167
+ // rounding is accepted, else the line search would stop Newton's method short (n = 5000 stalled at |g| = 1e-5)
168
+ const slack = 1e-12 * (Math.abs(f) + 1);
169
+ let t = 1, next = beta.map((b, j) => b + step[j]), fn = objective(next);
170
+ while (!(fn <= f + slack) && t > 1e-10) {
171
+ t /= 2;
172
+ next = beta.map((b, j) => b + t * step[j]);
173
+ fn = objective(next);
174
+ }
175
+ if (!(fn <= f + slack))
176
+ break;
177
+ const moved = step.some((v, j) => Math.abs(t * v) > 1e-15 * Math.max(1, Math.abs(beta[j])));
178
+ beta.splice(0, p, ...next);
179
+ f = fn;
180
+ if (!moved) {
181
+ converged = gmax <= 1e-9 * Math.max(1, Math.abs(target[0]));
182
+ break;
183
+ }
184
+ }
185
+ return { eta: X.map((x) => x.reduce((a, v, j) => a + v * beta[j], 0)), converged };
186
+ }
187
+ const LINKS = {
188
+ logit: { p: (e) => plogis(e), q: (e) => plogis(-e), d: (e) => plogis(e) * plogis(-e) },
189
+ probit: { p: (e) => pnorm(e), q: (e) => pnorm(-e), d: (e) => dnorm(e) },
190
+ };
191
+ /** The just-identified CBPS: beta with sum c_i x_i = 0, c_i the treated weight or minus the control weight */
192
+ function cbps(X, tr, estimand, link, start) {
193
+ const n = tr.length, p = start.length;
194
+ let beta = start.slice();
195
+ const parts = (b) => {
196
+ const g = new Array(p).fill(0);
197
+ const J = Array.from({ length: p }, () => new Array(p).fill(0));
198
+ for (let i = 0; i < n; i++) {
199
+ const x = X[i], eta = x.reduce((a, v, j) => a + v * b[j], 0);
200
+ const P = link.p(eta), Q = link.q(eta), D = link.d(eta), t = tr[i];
201
+ let c, dc;
202
+ if (estimand === "ATE") {
203
+ c = t ? 1 / P : -1 / Q;
204
+ dc = t ? -D / (P * P) : -D / (Q * Q);
205
+ }
206
+ else if (estimand === "ATT") {
207
+ c = t ? 1 : -P / Q;
208
+ dc = t ? 0 : -D / (Q * Q);
209
+ }
210
+ else if (estimand === "ATC") {
211
+ c = t ? Q / P : -1;
212
+ dc = t ? -D / (P * P) : 0;
213
+ }
214
+ else {
215
+ c = t ? Q : -P;
216
+ dc = -D;
217
+ }
218
+ for (let j = 0; j < p; j++) {
219
+ g[j] += c * x[j];
220
+ for (let k = 0; k < p; k++)
221
+ J[j][k] += dc * x[j] * x[k];
222
+ }
223
+ }
224
+ return { g, J };
225
+ };
226
+ const norm = (g) => g.reduce((a, v) => a + v * v, 0);
227
+ let { g, J } = parts(beta);
228
+ let f = norm(g), converged = false;
229
+ const tol = 1e-12 * n;
230
+ for (let it = 0; it < 200; it++) {
231
+ if (Math.max(...g.map(Math.abs)) <= tol) {
232
+ converged = true;
233
+ break;
234
+ }
235
+ const step = solve(J, g.map((v) => -v));
236
+ if (step === null || step.some((v) => !Number.isFinite(v)))
237
+ break;
238
+ let t = 1, next = beta.map((b, j) => b + step[j]), pn = parts(next), fn = norm(pn.g);
239
+ while (!(fn < f) && t > 1e-10) {
240
+ t /= 2;
241
+ next = beta.map((b, j) => b + t * step[j]);
242
+ pn = parts(next);
243
+ fn = norm(pn.g);
244
+ }
245
+ if (!(fn < f)) {
246
+ converged = Math.max(...g.map(Math.abs)) <= 1e-8 * n;
247
+ break;
248
+ }
249
+ beta = next;
250
+ g = pn.g;
251
+ J = pn.J;
252
+ f = fn;
253
+ }
254
+ return { eta: X.map((x) => x.reduce((a, v, j) => a + v * beta[j], 0)), converged };
255
+ }
256
+ /** Weights of the estimand from the propensity score p (q = 1 - p, computed apart for accuracy) */
257
+ function psWeight(estimand, t, p, q) {
258
+ switch (estimand) {
259
+ case "ATE": return t ? 1 / p : 1 / q;
260
+ case "ATT": return t ? 1 : p / q;
261
+ case "ATC": return t ? q / p : 1;
262
+ default: return t ? q : p;
263
+ }
264
+ }
265
+ /** R's warnings when the estimation does not converge (WeightIt's wording, the lines of the cli message joined) */
266
+ const NOT_CONVERGED = {
267
+ glm: "glm.fit: algorithm did not converge",
268
+ cbps: "The covariate balancing conditions could not be solved, so the covariates will not be exactly balanced.",
269
+ ipt: "The optimization failed to converge; consider using fewer covariates or a different link function.",
270
+ ebal: "The estimated weights do not balance the covariates, indicating the optimization arrived at a degenerate " +
271
+ "solution. Try decreasing the number of variables supplied to the optimization.",
272
+ };
273
+ const METHOD_NAME = { cbps: "covariate balancing propensity score weighting", ipt: "inverse probability tilting",
274
+ ebal: "entropy balancing" };
275
+ /**
276
+ * Balancing weights for a binary treatment. Equivalent to `WeightIt::weightit()` in R. The call followed is
277
+ * `weightit(tr ~ covariates, data, method, link, estimand, stabilize)`.
278
+ *
279
+ * - `"glm"` (`"ps"`): the propensity score `p` of a binomial glm with the link, and the weights 1/p and 1/(1 − p)
280
+ * (ATE), 1 and p/(1 − p) (ATT), (1 − p)/p and 1 (ATC), 1 − p and p (ATO, the overlap weights).
281
+ * - `"cbps"`: the just-identified covariate balancing propensity score: the score whose weights (the same formulas)
282
+ * make the weighted means of every covariate column equal in the two groups (ATT: the controls' to the treated's).
283
+ * - `"ipt"`: inverse probability tilting, a logistic score per weighted group whose weights move the group's means to
284
+ * the target (ATE: the whole sample's). Not ATO.
285
+ * - `"ebal"`: entropy balancing: the weights closest to uniform in entropy with the target means, summing to the
286
+ * target size. No propensity score; not ATO.
287
+ *
288
+ * cbps, ipt and ebal are solved exactly (Newton's method on the balance conditions); R stops its optimisers earlier, so
289
+ * those weights agree with R's to about 1e-8 relative. A string covariate is a factor (levels in code-point order);
290
+ * missing values are an error (R drops or imputes them depending on the method).
291
+ * @category Causal inference
292
+ * @example
293
+ * ```ts
294
+ * const tr = [1, 0, 1, 0, 0, 1, 0, 0, 1, 0];
295
+ * const age = [52, 40, 61, 58, 33, 47, 50, 45, 39, 44];
296
+ * const w = weightit(tr, { age }, { estimand: "ATE" });
297
+ * w.ps[0]; // 0.48529828581084455
298
+ * w.weights[0]; // 2.0605883623289194 (1 / ps for a treated unit)
299
+ * ```
300
+ */
301
+ export function weightit(tr, covariates, options = {}) {
302
+ checkOptions(options, WEIGHTIT_KEYS, "weightit"); // generated: option-keys.mjs
303
+ const { method: given = "glm", estimand = "ATE", stabilize = false } = options;
304
+ const method = given === "ps" ? "glm" : given;
305
+ if (!["glm", "cbps", "ipt", "ebal"].includes(method))
306
+ throw new RangeError(`unknown method '${String(given)}'`);
307
+ if (!["ATE", "ATT", "ATC", "ATO"].includes(estimand))
308
+ throw new RangeError(`unknown estimand '${String(estimand)}'`);
309
+ const link = method === "ebal" ? null : options.link ?? "logit";
310
+ const allowed = { glm: ["logit", "probit", "cauchit", "cloglog"],
311
+ cbps: ["logit", "probit"], ipt: ["logit"] };
312
+ if (link !== null && !allowed[method].includes(link))
313
+ throw new RangeError(`link '${link}' is not available for method '${method}'`);
314
+ if ((method === "ipt" || method === "ebal") && estimand === "ATO") {
315
+ throw new RangeError(`"ATO" is not an allowable estimand for ${METHOD_NAME[method]} with a binary treatment. ` +
316
+ `Only "ATE", "ATT", and "ATC" are allowed.`);
317
+ }
318
+ const warnings = [];
319
+ if (stabilize && method === "glm" && estimand !== "ATE")
320
+ throw new RangeError("`stabilize` can only be supplied when `estimand = \"ATE\"`.");
321
+ if (stabilize && method !== "glm")
322
+ warnings.push(`\`stabilize\` cannot be used with ${METHOD_NAME[method]} and will be ignored.`);
323
+ const t = treatment(tr);
324
+ const n = t.length;
325
+ if (!t.includes(0) || !t.includes(1))
326
+ throw new RangeError("The treatment must have at least two unique values.");
327
+ const { names, columns: raw } = covariateColumns(covariates, n);
328
+ if (raw.length === 0)
329
+ throw new RangeError("'covariates' must have at least one column");
330
+ // each column rescaled exactly (by a power of 2, then less its first value): with the intercept the scores and
331
+ // weights do not change, while a column like 1e15 + small differences keeps its digits and one near 1e-300 does not
332
+ // underflow; constant and aliased columns are left out (R's fit drops them)
333
+ const columns = independent(raw.map((c) => rescaled(c).values));
334
+ const treated = t.flatMap((v, i) => (v ? [i] : [])), control = t.flatMap((v, i) => (v ? [] : [i]));
335
+ const all = t.map((_, i) => i);
336
+ const focal = estimand === "ATT" ? 1 : estimand === "ATC" ? 0 : null;
337
+ let ps = null, weights, converged = true;
338
+ if (method === "glm") {
339
+ const fit = unreported(() => glm(design(columns, n).map((r) => r.slice(1)), t, { family: "binomial", link: link }));
340
+ converged = fit.converged;
341
+ // R's glm keeps the scores within [eps, 1 - eps] (logit: eps beyond |eta| = 30); rStats.js's glm gives the exact
342
+ // values there, so they are bounded here as R's, and the weights follow from them
343
+ ps = fit.fittedValues.map((p, i) => (link === "logit" && Math.abs(fit.linearPredictors[i]) > 30
344
+ ? (fit.linearPredictors[i] > 0 ? 1 - EPS : EPS) : Math.min(Math.max(p, EPS), 1 - EPS)));
345
+ // from the score as R does (1 - p, not a separately computed complement)
346
+ weights = t.map((v, i) => psWeight(estimand, v, ps[i], 1 - ps[i]));
347
+ if (ps.some((p) => p <= 10 * EPS || p >= 1 - 10 * EPS)) {
348
+ warnings.push("Propensity scores numerically equal to 0 or 1 were estimated, indicating perfect separation. These " +
349
+ "may yield problems with inference. See `?method_glm` (`?WeightIt::method_glm()`) for details.");
350
+ }
351
+ }
352
+ else if (method === "cbps") {
353
+ const z = standardised(columns);
354
+ const X = design(z, n);
355
+ // start: the glm of the same link on the standardised columns
356
+ const start = unreported(() => glm(X.map((r) => r.slice(1)), t, { family: "binomial", link: link })).coefficients
357
+ .map((b) => (Number.isFinite(b) ? b : 0));
358
+ const fn = LINKS[link];
359
+ const r = cbps(X, t, estimand, fn, start);
360
+ converged = r.converged;
361
+ // R keeps the scores within [eps, 1 - eps] (a score of 1e-19 is reported as 2.2e-16) and weighs by them
362
+ const bounded = (x) => Math.min(Math.max(x, EPS), 1 - EPS);
363
+ ps = r.eta.map((e) => bounded(fn.p(e)));
364
+ weights = t.map((v, i) => psWeight(estimand, v, ps[i], bounded(fn.q(r.eta[i]))));
365
+ }
366
+ else {
367
+ // a tilting of the controls towards the treated means (beta_C) and of the treated towards the controls' (beta_T):
368
+ // with an intercept, the ATE conditions of each group are the same equations
369
+ const z = standardised(columns);
370
+ const X = design(z, n);
371
+ const sums = (rows) => X[0].map((_, j) => rows.reduce((s, i) => s + X[i][j], 0));
372
+ const need = { C: estimand !== "ATC", T: estimand !== "ATT" };
373
+ const target = method === "ebal" && estimand === "ATE" ? { C: sums(all), T: sums(all) }
374
+ : { C: sums(treated), T: sums(control) };
375
+ const C = need.C ? tilt(X, control, target.C) : null, T = need.T ? tilt(X, treated, target.T) : null;
376
+ converged = (C?.converged ?? true) && (T?.converged ?? true);
377
+ if (method === "ebal") {
378
+ weights = t.map((v, i) => (v ? (T ? Math.exp(T.eta[i]) : 1) : (C ? Math.exp(C.eta[i]) : 1)));
379
+ }
380
+ else {
381
+ // ipt: controls weigh 1 + exp(eta_C) (ATE) or exp(eta_C) (ATT); the treated 1 + exp(eta_T) or exp(eta_T) (ATC),
382
+ // their scores plogis(eta_C) and plogis(-eta_T)
383
+ const add = estimand === "ATE" ? 1 : 0;
384
+ weights = t.map((v, i) => (v ? (T ? add + Math.exp(T.eta[i]) : 1) : (C ? add + Math.exp(C.eta[i]) : 1)));
385
+ ps = t.map((v, i) => (estimand === "ATT" ? plogis(C.eta[i]) : estimand === "ATC" ? plogis(-T.eta[i])
386
+ : v ? plogis(-T.eta[i]) : plogis(C.eta[i])));
387
+ }
388
+ }
389
+ if (!converged)
390
+ warnings.push(NOT_CONVERGED[method]);
391
+ if (stabilize && method === "glm") {
392
+ const share = [control.length / n, treated.length / n];
393
+ weights = weights.map((w, i) => w * share[t[i]]);
394
+ }
395
+ if (weights.every((w) => Math.abs(w - 1) < Math.sqrt(EPS))) {
396
+ warnings.push("All weights are 1, possibly indicating an estimation failure.");
397
+ }
398
+ return reported("weightit", {
399
+ weights, ps, treat: t, estimand, method, link, stabilized: stabilize && method === "glm", focal, columnNames: names,
400
+ converged, warnings,
401
+ });
402
+ }
403
+ /** The weights with the extremes of the units in `rows` capped as trim() does; null when `at` is the number of units
404
+ * or more (R warns and does not trim) */
405
+ function trimmed(w, rows, at, lower) {
406
+ const out = w.slice();
407
+ if (rows.length === 0)
408
+ return out;
409
+ const v = rows.map((i) => w[i]);
410
+ let hi, lo;
411
+ if (at < 1) {
412
+ // R reads a quantile below 0.5 as its complement (0.1 trims the top 10%, as 0.9)
413
+ const q = at < 0.5 ? 1 - at : at;
414
+ hi = quantile(v, q, { type: 3 });
415
+ lo = quantile(v, 1 - q, { type: 3 });
416
+ }
417
+ else {
418
+ if (!Number.isInteger(at))
419
+ throw new RangeError("'at' must be below 1 or a whole number");
420
+ if (at >= v.length)
421
+ return null;
422
+ // a count above half the units is read as its complement (8 of 10 trims the top 2), as R
423
+ const k = at > v.length / 2 ? v.length - at : at;
424
+ const s = v.slice().sort((a, b) => a - b);
425
+ hi = s[s.length - 1 - k];
426
+ lo = s[k];
427
+ }
428
+ for (const i of rows) {
429
+ if (w[i] > hi)
430
+ out[i] = hi;
431
+ if (lower && w[i] < lo)
432
+ out[i] = lo;
433
+ }
434
+ return out;
435
+ }
436
+ /** R's warning when `at` counts as many weights as there are units to trim */
437
+ const tooMany = (n) => `\`at\` must be less than ${n}, the number of units. Weights will not be trimmed.`;
438
+ export function trimWeights(w, options) {
439
+ checkOptions(options, TRIM_WEIGHTS_KEYS, "trimWeights"); // generated: option-keys.mjs
440
+ const { at, lower = false } = options;
441
+ if (!(at > 0) || !Number.isFinite(at))
442
+ throw new RangeError("'at' must be a positive number");
443
+ if (Array.isArray(w) || ArrayBuffer.isView(w)) {
444
+ const v = Array.from(w);
445
+ if (options.treat !== undefined && options.treat.length !== v.length)
446
+ throw new RangeError("'treat' must have the length of 'w'");
447
+ const out = trimmed(v, v.map((_, i) => i), at, lower);
448
+ if (out === null) {
449
+ reportWarnings("trimWeights", [tooMany(v.length)]);
450
+ return v;
451
+ }
452
+ return out;
453
+ }
454
+ const fit = w;
455
+ const rows = fit.treat.flatMap((t, i) => (fit.focal === null || t !== fit.focal ? [i] : []));
456
+ const out = trimmed(fit.weights, rows, at, lower);
457
+ if (out === null)
458
+ return reported("trimWeights", { ...fit, weights: fit.weights.slice(), warnings: [tooMany(rows.length)] });
459
+ return { ...fit, weights: out, warnings: fit.warnings.slice() };
460
+ }
461
+ function groupSummary(w, index) {
462
+ const v = index.map((i) => w[i]);
463
+ const n = v.length;
464
+ let sum = 0, sum2 = 0;
465
+ for (const x of v) {
466
+ sum += x;
467
+ sum2 += x * x;
468
+ }
469
+ const mean = sum / n;
470
+ const ss = v.reduce((a, x) => a + (x - mean) * (x - mean), 0);
471
+ // all weights 0: r is undefined, and so the spread measures (R's NA)
472
+ const r = v.map((x) => (mean > 0 ? x / mean : NaN));
473
+ const order = v.map((_, k) => k).sort((a, b) => v[b] - v[a] || a - b).slice(0, 5).reverse();
474
+ return {
475
+ range: [Math.min(...v), Math.max(...v)],
476
+ top: { index: order.map((k) => index[k] + 1), weights: order.map((k) => v[k]) },
477
+ mean, coefOfVar: Math.sqrt(ss / (n - 1)) / mean, scaledMad: r.reduce((a, x) => a + Math.abs(x - 1), 0) / n,
478
+ negativeEntropy: r.reduce((a, x) => a + (Number.isNaN(x) ? NaN : x > 0 ? x * Math.log(x) : 0), 0) / n,
479
+ // R counts the weights below about 1e-10 as zeros (weightit.json: 7.9e-11 counted, 1.7e-10 not)
480
+ numZeros: v.filter((x) => Math.abs(x) < 1e-10).length, n, ess: (sum * sum) / sum2,
481
+ };
482
+ }
483
+ /**
484
+ * Summary of balancing weights by group: range, largest weights, coefficient of variation, scaled MAD, negative
485
+ * entropy, zeros and Kish's effective sample size. Equivalent to `WeightIt::summary.weightit()` in R.
486
+ * @category Causal inference
487
+ */
488
+ export function weightSummary(w) {
489
+ const treated = w.treat.flatMap((t, i) => (t ? [i] : [])), control = w.treat.flatMap((t, i) => (t ? [] : [i]));
490
+ return { treated: groupSummary(w.weights, treated), control: groupSummary(w.weights, control), stabilized: w.stabilized };
491
+ }
package/dist/causal.js CHANGED
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.12.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
- import{b as $}from"./chunks/chunk-2P42OXYW.js";import"./chunks/chunk-4U65I4J2.js";import"./chunks/chunk-XQSYV3IZ.js";import"./chunks/chunk-4B7NEJCE.js";import{g as K}from"./chunks/chunk-DWVTVOQS.js";import"./chunks/chunk-O6OMXX5U.js";import{h as U}from"./chunks/chunk-NAACMR7H.js";import{l as C}from"./chunks/chunk-52KGBGFL.js";function k(r){let n=0;for(let u of r)Math.abs(u)>n&&(n=Math.abs(u));return n>0&&Number.isFinite(n)?Math.floor(Math.log2(n)):0}function B(r){let n=k(r),u=r.map(o=>U(o,-n)),s=u[0]??0,d=u.map(o=>o-s),l=k(d);return{values:d.map(o=>U(o,-l)),unitExp:n+l}}var Y=["estimand","M","caliper"];function z(r,n,u={}){C(u,Y,"match");let{estimand:s="ATT",M:d=1,caliper:l}=u,o=r.length;if(n.length!==o)throw new RangeError("length(Tr) != nrow(X)");if(s!=="ATT"&&s!=="ATE"&&s!=="ATC")throw new RangeError(`invalid 'estimand': ${String(s)}`);if(!Number.isInteger(d)||d<1)throw new RangeError("'M' must be a positive integer");if(l!==void 0&&!(l>0&&Number.isFinite(l)))throw new RangeError("'caliper' must be a positive number");let T=[];for(let a=0;a<o;a++){let g=r[a];if(g===!0||g===1)T.push(!0);else if(g===!1||g===0)T.push(!1);else throw typeof g=="number"&&Number.isNaN(g)?new RangeError("Match(): input includes NAs"):new RangeError("Treatment indicator ('Tr') must be a logical variable---i.e., TRUE (1) or FALSE (0)");if(!Number.isFinite(n[a]))throw new RangeError("Match(): input includes NAs")}if(!T.includes(!0)||!T.includes(!1))throw new RangeError("Treatment indicator ('Tr') must contain both treatment and control observations");let v=0;for(let a of n)v=Math.max(v,Math.abs(a));let i=v>0?Math.floor(Math.log2(v)):0,c=n.map(a=>U(a,-i)),S=null,w=1/0;if(l!==void 0){let{values:a,unitExp:g}=B(c),R=0;for(let M of a)R+=M;R/=o;let y=0;for(let M of a)y+=(M-R)*(M-R);let _=U(Math.sqrt(y/o),g);w=l*_,S=U(w,i)}let A=[new Array(o).fill(!1),new Array(o).fill(!1)],t=[],e=[],m=[],p=[],N=0,h=0;for(let a=0;a<o;a++){let g=T[a];if(g?s==="ATC":s==="ATT")continue;let R=A[g?0:1],y=[];for(let f=0;f<o;f++){if(T[f]===g)continue;let j=Math.abs(c[a]-c[f]);j>w||R[f]||y.push({j:f,d:j})}if(y.length<d){h++,m.push(a+1);continue}let M=y.map(f=>f.d).sort((f,j)=>f-j)[d-1],O=y.filter(f=>f.d<=M).map(f=>f.j),q;if(O.length===d)q=O;else{p.push(O.length),q=[],O=O.slice();for(let f=0;f<d;f++){let j=O.length,F=Math.min(j-1,Math.floor(j*(1-K())));q.push(O[F]),O.splice(F,1)}q.sort((f,j)=>f-j)}for(let f of q)R[f]=!0,t.push((g?a:f)+1),e.push((g?f:a)+1);N++}let E=new Set([...t,...e]),b=S===null?[]:m.filter(a=>!E.has(a)),x=[];return t.length===0&&x.push("'Match' object contains no valid matches (probably because of the caliper or the exact option)."),{indexTreated:t,indexControl:e,weights:t.map(()=>1/d),indexDropped:b.length>0?b:null,caliper:l??null,ecaliper:S,nobs:o,wnobs:N,ndrops:h,estimand:s,M:d,tieSizes:p,warnings:x}}var I=["match","weights","estimand","binary"],W=["factor"];function L(r){let n=new Array(r.nobs).fill(0);return r.indexTreated.forEach((u,s)=>{n[u-1]+=r.weights[s],n[r.indexControl[s]-1]+=r.weights[s]}),n}function H(r,n){if(r===!0||r===1)return!0;if(r===!1||r===0)return!1;throw new RangeError(`'tr' must be 0 or 1 (element ${n+1})`)}function D(r,n,u,s){let d=0,l=0,o=0;for(let i=0;i<r.length;i++){if(u[i]!==s)continue;let c=n===null?1:n[i];d+=c,l+=c*c,o+=c*r[i]}let T=o/d,v=0;for(let i=0;i<r.length;i++){if(u[i]!==s)continue;let c=n===null?1:n[i];v+=c*(r[i]-T)*(r[i]-T)}return[T,v/(d-l/d)]}function P(r,n,u={}){C(u,I,"balTab");let{match:s,binary:d="raw"}=u,l=s===void 0?u.weights:L(s),o=s?.estimand??u.estimand??"ATT",T=new Set(s?.indexDropped??[]),v=s!==void 0&&s.caliper!==null,i=r.length,c=r.map(H);if(!c.includes(!0)||!c.includes(!1))throw new RangeError("'tr' must contain both groups");if(l!==void 0&&l.length!==i)throw new RangeError("'weights' must have the length of 'tr'");let S=Object.keys(n),w={rows:S,type:[],diffUn:[],diffAdj:[],vRatioUn:[],vRatioAdj:[],observations:{rows:["All (ESS)","All (Unweighted)","Matched (ESS)","Matched (Unweighted)","Unmatched",...v?["Discarded"]:[]],control:[],treated:[]}};for(let A of S){let t=n[A];if(t.length!==i)throw new RangeError(`covariate '${A}' must have the length of 'tr'`);if(t.some(M=>!Number.isFinite(M)))throw new RangeError(`covariate '${A}' has missing or infinite values`);let e=new Set(t).size<=2&&t.every(M=>M===0||M===1),m=e?t:B(t).values,[p,N]=D(m,null,c,!0),[h,E]=D(m,null,c,!1),b=e?[p*(1-p),h*(1-h)]:[N,E],x=Math.sqrt(o==="ATT"?b[0]:o==="ATC"?b[1]:(b[0]+b[1])/2),a=e&&d==="raw"?1:x;if(w.type.push(e?"Binary":"Contin."),w.diffUn.push(p===h?0:(p-h)/a),w.vRatioUn.push(e||E===0?NaN:N/E),l===void 0){w.diffAdj.push(NaN),w.vRatioAdj.push(NaN);continue}let[g,R]=D(m,l,c,!0),[y,_]=D(m,l,c,!1);w.diffAdj.push(g===y?0:(g-y)/a),w.vRatioAdj.push(e||_===0?NaN:R/_)}for(let A of[!1,!0]){let t=0,e=0,m=0,p=0,N=0;for(let E=0;E<i;E++){if(c[E]!==A||(t++,T.has(E+1)&&N++,l===void 0))continue;let b=l[E];e+=b,m+=b*b,b>0&&p++}let h=l===void 0?[NaN,NaN,NaN]:[e*e/m,p,t-p-N];v&&h.push(N),(A?w.observations.treated:w.observations.control).push(t,t,...h)}return w}function X(r,n,u={}){C(u,W,"tableOneSmd");let{factor:s=!1}=u;if(r.length!==n.length)throw new RangeError("'x' and 'group' must have the same length");let d=[...new Set(n)].sort((t,e)=>t<e?-1:t>e?1:0);if(d.length!==2)throw new RangeError("'group' must have exactly two levels");let l=t=>t!==null&&!(typeof t=="number"&&Number.isNaN(t)),o=d.map(t=>r.filter((e,m)=>n[m]===t&&l(e)));if(!s){if(o.flat().some(h=>typeof h!="number"))throw new TypeError("'x' must be numeric unless factor: true");let t=B(o.flat()).values,m=[t.slice(0,o[0].length),t.slice(o[0].length)].map(h=>{let E=h.reduce((b,x)=>b+x,0)/h.length;return[E,h.reduce((b,x)=>b+(x-E)*(x-E),0)/(h.length-1)]}),p=m[1][0]-m[0][0],N=Math.sqrt((m[0][1]+m[1][1])/2);return p===0?0:Math.abs(p)/N}let T=[...new Set(o.flat())].sort((t,e)=>typeof t=="number"&&typeof e=="number"?t-e:String(t)<String(e)?-1:String(t)>String(e)?1:0),v=o.map(t=>T.slice(1).map(e=>t.filter(m=>m===e).length/t.length)),i=v[1].map((t,e)=>t-v[0][e]);if(i.every(t=>t===0))return 0;let c=i.length,S=Array.from({length:c},(t,e)=>Array.from({length:c},(m,p)=>{let N=h=>e===p?h[e]*(1-h[e]):-h[e]*h[p];return(N(v[0])+N(v[1]))/2}));if(S.every(t=>t.every(e=>e===0)))return NaN;let w=$(S),A=0;for(let t=0;t<c;t++)for(let e=0;e<c;e++)A+=i[t]*w[t][e]*i[e];return Math.sqrt(A)}export{P as balTab,z as match,L as matchWeights,X as tableOneSmd};
1
+ /*! rStats.js 1.14.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{a as H}from"./chunks/chunk-D25AVVVI.js";import"./chunks/chunk-ZWSHIUBZ.js";import{b as Q}from"./chunks/chunk-7VMGP2U7.js";import"./chunks/chunk-SEKOIW43.js";import"./chunks/chunk-3DA7CMFN.js";import{f as L}from"./chunks/chunk-AONDWNMF.js";import"./chunks/chunk-QLKZ2OFQ.js";import{d as $}from"./chunks/chunk-7BBIQY4W.js";import"./chunks/chunk-KITNZUYC.js";import"./chunks/chunk-F6KKW5YN.js";import"./chunks/chunk-EWNJT27V.js";import"./chunks/chunk-I2OTBVRK.js";import"./chunks/chunk-MJHFGGPU.js";import"./chunks/chunk-EDRBKZ3C.js";import{a as D}from"./chunks/chunk-DZQWGBTW.js";import{g as G,m as J,n as K,o as B}from"./chunks/chunk-6VY3XNAF.js";import"./chunks/chunk-PHDTVTKV.js";import"./chunks/chunk-3XUHCWLU.js";import"./chunks/chunk-62Y36UKH.js";import"./chunks/chunk-JCGCJT7T.js";import"./chunks/chunk-6HUTVWPO.js";import{r as V,s as U}from"./chunks/chunk-ZJJJDLRL.js";import{h as _}from"./chunks/chunk-B6NPCYFO.js";import{l as W}from"./chunks/chunk-TGXUU5NB.js";function Z(s){let i=0;for(let n of s)Math.abs(n)>i&&(i=Math.abs(n));return i>0&&Number.isFinite(i)?Math.floor(Math.log2(i)):0}function I(s){let i=Z(s),n=s.map(e=>_(e,-i)),r=n[0]??0,t=n.map(e=>e-r),p=Z(t);return{values:t.map(e=>_(e,-p)),unitExp:i+p}}var ce=["estimand","M","caliper"];function fe(s,i,n={}){W(n,ce,"match");let{estimand:r="ATT",M:t=1,caliper:p}=n,e=s.length;if(i.length!==e)throw new RangeError("length(Tr) != nrow(X)");if(r!=="ATT"&&r!=="ATE"&&r!=="ATC")throw new RangeError(`invalid 'estimand': ${String(r)}`);if(!Number.isInteger(t)||t<1)throw new RangeError("'M' must be a positive integer");if(p!==void 0&&!(p>0&&Number.isFinite(p)))throw new RangeError("'caliper' must be a positive number");let a=[];for(let u=0;u<e;u++){let b=s[u];if(b===!0||b===1)a.push(!0);else if(b===!1||b===0)a.push(!1);else throw typeof b=="number"&&Number.isNaN(b)?new RangeError("Match(): input includes NAs"):new RangeError("Treatment indicator ('Tr') must be a logical variable---i.e., TRUE (1) or FALSE (0)");if(!Number.isFinite(i[u]))throw new RangeError("Match(): input includes NAs")}if(!a.includes(!0)||!a.includes(!1))throw new RangeError("Treatment indicator ('Tr') must contain both treatment and control observations");let l=0;for(let u of i)l=Math.max(l,Math.abs(u));let c=l>0?Math.floor(Math.log2(l)):0,o=i.map(u=>_(u,-c)),d=null,N=1/0;if(p!==void 0){let{values:u,unitExp:b}=I(o),x=0;for(let E of u)x+=E;x/=e;let S=0;for(let E of u)S+=(E-x)*(E-x);let k=_(Math.sqrt(S/e),b);N=p*k,d=_(N,c)}let R=[new Array(e).fill(!1),new Array(e).fill(!1)],g=[],w=[],v=[],T=[],M=0,f=0;for(let u=0;u<e;u++){let b=a[u];if(b?r==="ATC":r==="ATT")continue;let x=R[b?0:1],S=[];for(let y=0;y<e;y++){if(a[y]===b)continue;let q=Math.abs(o[u]-o[y]);q>N||x[y]||S.push({j:y,d:q})}if(S.length<t){f++,v.push(u+1);continue}let E=S.map(y=>y.d).sort((y,q)=>y-q)[t-1],C=S.filter(y=>y.d<=E).map(y=>y.j),j;if(C.length===t)j=C;else{T.push(C.length),j=[],C=C.slice();for(let y=0;y<t;y++){let q=C.length,O=Math.min(q-1,Math.floor(q*(1-G())));j.push(C[O]),C.splice(O,1)}j.sort((y,q)=>y-q)}for(let y of j)x[y]=!0,g.push((b?u:y)+1),w.push((b?y:u)+1);M++}let h=new Set([...g,...w]),A=d===null?[]:v.filter(u=>!h.has(u)),m=[];return g.length===0&&m.push("'Match' object contains no valid matches (probably because of the caliper or the exact option)."),{indexTreated:g,indexControl:w,weights:g.map(()=>1/t),indexDropped:A.length>0?A:null,caliper:p??null,ecaliper:d,nobs:e,wnobs:M,ndrops:f,estimand:r,M:t,tieSizes:T,warnings:m}}var ue=["match","weightit","weights","estimand","levels","binary"],he=["factor"];function X(s){let i=new Array(s.nobs).fill(0);return s.indexTreated.forEach((n,r)=>{i[n-1]+=s.weights[r],i[s.indexControl[r]-1]+=s.weights[r]}),i}function me(s,i){if(s===!0||s===1)return!0;if(s===!1||s===0)return!1;throw new RangeError(`'tr' must be 0 or 1 (element ${i+1})`)}function F(s,i,n,r){let t=0,p=0,e=0;for(let c=0;c<s.length;c++){if(n[c]!==r)continue;let o=i===null?1:i[c];t+=o,p+=o*o,e+=o*s[c]}let a=e/t,l=0;for(let c=0;c<s.length;c++){if(n[c]!==r)continue;let o=i===null?1:i[c];l+=o*(s[c]-a)*(s[c]-a)}return[a,l/(t-p/t)]}function pe(s,i,n={}){W(n,ue,"balTab");let{match:r,weightit:t,binary:p="raw",levels:e={}}=n;if(r!==void 0&&t!==void 0)throw new RangeError("give 'match' or 'weightit', not both");let a=r!==void 0?X(r):t!==void 0?t.weights:n.weights,l=r?.estimand??t?.estimand??n.estimand??"ATT",c=new Set(r?.indexDropped??[]),o=r!==void 0&&r.caliper!==null,d=s.length,N=s.map(me);if(!N.includes(!0)||!N.includes(!1))throw new RangeError("'tr' must contain both groups");if(a!==void 0&&a.length!==d)throw new RangeError("'weights' must have the length of 'tr'");if(l==="ATO"&&a===void 0)throw new RangeError("estimand 'ATO' needs the weights");let R=[];t?.ps&&R.push(["prop.score",t.ps,"Distance"]);for(let[T,M]of Object.entries(i)){if(M.length!==d)throw new RangeError(`covariate '${T}' must have the length of 'tr'`);if(M.every(h=>typeof h=="number")){R.push([T,M,null]);continue}if(!M.every(h=>typeof h=="string"))throw new TypeError(`covariate '${T}' must be all numbers or all strings`);let f=e[T]??[...new Set(M)].sort(D);if(M.some(h=>!f.includes(h)))throw new RangeError(`covariate '${T}' has values not among its levels`);for(let h of f.length===2?f.slice(1):f)R.push([`${T}_${h}`,M.map(A=>A===h?1:0),null])}let g=N.map(()=>!0),w=t!==void 0,v={rows:R.map(([T])=>T),type:[],diffUn:[],diffAdj:[],vRatioUn:[],vRatioAdj:[],observations:{rows:w?["Unadjusted","Adjusted"]:["All (ESS)","All (Unweighted)","Matched (ESS)","Matched (Unweighted)","Unmatched",...o?["Discarded"]:[]],control:[],treated:[]}};for(let[T,M,f]of R){if(M.some(O=>!Number.isFinite(O)))throw new RangeError(`covariate '${T}' has missing or infinite values`);let h=f===null&&new Set(M).size<=2&&M.every(O=>O===0||O===1),A=h?null:I(M),m=A===null?M:A.values,[u,b]=F(m,null,N,!0),[x,S]=F(m,null,N,!1),k;if(l==="ATO"){let[O,P]=F(m,a,g,!0);k=Math.sqrt(h?O*(1-O):P)}else{let O=h?[u*(1-u),x*(1-x)]:[b,S];if(k=Math.sqrt(l==="ATT"?O[0]:l==="ATC"?O[1]:(O[0]+O[1])/2),_(k,A?.unitExp??0)<Math.sqrt(Number.EPSILON)){let[P,le]=F(m,null,g,!0);k=Math.sqrt(h?P*(1-P):le)}}let E=h&&p==="raw"?1:k;if(v.type.push(f??(h?"Binary":"Contin.")),v.diffUn.push(u===x?0:(u-x)/E),v.vRatioUn.push(h||S===0?NaN:b/S),a===void 0){v.diffAdj.push(NaN),v.vRatioAdj.push(NaN);continue}let[C,j]=F(m,a,N,!0),[y,q]=F(m,a,N,!1);v.diffAdj.push(C===y?0:(C-y)/E),v.vRatioAdj.push(h||q===0?NaN:j/q)}for(let T of[!1,!0]){let M=0,f=0,h=0,A=0,m=0;for(let x=0;x<d;x++){if(N[x]!==T||(M++,c.has(x+1)&&m++,a===void 0))continue;let S=a[x];f+=S,h+=S*S,S>0&&A++}let u=T?v.observations.treated:v.observations.control;if(w){u.push(M,f*f/h);continue}let b=a===void 0?[NaN,NaN,NaN]:[f*f/h,A,M-A-m];o&&b.push(m),u.push(M,M,...b)}return v}function de(s,i,n={}){W(n,he,"tableOneSmd");let{factor:r=!1}=n;if(s.length!==i.length)throw new RangeError("'x' and 'group' must have the same length");let t=[...new Set(i)].sort((g,w)=>g<w?-1:g>w?1:0);if(t.length!==2)throw new RangeError("'group' must have exactly two levels");let p=g=>g!==null&&!(typeof g=="number"&&Number.isNaN(g)),e=t.map(g=>s.filter((w,v)=>i[v]===g&&p(w)));if(!r){if(e.flat().some(f=>typeof f!="number"))throw new TypeError("'x' must be numeric unless factor: true");let g=I(e.flat()).values,v=[g.slice(0,e[0].length),g.slice(e[0].length)].map(f=>{let h=f.reduce((A,m)=>A+m,0)/f.length;return[h,f.reduce((A,m)=>A+(m-h)*(m-h),0)/(f.length-1)]}),T=v[1][0]-v[0][0],M=Math.sqrt((v[0][1]+v[1][1])/2);return T===0?0:Math.abs(T)/M}let a=[...new Set(e.flat())].sort((g,w)=>typeof g=="number"&&typeof w=="number"?g-w:String(g)<String(w)?-1:String(g)>String(w)?1:0),l=e.map(g=>a.slice(1).map(w=>g.filter(v=>v===w).length/g.length)),c=l[1].map((g,w)=>g-l[0][w]);if(c.every(g=>g===0))return 0;let o=c.length,d=Array.from({length:o},(g,w)=>Array.from({length:o},(v,T)=>{let M=f=>w===T?f[w]*(1-f[w]):-f[w]*f[T];return(M(l[0])+M(l[1]))/2}));if(d.every(g=>g.every(w=>w===0)))return NaN;let N=Q(d),R=0;for(let g=0;g<o;g++)for(let w=0;w<o;w++)R+=c[g]*N[g][w]*c[w];return Math.sqrt(R)}var ge=["method","link","estimand","stabilize"],we=["at","lower","treat"],z=Number.EPSILON;function be(s){return s.map((i,n)=>{if(i===!0||i===1)return 1;if(i===!1||i===0)return 0;throw new RangeError(`'tr' must be 0 or 1 (element ${n+1})`)})}function ve(s,i){let n=[],r=[],t={};for(let[p,e]of Object.entries(s)){if(e.length!==i)throw new RangeError(`covariate '${p}' must have the length of 'tr'`);if(e.every(c=>typeof c=="number")){let c=e;if(c.some(o=>!Number.isFinite(o)))throw new RangeError(`covariate '${p}' has missing or infinite values`);n.push(p),r.push(c.slice());continue}if(!e.every(c=>typeof c=="string"))throw new TypeError(`covariate '${p}' must be all numbers or all strings`);let a=e,l=[...new Set(a)].sort(D);t[p]=l;for(let c of l.slice(1))n.push(p+c),r.push(a.map(o=>o===c?1:0))}return{names:n,columns:r,factors:t}}function ee(s){return s.map(i=>{let n=i.reduce((t,p)=>t+p,0)/i.length,r=i.reduce((t,p)=>Math.max(t,Math.abs(p-n)),0);return i.map(t=>r>0?(t-n)/r:0)})}function Me(s){let i=s[0]?.length??0,n=[new Array(i).fill(1/Math.sqrt(i))],r=[];for(let t of s){let p=Math.sqrt(t.reduce((l,c)=>l+c*c,0)),e=t.slice();for(let l=0;l<2;l++)for(let c of n){let o=e.reduce((d,N,R)=>d+N*c[R],0);for(let d=0;d<i;d++)e[d]-=o*c[d]}let a=Math.sqrt(e.reduce((l,c)=>l+c*c,0));a>1e-7*p&&(n.push(e.map(l=>l/a)),r.push(t))}return r}function ae(s,i){let n=i.length,r=s.map((e,a)=>[...e,i[a]]),t=0;for(let e of s)for(let a of e)t=Math.max(t,Math.abs(a));for(let e=0;e<n;e++){let a=e;for(let l=e+1;l<n;l++)Math.abs(r[l][e])>Math.abs(r[a][e])&&(a=l);if(!(Math.abs(r[a][e])>1e-13*t))return null;[r[e],r[a]]=[r[a],r[e]];for(let l=e+1;l<n;l++){let c=r[l][e]/r[e][e];if(c!==0)for(let o=e;o<=n;o++)r[l][o]-=c*r[e][o]}}let p=new Array(n).fill(0);for(let e=n-1;e>=0;e--){let a=r[e][n];for(let l=e+1;l<n;l++)a-=r[e][l]*p[l];p[e]=a/r[e][e]}return p}function Y(s,i){return Array.from({length:i},(n,r)=>[1,...s.map(t=>t[r])])}function te(s,i,n){let r=n.length,t=new Array(r).fill(0);t[0]=Math.log(n[0]/i.length);let p=c=>{let o=0;for(let d of i)o+=Math.exp(s[d].reduce((N,R,g)=>N+R*c[g],0));return o-n.reduce((d,N,R)=>d+N*c[R],0)},e=p(t),a=!1,l=1e-13*Math.max(1,Math.abs(n[0]));for(let c=0;c<200;c++){let o=n.map(f=>-f),d=Array.from({length:r},()=>new Array(r).fill(0));for(let f of i){let h=s[f],A=Math.exp(h.reduce((m,u,b)=>m+u*t[b],0));for(let m=0;m<r;m++){o[m]+=A*h[m];for(let u=0;u<=m;u++)d[m][u]+=A*h[m]*h[u]}}for(let f=0;f<r;f++)for(let h=f+1;h<r;h++)d[f][h]=d[h][f];let N=Math.max(...o.map(Math.abs));if(N<=l){a=!0;break}let R=ae(d,o.map(f=>-f));if(R===null||R.some(f=>!Number.isFinite(f)))break;let g=1e-12*(Math.abs(e)+1),w=1,v=t.map((f,h)=>f+R[h]),T=p(v);for(;!(T<=e+g)&&w>1e-10;)w/=2,v=t.map((f,h)=>f+w*R[h]),T=p(v);if(!(T<=e+g))break;let M=R.some((f,h)=>Math.abs(w*f)>1e-15*Math.max(1,Math.abs(t[h])));if(t.splice(0,r,...v),e=T,!M){a=N<=1e-9*Math.max(1,Math.abs(n[0]));break}}return{eta:s.map(c=>c.reduce((o,d,N)=>o+d*t[N],0)),converged:a}}var Te={logit:{p:s=>$(s),q:s=>$(-s),d:s=>$(s)*$(-s)},probit:{p:s=>U(s),q:s=>U(-s),d:s=>V(s)}};function Ae(s,i,n,r,t){let p=i.length,e=t.length,a=t.slice(),l=w=>{let v=new Array(e).fill(0),T=Array.from({length:e},()=>new Array(e).fill(0));for(let M=0;M<p;M++){let f=s[M],h=f.reduce((k,E,C)=>k+E*w[C],0),A=r.p(h),m=r.q(h),u=r.d(h),b=i[M],x,S;n==="ATE"?(x=b?1/A:-1/m,S=b?-u/(A*A):-u/(m*m)):n==="ATT"?(x=b?1:-A/m,S=b?0:-u/(m*m)):n==="ATC"?(x=b?m/A:-1,S=b?-u/(A*A):0):(x=b?m:-A,S=-u);for(let k=0;k<e;k++){v[k]+=x*f[k];for(let E=0;E<e;E++)T[k][E]+=S*f[k]*f[E]}}return{g:v,J:T}},c=w=>w.reduce((v,T)=>v+T*T,0),{g:o,J:d}=l(a),N=c(o),R=!1,g=1e-12*p;for(let w=0;w<200;w++){if(Math.max(...o.map(Math.abs))<=g){R=!0;break}let v=ae(d,o.map(A=>-A));if(v===null||v.some(A=>!Number.isFinite(A)))break;let T=1,M=a.map((A,m)=>A+v[m]),f=l(M),h=c(f.g);for(;!(h<N)&&T>1e-10;)T/=2,M=a.map((A,m)=>A+T*v[m]),f=l(M),h=c(f.g);if(!(h<N)){R=Math.max(...o.map(Math.abs))<=1e-8*p;break}a=M,o=f.g,d=f.J,N=h}return{eta:s.map(w=>w.reduce((v,T,M)=>v+T*a[M],0)),converged:R}}function ne(s,i,n,r){switch(s){case"ATE":return i?1/n:1/r;case"ATT":return i?1:n/r;case"ATC":return i?r/n:1;default:return i?r:n}}var ye={glm:"glm.fit: algorithm did not converge",cbps:"The covariate balancing conditions could not be solved, so the covariates will not be exactly balanced.",ipt:"The optimization failed to converge; consider using fewer covariates or a different link function.",ebal:"The estimated weights do not balance the covariates, indicating the optimization arrived at a degenerate solution. Try decreasing the number of variables supplied to the optimization."},re={cbps:"covariate balancing propensity score weighting",ipt:"inverse probability tilting",ebal:"entropy balancing"};function Ee(s,i,n={}){W(n,ge,"weightit");let{method:r="glm",estimand:t="ATE",stabilize:p=!1}=n,e=r==="ps"?"glm":r;if(!["glm","cbps","ipt","ebal"].includes(e))throw new RangeError(`unknown method '${String(r)}'`);if(!["ATE","ATT","ATC","ATO"].includes(t))throw new RangeError(`unknown estimand '${String(t)}'`);let a=e==="ebal"?null:n.link??"logit";if(a!==null&&!{glm:["logit","probit","cauchit","cloglog"],cbps:["logit","probit"],ipt:["logit"]}[e].includes(a))throw new RangeError(`link '${a}' is not available for method '${e}'`);if((e==="ipt"||e==="ebal")&&t==="ATO")throw new RangeError(`"ATO" is not an allowable estimand for ${re[e]} with a binary treatment. Only "ATE", "ATT", and "ATC" are allowed.`);let c=[];if(p&&e==="glm"&&t!=="ATE")throw new RangeError('`stabilize` can only be supplied when `estimand = "ATE"`.');p&&e!=="glm"&&c.push(`\`stabilize\` cannot be used with ${re[e]} and will be ignored.`);let o=be(s),d=o.length;if(!o.includes(0)||!o.includes(1))throw new RangeError("The treatment must have at least two unique values.");let{names:N,columns:R}=ve(i,d);if(R.length===0)throw new RangeError("'covariates' must have at least one column");let g=Me(R.map(m=>I(m).values)),w=o.flatMap((m,u)=>m?[u]:[]),v=o.flatMap((m,u)=>m?[]:[u]),T=o.map((m,u)=>u),M=t==="ATT"?1:t==="ATC"?0:null,f=null,h,A=!0;if(e==="glm"){let m=B(()=>L(Y(g,d).map(u=>u.slice(1)),o,{family:"binomial",link:a}));A=m.converged,f=m.fittedValues.map((u,b)=>a==="logit"&&Math.abs(m.linearPredictors[b])>30?m.linearPredictors[b]>0?1-z:z:Math.min(Math.max(u,z),1-z)),h=o.map((u,b)=>ne(t,u,f[b],1-f[b])),f.some(u=>u<=10*z||u>=1-10*z)&&c.push("Propensity scores numerically equal to 0 or 1 were estimated, indicating perfect separation. These may yield problems with inference. See `?method_glm` (`?WeightIt::method_glm()`) for details.")}else if(e==="cbps"){let m=ee(g),u=Y(m,d),b=B(()=>L(u.map(E=>E.slice(1)),o,{family:"binomial",link:a})).coefficients.map(E=>Number.isFinite(E)?E:0),x=Te[a],S=Ae(u,o,t,x,b);A=S.converged;let k=E=>Math.min(Math.max(E,z),1-z);f=S.eta.map(E=>k(x.p(E))),h=o.map((E,C)=>ne(t,E,f[C],k(x.q(S.eta[C]))))}else{let m=ee(g),u=Y(m,d),b=C=>u[0].map((j,y)=>C.reduce((q,O)=>q+u[O][y],0)),x={C:t!=="ATC",T:t!=="ATT"},S=e==="ebal"&&t==="ATE"?{C:b(T),T:b(T)}:{C:b(w),T:b(v)},k=x.C?te(u,v,S.C):null,E=x.T?te(u,w,S.T):null;if(A=(k?.converged??!0)&&(E?.converged??!0),e==="ebal")h=o.map((C,j)=>C?E?Math.exp(E.eta[j]):1:k?Math.exp(k.eta[j]):1);else{let C=t==="ATE"?1:0;h=o.map((j,y)=>j?E?C+Math.exp(E.eta[y]):1:k?C+Math.exp(k.eta[y]):1),f=o.map((j,y)=>t==="ATT"?$(k.eta[y]):t==="ATC"?$(-E.eta[y]):j?$(-E.eta[y]):$(k.eta[y]))}}if(A||c.push(ye[e]),p&&e==="glm"){let m=[v.length/d,w.length/d];h=h.map((u,b)=>u*m[o[b]])}return h.every(m=>Math.abs(m-1)<Math.sqrt(z))&&c.push("All weights are 1, possibly indicating an estimation failure."),K("weightit",{weights:h,ps:f,treat:o,estimand:t,method:e,link:a,stabilized:p&&e==="glm",focal:M,columnNames:N,converged:A,warnings:c})}function oe(s,i,n,r){let t=s.slice();if(i.length===0)return t;let p=i.map(l=>s[l]),e,a;if(n<1){let l=n<.5?1-n:n;e=H(p,l,{type:3}),a=H(p,1-l,{type:3})}else{if(!Number.isInteger(n))throw new RangeError("'at' must be below 1 or a whole number");if(n>=p.length)return null;let l=n>p.length/2?p.length-n:n,c=p.slice().sort((o,d)=>o-d);e=c[c.length-1-l],a=c[l]}for(let l of i)s[l]>e&&(t[l]=e),r&&s[l]<a&&(t[l]=a);return t}var se=s=>`\`at\` must be less than ${s}, the number of units. Weights will not be trimmed.`;function Ne(s,i){W(i,we,"trimWeights");let{at:n,lower:r=!1}=i;if(!(n>0)||!Number.isFinite(n))throw new RangeError("'at' must be a positive number");if(Array.isArray(s)||ArrayBuffer.isView(s)){let a=Array.from(s);if(i.treat!==void 0&&i.treat.length!==a.length)throw new RangeError("'treat' must have the length of 'w'");let l=oe(a,a.map((c,o)=>o),n,r);return l===null?(J("trimWeights",[se(a.length)]),a):l}let t=s,p=t.treat.flatMap((a,l)=>t.focal===null||a!==t.focal?[l]:[]),e=oe(t.weights,p,n,r);return e===null?K("trimWeights",{...t,weights:t.weights.slice(),warnings:[se(p.length)]}):{...t,weights:e,warnings:t.warnings.slice()}}function ie(s,i){let n=i.map(o=>s[o]),r=n.length,t=0,p=0;for(let o of n)t+=o,p+=o*o;let e=t/r,a=n.reduce((o,d)=>o+(d-e)*(d-e),0),l=n.map(o=>e>0?o/e:NaN),c=n.map((o,d)=>d).sort((o,d)=>n[d]-n[o]||o-d).slice(0,5).reverse();return{range:[Math.min(...n),Math.max(...n)],top:{index:c.map(o=>i[o]+1),weights:c.map(o=>n[o])},mean:e,coefOfVar:Math.sqrt(a/(r-1))/e,scaledMad:l.reduce((o,d)=>o+Math.abs(d-1),0)/r,negativeEntropy:l.reduce((o,d)=>o+(Number.isNaN(d)?NaN:d>0?d*Math.log(d):0),0)/r,numZeros:n.filter(o=>Math.abs(o)<1e-10).length,n:r,ess:t*t/p}}function xe(s){let i=s.treat.flatMap((r,t)=>r?[t]:[]),n=s.treat.flatMap((r,t)=>r?[]:[t]);return{treated:ie(s.weights,i),control:ie(s.weights,n),stabilized:s.stabilized}}export{pe as balTab,fe as match,X as matchWeights,de as tableOneSmd,Ne as trimWeights,xe as weightSummary,Ee as weightit};
@@ -1,2 +1,2 @@
1
- /*! rStats.js 1.12.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
- import{b as A}from"./chunk-SLMS3FQD.js";var y=t=>new SyntaxError(`invalid formula: ${t}`),L=/^(?:[\p{L}\p{Nl}.]|(?![0-9])\p{Nd})[\p{L}\p{Nl}\p{Nd}\p{M}._]*/u;function R(t,u,i=!1){let a=[],n=0;for(;n<t.length;){let e=t[n];if(/\s/.test(e)){n++;continue}if(/[0-9]/.test(e)||e==="."&&/[0-9]/.test(t[n+1]??"")){let c=/^(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(t.slice(n));a.push({kind:"num",text:c[0]}),n+=c[0].length;continue}let r=L.exec(t.slice(n));if(r!==null){a.push({kind:"name",text:r[0]}),n+=r[0].length;continue}if(t.startsWith("%in%",n)){a.push({kind:"op",text:"%in%"}),n+=4;continue}if(u&&e==="|"){let c=t[n+1]==="|"?"||":"|";a.push({kind:"op",text:c}),n+=c.length;continue}if("~+-*/:^()".includes(e)||i&&e===","){a.push({kind:"op",text:e}),n++;continue}throw y(`unexpected '${e}'`)}return a.push({kind:"end"}),a}var T={"|":.5,"||":.5,"+":1,"-":1,"*":2,"/":2,"%in%":3,":":4,"^":6},C=5;function I(t,u=!1,i=!1,a=!1){if(typeof t!="string")throw new TypeError("the formula must be a string");let n=R(t,i,a),e=0,r=()=>n[e],c=()=>n[e++],f=(o,d)=>o.kind==="op"&&o.text===d;function m(){let o=c();if(o.kind==="name"){if(f(r(),"(")){if(o.text!=="Error"||!u)throw y(`function calls are not supported (${o.text})`);c();let d=g(0);if(!f(c(),")"))throw y("missing ')'");return{type:"Error",arg:d}}if(o.text===".")return{type:"dot"};if(/^\.[0-9]/.test(o.text))throw y(`unexpected '${o.text}'`);return{type:"var",name:o.text}}if(o.kind==="num")return{type:"num",value:Number(o.text),text:o.text};if(o.kind==="op"&&o.text==="("){let d=g(0);if(!f(c(),")"))throw y("missing ')'");return{type:"paren",arg:d}}if(o.kind==="op"&&(o.text==="-"||o.text==="+"))return{type:"unary",op:o.text,arg:g(C)};throw y(o.kind==="end"?"unexpected end of input":`unexpected '${o.kind==="op"?o.text:""}'`)}function g(o){let d=m();for(;;){let x=r();if(x.kind!=="op")break;let h=T[x.text];if(h===void 0||h<=o)break;c();let v=g(x.text==="^"?h-1:h);d=x.text==="|"||x.text==="||"?{type:"bar",double:x.text==="||",lhs:d,group:v}:{type:"binary",op:x.text,left:d,right:v}}return d}let b,l,s=n[0];if(a&&s.kind==="name"&&s.text==="cbind"&&f(n[1],"(")){let o=n[2],d=n[4],x=h=>h.kind==="name"&&h.text!=="."&&!/^\.[0-9]/.test(h.text);if(!(x(o)&&f(n[3],",")&&x(d)&&f(n[5],")")&&f(n[6],"~")))throw y("the response cbind() must have two column names: cbind(successes, failures)");l=[o.text,d.text],b=l[0],e=6}else if(!f(r(),"~")){let o=c();if(o.kind!=="name"||o.text==="."||!f(r(),"~"))throw y("the response must be a variable name followed by '~'");b=o.text}c();let p=g(0);if(r().kind!=="end")throw y("unexpected input after the formula");return l===void 0?{response:b,rhs:p}:{response:b,responseColumns:l,rhs:p}}function V(t){let u=[],i=e=>{if(e.type==="Error"){u.push(e.arg);return}if(e.type==="paren"){let r=i(e.arg);return r===void 0?void 0:{...e,arg:r}}if(e.type==="binary"&&e.op==="+"){let r=i(e.left),c=i(e.right);return r===void 0?c:c===void 0?r:{...e,left:r,right:c}}if(e.type==="binary"&&e.op==="-"){let r=i(e.left);return r===void 0?{type:"unary",op:"-",arg:e.right}:{...e,left:r}}return e},a=i(t),n=e=>{if(e.type==="Error")throw y("Error() must be a term of the right-hand side");e.type==="binary"?(n(e.left),n(e.right)):(e.type==="unary"||e.type==="paren")&&n(e.arg)};return a!==void 0&&n(a),u.forEach(n),{treatment:a,errors:u}}function Y(t){let u=[],i=e=>{switch(e.type){case"bar":u.push(e);return;case"paren":{let r=i(e.arg);return r===void 0?void 0:{...e,arg:r}}case"binary":if(e.op==="+"){let r=i(e.left),c=i(e.right);return r===void 0?c:c===void 0?r:{...e,left:r,right:c}}if(e.op==="-"){let r=i(e.left);return r===void 0?{type:"unary",op:"-",arg:e.right}:{...e,left:r}}return e;default:return e}},a=i(t),n=e=>{if(e.type==="bar")throw y("a random-effects term (lhs | group) must be a term of the right-hand side");e.type==="binary"?(n(e.left),n(e.right)):(e.type==="unary"||e.type==="paren"||e.type==="Error")&&n(e.arg)};a!==void 0&&n(a);for(let e of u)n(e.lhs),n(e.group);return{fixed:a,bars:u}}var M=new Set(["+","-","*","%in%"]);function w(t){switch(t.type){case"var":return t.name;case"dot":return".";case"num":return A(t.value);case"binary":{let u=w(t.left),i=w(t.right);return M.has(t.op)?`${u} ${t.op} ${i}`:`${u}${t.op}${i}`}case"unary":return`${t.op}${w(t.arg)}`;case"paren":return`(${w(t.arg)})`;case"Error":return`Error(${w(t.arg)})`;case"bar":return`${w(t.lhs)} ${t.double?"||":"|"} ${w(t.group)}`}}function k(t,u,i){if(t!==void 0)switch(t.type){case"var":i.includes(t.name)||i.push(t.name);return;case"dot":for(let a of u)i.includes(a)||i.push(a);return;case"num":return;case"binary":k(t.left,u,i),t.op!=="^"&&k(t.right,u,i);return;case"unary":case"paren":case"Error":k(t.arg,u,i);return;case"bar":k(t.lhs,u,i),k(t.group,u,i)}}function j(t,u){let i=[];return k(t,u,i),i}var N=t=>t.join(",");function E(t){let u=new Set;return t.filter(i=>{let a=N(i);return u.has(a)?!1:(u.add(a),!0)})}var $=(t,u)=>[...new Set([...t,...u])].sort((i,a)=>i-a);function B(t,u,i){let a=!0,n=(r,c)=>{switch(r.type){case"var":return[[u(r.name)]];case"dot":return i.map(f=>[u(f)]);case"num":if(r.value===1)a=!c;else if(r.value===0)a=c;else throw y(`a number (${r.text}) is not a term`);return[];case"paren":return n(r.arg,c);case"Error":throw y("Error() must be a term of the right-hand side");case"bar":throw y("a random-effects term (lhs | group) must be a term of the right-hand side");case"unary":return r.op==="+"?n(r.arg,c):(n(r.arg,!c),[]);case"binary":{if(r.op==="^"){let l=n(r.left,c),s=r.right;for(;s.type==="paren";)s=s.arg;let p=s.type==="num"?Math.trunc(s.value):NaN;if(!(p>=2&&p<=2147483647))throw new Error("invalid power in formula");let o=l;for(let d=1;d<p;d++){let x=[];for(let S of l)for(let O of o)x.push($(S,O));let h=E(x),v=h.length===o.length&&h.every((S,O)=>N(S)===N(o[O]));if(o=h,v)break}return o}if(r.op==="-"){let l=n(r.left,c),s=new Set(n(r.right,!c).map(N));return l.filter(p=>!s.has(N(p)))}let f=n(r.left,c),m=n(r.right,c);if(f.length===0&&r.op!=="+")return[];let g=()=>{let l=[];for(let s of f)for(let p of m)l.push($(s,p));return l},b=l=>l.reduce((s,p)=>$(s,p),[]);switch(r.op){case"+":return E([...f,...m]);case":":return E(g());case"*":return E([...f,...m,...g()]);case"/":{let l=b(f);return E([...f,...m.map(s=>$(s,l))])}case"%in%":{let l=b(m);return E(f.map(s=>$(s,l)))}}}}throw y("unsupported expression")};return{terms:t===void 0?[]:n(t,!1),intercept:a}}function z(t,u,i=t.rhs){let{response:a,responseColumns:n}=t,e=u.filter(s=>s!==a&&!(n?.includes(s)??!1)),r=a===void 0?[]:[a];n!==void 0&&n[1]!==a&&r.push(n[1]),k(t.rhs,e,r);let f=B(i,s=>r.indexOf(s),e),m=f.terms.map((s,p)=>[s,p]).sort((s,p)=>s[0].length-p[0].length||s[1]-p[1]).map(([s])=>s),g=[],b=a===void 0?-1:m.findIndex(s=>s.length===1&&s[0]===0);b>=0&&(g.push("the response appeared on the right-hand side and was dropped"),g.push(`problem with term ${b+1} in model.matrix: no columns are assigned`));let l=r.map(()=>m.map(()=>0));return m.forEach((s,p)=>{for(let o of s){let d=s.filter(h=>h!==o),x=d.length===0||m.slice(0,p).some(h=>d.every(v=>h.includes(v)));l[o][p]=x?1:2}}),{variables:r,response:a===void 0?-1:0,terms:m,termLabels:m.map(s=>s.map(p=>r[p]).join(":")),order:m.map(s=>s.length),intercept:f.intercept,factors:l,responseTerm:b,warnings:g}}export{I as a,V as b,Y as c,w as d,j as e,B as f,z as g};
1
+ /*! rStats.js 1.14.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
2
+ import{b as A}from"./chunk-PHDTVTKV.js";var y=t=>new SyntaxError(`invalid formula: ${t}`),L=/^(?:[\p{L}\p{Nl}.]|(?![0-9])\p{Nd})[\p{L}\p{Nl}\p{Nd}\p{M}._]*/u;function R(t,u,i=!1){let a=[],n=0;for(;n<t.length;){let e=t[n];if(/\s/.test(e)){n++;continue}if(/[0-9]/.test(e)||e==="."&&/[0-9]/.test(t[n+1]??"")){let c=/^(?:[0-9]+\.?[0-9]*|\.[0-9]+)(?:[eE][+-]?[0-9]+)?/.exec(t.slice(n));a.push({kind:"num",text:c[0]}),n+=c[0].length;continue}let r=L.exec(t.slice(n));if(r!==null){a.push({kind:"name",text:r[0]}),n+=r[0].length;continue}if(t.startsWith("%in%",n)){a.push({kind:"op",text:"%in%"}),n+=4;continue}if(u&&e==="|"){let c=t[n+1]==="|"?"||":"|";a.push({kind:"op",text:c}),n+=c.length;continue}if("~+-*/:^()".includes(e)||i&&e===","){a.push({kind:"op",text:e}),n++;continue}throw y(`unexpected '${e}'`)}return a.push({kind:"end"}),a}var T={"|":.5,"||":.5,"+":1,"-":1,"*":2,"/":2,"%in%":3,":":4,"^":6},C=5;function I(t,u=!1,i=!1,a=!1){if(typeof t!="string")throw new TypeError("the formula must be a string");let n=R(t,i,a),e=0,r=()=>n[e],c=()=>n[e++],f=(o,d)=>o.kind==="op"&&o.text===d;function m(){let o=c();if(o.kind==="name"){if(f(r(),"(")){if(o.text!=="Error"||!u)throw y(`function calls are not supported (${o.text})`);c();let d=g(0);if(!f(c(),")"))throw y("missing ')'");return{type:"Error",arg:d}}if(o.text===".")return{type:"dot"};if(/^\.[0-9]/.test(o.text))throw y(`unexpected '${o.text}'`);return{type:"var",name:o.text}}if(o.kind==="num")return{type:"num",value:Number(o.text),text:o.text};if(o.kind==="op"&&o.text==="("){let d=g(0);if(!f(c(),")"))throw y("missing ')'");return{type:"paren",arg:d}}if(o.kind==="op"&&(o.text==="-"||o.text==="+"))return{type:"unary",op:o.text,arg:g(C)};throw y(o.kind==="end"?"unexpected end of input":`unexpected '${o.kind==="op"?o.text:""}'`)}function g(o){let d=m();for(;;){let x=r();if(x.kind!=="op")break;let h=T[x.text];if(h===void 0||h<=o)break;c();let v=g(x.text==="^"?h-1:h);d=x.text==="|"||x.text==="||"?{type:"bar",double:x.text==="||",lhs:d,group:v}:{type:"binary",op:x.text,left:d,right:v}}return d}let b,l,s=n[0];if(a&&s.kind==="name"&&s.text==="cbind"&&f(n[1],"(")){let o=n[2],d=n[4],x=h=>h.kind==="name"&&h.text!=="."&&!/^\.[0-9]/.test(h.text);if(!(x(o)&&f(n[3],",")&&x(d)&&f(n[5],")")&&f(n[6],"~")))throw y("the response cbind() must have two column names: cbind(successes, failures)");l=[o.text,d.text],b=l[0],e=6}else if(!f(r(),"~")){let o=c();if(o.kind!=="name"||o.text==="."||!f(r(),"~"))throw y("the response must be a variable name followed by '~'");b=o.text}c();let p=g(0);if(r().kind!=="end")throw y("unexpected input after the formula");return l===void 0?{response:b,rhs:p}:{response:b,responseColumns:l,rhs:p}}function V(t){let u=[],i=e=>{if(e.type==="Error"){u.push(e.arg);return}if(e.type==="paren"){let r=i(e.arg);return r===void 0?void 0:{...e,arg:r}}if(e.type==="binary"&&e.op==="+"){let r=i(e.left),c=i(e.right);return r===void 0?c:c===void 0?r:{...e,left:r,right:c}}if(e.type==="binary"&&e.op==="-"){let r=i(e.left);return r===void 0?{type:"unary",op:"-",arg:e.right}:{...e,left:r}}return e},a=i(t),n=e=>{if(e.type==="Error")throw y("Error() must be a term of the right-hand side");e.type==="binary"?(n(e.left),n(e.right)):(e.type==="unary"||e.type==="paren")&&n(e.arg)};return a!==void 0&&n(a),u.forEach(n),{treatment:a,errors:u}}function Y(t){let u=[],i=e=>{switch(e.type){case"bar":u.push(e);return;case"paren":{let r=i(e.arg);return r===void 0?void 0:{...e,arg:r}}case"binary":if(e.op==="+"){let r=i(e.left),c=i(e.right);return r===void 0?c:c===void 0?r:{...e,left:r,right:c}}if(e.op==="-"){let r=i(e.left);return r===void 0?{type:"unary",op:"-",arg:e.right}:{...e,left:r}}return e;default:return e}},a=i(t),n=e=>{if(e.type==="bar")throw y("a random-effects term (lhs | group) must be a term of the right-hand side");e.type==="binary"?(n(e.left),n(e.right)):(e.type==="unary"||e.type==="paren"||e.type==="Error")&&n(e.arg)};a!==void 0&&n(a);for(let e of u)n(e.lhs),n(e.group);return{fixed:a,bars:u}}var M=new Set(["+","-","*","%in%"]);function w(t){switch(t.type){case"var":return t.name;case"dot":return".";case"num":return A(t.value);case"binary":{let u=w(t.left),i=w(t.right);return M.has(t.op)?`${u} ${t.op} ${i}`:`${u}${t.op}${i}`}case"unary":return`${t.op}${w(t.arg)}`;case"paren":return`(${w(t.arg)})`;case"Error":return`Error(${w(t.arg)})`;case"bar":return`${w(t.lhs)} ${t.double?"||":"|"} ${w(t.group)}`}}function k(t,u,i){if(t!==void 0)switch(t.type){case"var":i.includes(t.name)||i.push(t.name);return;case"dot":for(let a of u)i.includes(a)||i.push(a);return;case"num":return;case"binary":k(t.left,u,i),t.op!=="^"&&k(t.right,u,i);return;case"unary":case"paren":case"Error":k(t.arg,u,i);return;case"bar":k(t.lhs,u,i),k(t.group,u,i)}}function j(t,u){let i=[];return k(t,u,i),i}var N=t=>t.join(",");function E(t){let u=new Set;return t.filter(i=>{let a=N(i);return u.has(a)?!1:(u.add(a),!0)})}var $=(t,u)=>[...new Set([...t,...u])].sort((i,a)=>i-a);function B(t,u,i){let a=!0,n=(r,c)=>{switch(r.type){case"var":return[[u(r.name)]];case"dot":return i.map(f=>[u(f)]);case"num":if(r.value===1)a=!c;else if(r.value===0)a=c;else throw y(`a number (${r.text}) is not a term`);return[];case"paren":return n(r.arg,c);case"Error":throw y("Error() must be a term of the right-hand side");case"bar":throw y("a random-effects term (lhs | group) must be a term of the right-hand side");case"unary":return r.op==="+"?n(r.arg,c):(n(r.arg,!c),[]);case"binary":{if(r.op==="^"){let l=n(r.left,c),s=r.right;for(;s.type==="paren";)s=s.arg;let p=s.type==="num"?Math.trunc(s.value):NaN;if(!(p>=2&&p<=2147483647))throw new Error("invalid power in formula");let o=l;for(let d=1;d<p;d++){let x=[];for(let S of l)for(let O of o)x.push($(S,O));let h=E(x),v=h.length===o.length&&h.every((S,O)=>N(S)===N(o[O]));if(o=h,v)break}return o}if(r.op==="-"){let l=n(r.left,c),s=new Set(n(r.right,!c).map(N));return l.filter(p=>!s.has(N(p)))}let f=n(r.left,c),m=n(r.right,c);if(f.length===0&&r.op!=="+")return[];let g=()=>{let l=[];for(let s of f)for(let p of m)l.push($(s,p));return l},b=l=>l.reduce((s,p)=>$(s,p),[]);switch(r.op){case"+":return E([...f,...m]);case":":return E(g());case"*":return E([...f,...m,...g()]);case"/":{let l=b(f);return E([...f,...m.map(s=>$(s,l))])}case"%in%":{let l=b(m);return E(f.map(s=>$(s,l)))}}}}throw y("unsupported expression")};return{terms:t===void 0?[]:n(t,!1),intercept:a}}function z(t,u,i=t.rhs){let{response:a,responseColumns:n}=t,e=u.filter(s=>s!==a&&!(n?.includes(s)??!1)),r=a===void 0?[]:[a];n!==void 0&&n[1]!==a&&r.push(n[1]),k(t.rhs,e,r);let f=B(i,s=>r.indexOf(s),e),m=f.terms.map((s,p)=>[s,p]).sort((s,p)=>s[0].length-p[0].length||s[1]-p[1]).map(([s])=>s),g=[],b=a===void 0?-1:m.findIndex(s=>s.length===1&&s[0]===0);b>=0&&(g.push("the response appeared on the right-hand side and was dropped"),g.push(`problem with term ${b+1} in model.matrix: no columns are assigned`));let l=r.map(()=>m.map(()=>0));return m.forEach((s,p)=>{for(let o of s){let d=s.filter(h=>h!==o),x=d.length===0||m.slice(0,p).some(h=>d.every(v=>h.includes(v)));l[o][p]=x?1:2}}),{variables:r,response:a===void 0?-1:0,terms:m,termLabels:m.map(s=>s.map(p=>r[p]).join(":")),order:m.map(s=>s.length),intercept:f.intercept,factors:l,responseTerm:b,warnings:g}}export{I as a,V as b,Y as c,w as d,j as e,B as f,z as g};