@numero-uno-jpn/rstats 1.15.0 → 1.17.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 (96) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/README.ja.md +8 -8
  3. package/README.md +8 -8
  4. package/dist/causal/mediate.d.ts +146 -0
  5. package/dist/causal/mediate.js +399 -0
  6. package/dist/causal/mediationProcedures.d.ts +231 -0
  7. package/dist/causal/mediationProcedures.js +240 -0
  8. package/dist/causal/moderation.d.ts +148 -0
  9. package/dist/causal/moderation.js +165 -0
  10. package/dist/causal.js +2 -2
  11. package/dist/chunks/{chunk-FD375XBW.js → chunk-23QCIPET.js} +2 -2
  12. package/dist/chunks/chunk-3UEYA6VG.js +2 -0
  13. package/dist/chunks/{chunk-SMA62635.js → chunk-3Y4DNK4O.js} +2 -2
  14. package/dist/chunks/{chunk-L7HJGM52.js → chunk-4BGGWQWS.js} +2 -2
  15. package/dist/chunks/chunk-5UFVACSV.js +2 -0
  16. package/dist/chunks/{chunk-5BCXHJPF.js → chunk-5W2OZAHQ.js} +2 -2
  17. package/dist/chunks/{chunk-PZRABNMZ.js → chunk-6MLDKHTY.js} +2 -2
  18. package/dist/chunks/{chunk-XVRRYHLM.js → chunk-72I7GDWL.js} +2 -2
  19. package/dist/chunks/chunk-BWDXJL7T.js +2 -0
  20. package/dist/chunks/{chunk-VO3E4Q6H.js → chunk-DD2GG4EC.js} +1 -1
  21. package/dist/chunks/{chunk-CIBAGTO2.js → chunk-EB45CDFA.js} +2 -2
  22. package/dist/chunks/chunk-EIUK6TKF.js +2 -0
  23. package/dist/chunks/chunk-GIIURG5X.js +2 -0
  24. package/dist/chunks/chunk-GLABB425.js +2 -0
  25. package/dist/chunks/{chunk-OO22LZ7Q.js → chunk-GOYTZ5RB.js} +2 -2
  26. package/dist/chunks/{chunk-HF4TT233.js → chunk-GTSK4IN4.js} +1 -1
  27. package/dist/chunks/{chunk-SNQABDAT.js → chunk-I2KJMF4G.js} +1 -1
  28. package/dist/chunks/chunk-JG4TWDQ4.js +2 -0
  29. package/dist/chunks/{chunk-UFJFVNC6.js → chunk-JHABMYNH.js} +1 -1
  30. package/dist/chunks/chunk-JV3POOET.js +2 -0
  31. package/dist/chunks/chunk-K3YSXDTU.js +2 -0
  32. package/dist/chunks/{chunk-R74QJUYU.js → chunk-KY53MB3J.js} +2 -2
  33. package/dist/chunks/{chunk-AGA7JCRF.js → chunk-L77QFL3C.js} +2 -2
  34. package/dist/chunks/chunk-LKKUUREA.js +2 -0
  35. package/dist/chunks/{chunk-WL3JGBLZ.js → chunk-LY2UZGUL.js} +2 -2
  36. package/dist/chunks/chunk-NCDPZSI2.js +2 -0
  37. package/dist/chunks/{chunk-6SZLUVSL.js → chunk-NCRL33PQ.js} +2 -2
  38. package/dist/chunks/{chunk-RHNGF7R7.js → chunk-NPWWGIFG.js} +2 -2
  39. package/dist/chunks/chunk-O4D43LWM.js +2 -0
  40. package/dist/chunks/chunk-PSQ6MLJM.js +2 -0
  41. package/dist/chunks/{chunk-M3HFLMXL.js → chunk-QCPGV7XH.js} +2 -2
  42. package/dist/chunks/{chunk-JAXYZJV7.js → chunk-RM5D7Q7W.js} +2 -2
  43. package/dist/chunks/{chunk-IMSXMJ43.js → chunk-RNGDVSTS.js} +2 -2
  44. package/dist/chunks/{chunk-3K47QLCY.js → chunk-SA2E5GVO.js} +2 -2
  45. package/dist/chunks/{chunk-VHMFOILD.js → chunk-T5ZALLTJ.js} +2 -2
  46. package/dist/chunks/{chunk-GBNGGBU3.js → chunk-TTOJDLIQ.js} +2 -2
  47. package/dist/chunks/{chunk-FV4ZQPRI.js → chunk-V54MBEJM.js} +2 -2
  48. package/dist/chunks/chunk-VZSQAGL2.js +3 -0
  49. package/dist/chunks/{chunk-NULJXDAR.js → chunk-XEJX5HBJ.js} +2 -2
  50. package/dist/chunks/chunk-XPYZOG5H.js +2 -0
  51. package/dist/chunks/{chunk-4EH3O466.js → chunk-XR7Y4ZV6.js} +2 -2
  52. package/dist/chunks/{chunk-JGZSGGMD.js → chunk-YMI33F7W.js} +2 -2
  53. package/dist/chunks/{chunk-MKCPS5QQ.js → chunk-ZRKXHVTJ.js} +2 -2
  54. package/dist/descriptive.js +2 -2
  55. package/dist/distributions.js +2 -2
  56. package/dist/entries/causal.d.ts +3 -0
  57. package/dist/entries/causal.js +3 -0
  58. package/dist/entries/distributions.d.ts +1 -0
  59. package/dist/entries/distributions.js +1 -0
  60. package/dist/entries/regression.d.ts +3 -0
  61. package/dist/entries/regression.js +6 -0
  62. package/dist/linalg.js +2 -2
  63. package/dist/mixed.js +2 -2
  64. package/dist/models/betareg.d.ts +278 -0
  65. package/dist/models/betareg.js +588 -0
  66. package/dist/models/fitOptions.js +6 -4
  67. package/dist/models/loglin.d.ts +186 -0
  68. package/dist/models/loglin.js +349 -0
  69. package/dist/models/survreg.d.ts +43 -0
  70. package/dist/models/survreg.js +6 -3
  71. package/dist/models/tobit.d.ts +132 -0
  72. package/dist/models/tobit.js +172 -0
  73. package/dist/multivariate.js +2 -2
  74. package/dist/numerics.js +2 -2
  75. package/dist/random/mvrnorm.d.ts +60 -0
  76. package/dist/random/mvrnorm.js +237 -0
  77. package/dist/regression.js +3 -3
  78. package/dist/rstats.js +16 -16
  79. package/dist/special.js +2 -2
  80. package/dist/tests.js +15 -15
  81. package/dist/timeseries.js +2 -2
  82. package/package.json +1 -1
  83. package/dist/chunks/chunk-5JKKIVYL.js +0 -3
  84. package/dist/chunks/chunk-5Q5YVM7S.js +0 -2
  85. package/dist/chunks/chunk-AILN2NGE.js +0 -2
  86. package/dist/chunks/chunk-APOF7BLH.js +0 -2
  87. package/dist/chunks/chunk-HSVVCFEN.js +0 -2
  88. package/dist/chunks/chunk-KQGH6SEW.js +0 -2
  89. package/dist/chunks/chunk-OBTCIG5D.js +0 -2
  90. package/dist/chunks/chunk-P4TKSL4W.js +0 -2
  91. package/dist/chunks/chunk-RV4JZHTE.js +0 -2
  92. package/dist/chunks/chunk-U5UOVXKD.js +0 -2
  93. package/dist/chunks/chunk-VHBIWPB4.js +0 -2
  94. package/dist/chunks/chunk-YYLBBEWZ.js +0 -2
  95. package/dist/chunks/chunk-ZDUVFNFH.js +0 -2
  96. package/dist/chunks/chunk-ZUTVNRML.js +0 -2
@@ -0,0 +1,588 @@
1
+ // Beta regression: betareg's betareg (maximum likelihood, bias-corrected and bias-reduced) with summary, confint,
2
+ // predict and residuals. Behaviour: oracle/tobit-betareg-loglin-behaviour.md (clean room: from betareg's
3
+ // documentation, the papers it cites and the output of R; no source of R or of a package was read). Written for
4
+ // rStats.js.
5
+ import { pnorm, qnorm } from "../distributions/normal.js";
6
+ import { dbeta1, pbeta1, qbeta1 } from "../distributions/beta.js";
7
+ import { digamma, trigamma, psigamma } from "../special/psigamma.js";
8
+ import { parseFormula } from "./formula.js";
9
+ import { design } from "./modelMatrix.js";
10
+ import { dataRowCount } from "./inputRows.js";
11
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
12
+ import { checkOptions } from "../internal/checkOptions.js";
13
+ const BETAREG_KEYS = ["link", "linkPhi", "type", "weights", "contrasts", "maxit"];
14
+ const BETAREG_CONFINT_KEYS = ["level"];
15
+ const BETAREG_PREDICT_KEYS = ["newdata", "type", "at", "elementwise"];
16
+ const BETAREG_RESIDUALS_KEYS = ["type"];
17
+ const EPS = 2 ** -52;
18
+ /** A probability kept within (0, 1): the least double and the largest double below 1 at the ends */
19
+ const inUnit = (p) => Math.min(Math.max(p, Number.MIN_VALUE), 1 - 2 ** -53);
20
+ function meanLink(name) {
21
+ switch (name) {
22
+ case "logit": return {
23
+ fun: (m) => Math.log(m / (1 - m)),
24
+ inv: (e) => inUnit(e >= 0 ? 1 / (1 + Math.exp(-e)) : Math.exp(e) / (1 + Math.exp(e))),
25
+ d1: (e) => { const z = Math.exp(-Math.abs(e)); return z / ((1 + z) * (1 + z)); },
26
+ d2: (e) => { const z = Math.exp(-Math.abs(e)), m = 1 / (1 + z), d = z / ((1 + z) * (1 + z)); return d * (e >= 0 ? 1 - 2 * m : 2 * m - 1); },
27
+ };
28
+ case "probit": return {
29
+ fun: (m) => qnorm(m), inv: (e) => inUnit(pnorm(e)),
30
+ d1: (e) => Math.exp(-0.5 * e * e) / Math.sqrt(2 * Math.PI), d2: (e) => -e * Math.exp(-0.5 * e * e) / Math.sqrt(2 * Math.PI),
31
+ };
32
+ // cloglog and loglog: R's bias correction uses the second derivative of the inverse link floored at 2.2e-16 where
33
+ // it is negative (read off R's bias in intercept-only models, experiments/regression117-betareg-d2b.R; logit's
34
+ // negative values are used as they are). Kept as R: it changes BC and BR estimates by about 1e-4
35
+ case "cloglog": return {
36
+ fun: (m) => Math.log(-Math.log1p(-m)), inv: (e) => inUnit(-Math.expm1(-Math.exp(e))),
37
+ d1: (e) => Math.exp(e - Math.exp(e)), d2: (e) => Math.max(Math.exp(e - Math.exp(e)) * (1 - Math.exp(e)), EPS),
38
+ };
39
+ case "cauchit": return {
40
+ fun: (m) => Math.tan(Math.PI * (m - 0.5)), inv: (e) => inUnit(0.5 + Math.atan(e) / Math.PI),
41
+ d1: (e) => 1 / (Math.PI * (1 + e * e)), d2: (e) => -2 * e / (Math.PI * (1 + e * e) * (1 + e * e)),
42
+ };
43
+ // no clamp: a mean above 1 makes the log-likelihood NaN, as in R
44
+ case "log": return { fun: Math.log, inv: Math.exp, d1: Math.exp, d2: Math.exp };
45
+ case "loglog": return {
46
+ fun: (m) => -Math.log(-Math.log(m)), inv: (e) => inUnit(Math.exp(-Math.exp(-e))),
47
+ d1: (e) => Math.exp(-e - Math.exp(-e)), d2: (e) => Math.max(Math.exp(-e - Math.exp(-e)) * (Math.exp(-e) - 1), EPS),
48
+ };
49
+ default:
50
+ throw new RangeError("'arg' should be one of “logit”, “probit”, “cloglog”, “cauchit”, “log”, “loglog”");
51
+ }
52
+ }
53
+ function phiLink(name) {
54
+ switch (name) {
55
+ case "identity": return { fun: (m) => m, inv: (e) => e, d1: () => 1, d2: () => 0 };
56
+ case "log": return { fun: Math.log, inv: Math.exp, d1: Math.exp, d2: Math.exp };
57
+ case "sqrt": return { fun: Math.sqrt, inv: (e) => e * e, d1: (e) => 2 * e, d2: () => 2 };
58
+ default:
59
+ throw new RangeError("'arg' should be one of “identity”, “log”, “sqrt”");
60
+ }
61
+ }
62
+ function evaluate(th, m, l1, l2) {
63
+ const { x, z, y, weights } = m, p = x[0].length, q = z[0].length, k = p + q;
64
+ const score = new Array(k).fill(0), info = Array.from({ length: k }, () => new Array(k).fill(0));
65
+ const mu = [], phi = [], e1s = [], e2s = [];
66
+ let ll = 0;
67
+ for (let i = 0; i < y.length; i++) {
68
+ const xi = x[i], zi = z[i], w = weights[i];
69
+ let e1 = 0, e2 = 0;
70
+ for (let j = 0; j < p; j++)
71
+ e1 += xi[j] * th[j];
72
+ for (let j = 0; j < q; j++)
73
+ e2 += zi[j] * th[p + j];
74
+ const m1 = l1.inv(e1), f = l2.inv(e2);
75
+ mu.push(m1);
76
+ phi.push(f);
77
+ e1s.push(e1);
78
+ e2s.push(e2);
79
+ if (w === 0)
80
+ continue;
81
+ const a = m1 * f, b = (1 - m1) * f, yi = y[i];
82
+ ll += w * dbeta1(yi, a, b, true);
83
+ const d1 = l1.d1(e1), d2 = l2.d1(e2);
84
+ const ys = Math.log(yi) - Math.log1p(-yi), ms = digamma(a) - digamma(b);
85
+ const s1 = w * f * (ys - ms) * d1, s2 = w * (m1 * (ys - ms) + Math.log1p(-yi) - digamma(b) + digamma(f)) * d2;
86
+ const t1 = trigamma(a), t2 = trigamma(b);
87
+ const W = w * f * f * (t1 + t2) * d1 * d1, C = w * f * (t1 * m1 - t2 * (1 - m1)) * d1 * d2;
88
+ const D = w * (t1 * m1 * m1 + t2 * (1 - m1) * (1 - m1) - trigamma(f)) * d2 * d2;
89
+ for (let j = 0; j < p; j++)
90
+ score[j] += s1 * xi[j];
91
+ for (let j = 0; j < q; j++)
92
+ score[p + j] += s2 * zi[j];
93
+ for (let r = 0; r < k; r++) {
94
+ const ur = r < p ? xi[r] : zi[r - p];
95
+ for (let c = 0; c <= r; c++) {
96
+ const uc = c < p ? xi[c] : zi[c - p];
97
+ const v = r < p ? W : c < p ? C : D;
98
+ info[r][c] += v * ur * uc;
99
+ }
100
+ }
101
+ }
102
+ for (let r = 0; r < k; r++)
103
+ for (let c = r + 1; c < k; c++)
104
+ info[r][c] = info[c][r];
105
+ return { ll, score, info, mu, phi, e1: e1s, e2: e2s };
106
+ }
107
+ /** Inverse of a symmetric positive definite matrix (Cholesky); null if it is not. */
108
+ function spdInverse(A) {
109
+ const n = A.length, L = A.map(() => new Array(n).fill(0));
110
+ for (let i = 0; i < n; i++)
111
+ for (let j = 0; j <= i; j++) {
112
+ let s = A[i][j];
113
+ for (let k = 0; k < j; k++)
114
+ s -= L[i][k] * L[j][k];
115
+ if (i === j) {
116
+ if (!(s > 0))
117
+ return null;
118
+ L[i][i] = Math.sqrt(s);
119
+ }
120
+ else
121
+ L[i][j] = s / L[j][j];
122
+ }
123
+ const inv = A.map(() => new Array(n).fill(0));
124
+ for (let c = 0; c < n; c++) {
125
+ const zc = new Array(n).fill(0);
126
+ for (let i = 0; i < n; i++) {
127
+ let s = i === c ? 1 : 0;
128
+ for (let k = 0; k < i; k++)
129
+ s -= L[i][k] * zc[k];
130
+ zc[i] = s / L[i][i];
131
+ }
132
+ for (let i = n - 1; i >= 0; i--) {
133
+ let s = zc[i];
134
+ for (let k = i + 1; k < n; k++)
135
+ s -= L[k][i] * inv[k][c];
136
+ inv[i][c] = s / L[i][i];
137
+ }
138
+ }
139
+ return inv;
140
+ }
141
+ const matVec = (A, v) => A.map((row) => row.reduce((s, a, j) => s + a * v[j], 0));
142
+ /** The Kosmidis-Firth adjustment A(theta) = 1/2 tr(F^-1 (P_t + Q_t)) (see the behaviour file for the closed forms). */
143
+ function adjustment(th, m, l1, l2, Finv) {
144
+ const { x, z, y, weights } = m, p = x[0].length, q = z[0].length, k = p + q;
145
+ const A = new Array(k).fill(0);
146
+ for (let i = 0; i < y.length; i++) {
147
+ const w = weights[i];
148
+ if (w === 0)
149
+ continue;
150
+ const xi = x[i], zi = z[i];
151
+ let e1 = 0, e2 = 0;
152
+ for (let j = 0; j < p; j++)
153
+ e1 += xi[j] * th[j];
154
+ for (let j = 0; j < q; j++)
155
+ e2 += zi[j] * th[p + j];
156
+ const mu = l1.inv(e1), f = l2.inv(e2), a = mu * f, b = (1 - mu) * f;
157
+ const d1 = l1.d1(e1), d2 = l2.d1(e2), d1p = l1.d2(e1), d2p = l2.d2(e2);
158
+ // the scores in (eta1, eta2) are C (L - E L), L = (log y, log(1 - y))
159
+ const C = [[f * d1, -f * d1], [mu * d2, (1 - mu) * d2]];
160
+ const tf = trigamma(f), S = [[trigamma(a) - tf, -tf], [-tf, trigamma(b) - tf]];
161
+ const pf = psigamma(f, 2), kap = (r, s, t) => {
162
+ const ones = r + s + t;
163
+ return ones === 0 ? psigamma(a, 2) - pf : ones === 3 ? psigamma(b, 2) - pf : -pf;
164
+ };
165
+ // dC_a / deta_b
166
+ const dC = [[[f * d1p, -f * d1p], [d2 * d1, -d2 * d1]], [[d1 * d2, -d1 * d2], [mu * d2p, (1 - mu) * d2p]]];
167
+ const SC = [0, 1].map((c) => [0, 1].map((r) => S[r][0] * C[c][0] + S[r][1] * C[c][1])); // Sigma C_c'
168
+ // G = J F^-1 J' (2 x 2)
169
+ const J0 = [...xi, ...new Array(q).fill(0)], J1 = [...new Array(p).fill(0), ...zi];
170
+ const FJ0 = matVec(Finv, J0), FJ1 = matVec(Finv, J1);
171
+ const G = [[dot(J0, FJ0), dot(J0, FJ1)], [dot(J1, FJ0), dot(J1, FJ1)]];
172
+ for (let c = 0; c < 2; c++) {
173
+ let tr = 0;
174
+ for (let r = 0; r < 2; r++)
175
+ for (let s = 0; s < 2; s++) {
176
+ let M = 0;
177
+ for (let u = 0; u < 2; u++)
178
+ for (let v = 0; v < 2; v++)
179
+ for (let t = 0; t < 2; t++)
180
+ M += C[r][u] * C[s][v] * C[c][t] * kap(u, v, t);
181
+ const Q = dC[r][s][0] * SC[c][0] + dC[r][s][1] * SC[c][1];
182
+ tr += (M + Q) * G[r][s];
183
+ }
184
+ const Jc = c === 0 ? J0 : J1;
185
+ for (let t = 0; t < k; t++)
186
+ A[t] += 0.5 * w * tr * Jc[t];
187
+ }
188
+ }
189
+ return A;
190
+ }
191
+ /** Columns other than an intercept (all 1) centred (when there is one) and divided by a power of 2; `map` takes the
192
+ * coefficients of the scaled columns to those of the original ones. */
193
+ function scaleColumns(m) {
194
+ const k = m[0]?.length ?? 0, n = m.length;
195
+ const icpt = Array.from({ length: k }, (_, j) => m.every((r) => r[j] === 1)).indexOf(true);
196
+ const centre = Array.from({ length: k }, (_, j) => (j === icpt || icpt < 0 ? 0 : m.reduce((s, r) => s + r[j], 0) / n));
197
+ const exps = Array.from({ length: k }, (_, j) => {
198
+ if (j === icpt)
199
+ return 0;
200
+ let top = 0;
201
+ for (const r of m)
202
+ top = Math.max(top, Math.abs(r[j] - centre[j]));
203
+ return top > 0 && Number.isFinite(top) ? Math.floor(Math.log2(top)) : 0;
204
+ });
205
+ const scaled = m.map((r) => r.map((v, j) => (j === icpt ? v : (v - centre[j]) * 2 ** -exps[j])));
206
+ // the 2^-e factor as two halves, so that e near +-1074 does not under- or overflow
207
+ const pw = (e) => 2 ** Math.trunc(-e / 2) * 2 ** (-e - Math.trunc(-e / 2));
208
+ const map = Array.from({ length: k }, (_, a) => Array.from({ length: k }, (_, b) => {
209
+ if (a === b)
210
+ return a === icpt ? 1 : pw(exps[a]);
211
+ if (a === icpt && b !== icpt)
212
+ return -centre[b] * pw(exps[b]);
213
+ return 0;
214
+ }));
215
+ return { scaled, map };
216
+ }
217
+ function blockDiagonal(a, b) {
218
+ const p = a.length, q = b.length;
219
+ return Array.from({ length: p + q }, (_, i) => Array.from({ length: p + q }, (_, j) => i < p && j < p ? a[i][j] : i >= p && j >= p ? b[i - p][j - p] : 0));
220
+ }
221
+ const dot = (a, b) => a.reduce((s, v, j) => s + v * b[j], 0);
222
+ /** Splits "y ~ x | z" at its top-level bar. */
223
+ function splitBar(formula) {
224
+ let depth = 0;
225
+ for (let i = 0; i < formula.length; i++) {
226
+ const ch = formula[i];
227
+ if (ch === "(")
228
+ depth++;
229
+ else if (ch === ")")
230
+ depth--;
231
+ else if (ch === "|" && depth === 0)
232
+ return [formula.slice(0, i), formula.slice(i + 1)];
233
+ }
234
+ return [formula, undefined];
235
+ }
236
+ /**
237
+ * Beta regression for rates and proportions in (0, 1): the mean linked to a linear predictor, the precision phi
238
+ * constant (`y ~ x`) or linked to its own regressors (`y ~ x | z`), fitted by maximum likelihood, or bias-corrected or
239
+ * bias-reduced (Kosmidis and Firth 2010). Equivalent to R's `betareg::betareg()`.
240
+ *
241
+ * The response must lie strictly between 0 and 1 (R fits an extended-support distribution to 0 and 1; rStats.js does
242
+ * not). rStats.js maximises the likelihood to convergence by Fisher scoring; R stops its optimiser slightly earlier,
243
+ * so estimates agree with R's to about 1e-7 relative.
244
+ * @example
245
+ * ```ts
246
+ * const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
247
+ * fit.coefficients; // { mean: [-1.5409, 0.33424], precision: [62.03] }
248
+ * ```
249
+ * @category Regression
250
+ */
251
+ export function betareg(formula, data, options = {}) {
252
+ checkOptions(options, BETAREG_KEYS, "betareg"); // generated: option-keys.mjs
253
+ const type = options.type ?? "ML";
254
+ if (type !== "ML" && type !== "BC" && type !== "BR")
255
+ throw new RangeError("'arg' should be one of “ML”, “BC”, “BR”");
256
+ const linkName = options.link ?? "logit", l1 = meanLink(linkName);
257
+ const [meanPart, precPart] = splitBar(formula);
258
+ const linkPhiName = options.linkPhi ?? (precPart === undefined ? "identity" : "log"), l2 = phiLink(linkPhiName);
259
+ const maxit = options.maxit ?? 5000;
260
+ if (!Number.isInteger(maxit) || maxit < 1)
261
+ throw new RangeError("'maxit' must be a positive integer");
262
+ const parsed = parseFormula(meanPart);
263
+ if (parsed.response === undefined)
264
+ throw new TypeError("the formula must have a response");
265
+ const parsedZ = precPart === undefined ? undefined : parseFormula(`~ ${precPart}`);
266
+ const contrasts = (options.contrasts ?? {});
267
+ // the rows: those complete in every variable of both parts
268
+ const zVars = parsedZ === undefined ? [] : design(parsedZ, data, { contrasts }).terms.variables;
269
+ const dOpts = { contrasts, extraVariables: zVars };
270
+ if (options.weights !== undefined)
271
+ dOpts.weights = options.weights;
272
+ const d = design(parsed, data, dOpts);
273
+ const y = d.y;
274
+ if (y === undefined)
275
+ throw new TypeError("the response must be numeric");
276
+ if (y.some((v) => !(v >= 0 && v <= 1)))
277
+ throw new RangeError("invalid dependent variable, all observations must be in [0, 1]");
278
+ if (y.some((v) => v === 0 || v === 1)) {
279
+ throw new RangeError("the responses must lie strictly between 0 and 1: rStats.js fits the beta distribution only (R's betareg switches to the extended-support beta distribution \"xbetax\" for 0 and 1)");
280
+ }
281
+ const rows = d.frame.rows;
282
+ let z, zNames;
283
+ const factorLevels = {};
284
+ d.terms.variables.forEach((v, i) => { const fv = d.frame.variables[i]; if (i > 0 && fv?.kind === "factor")
285
+ factorLevels[v] = fv.levels; });
286
+ if (parsedZ === undefined) {
287
+ z = y.map(() => [1]);
288
+ zNames = ["(Intercept)"];
289
+ }
290
+ else {
291
+ const sub = {};
292
+ for (const v of zVars) {
293
+ const col = data[v];
294
+ if (col !== undefined)
295
+ sub[v] = rows.map((r) => col[r]);
296
+ }
297
+ const dz = design(parsedZ, sub, { contrasts });
298
+ if (dz.frame.rows.length !== rows.length)
299
+ throw new RangeError("the precision model drops rows that the mean model keeps");
300
+ z = dz.x;
301
+ zNames = dz.colNames;
302
+ dz.terms.variables.forEach((v, i) => { const fv = dz.frame.variables[i]; if (fv?.kind === "factor")
303
+ factorLevels[v] = fv.levels; });
304
+ }
305
+ const weights = d.frame.weights ?? y.map(() => 1);
306
+ if (weights.some((v) => !(v >= 0) || !Number.isFinite(v)))
307
+ throw new RangeError("weights must be finite and non-negative");
308
+ const x = d.x, p = x[0]?.length ?? 0, q = z[0].length, k = p + q;
309
+ if (p === 0)
310
+ throw new RangeError("the mean model has no coefficients");
311
+ // the fit is done on columns centred (with an intercept) and divided by a power of 2, so that it does not depend on
312
+ // the scale of a covariate (1e+-300) or on a large common value (1e15 + small differences); the coefficients, their
313
+ // covariance and the bias follow exactly (R fails from 1e150 and from a common value of 1e8: log 28)
314
+ if (weights.filter((w) => w > 0).length < k)
315
+ throw new RangeError("fewer observations than coefficients");
316
+ const sx = scaleColumns(x), sz = scaleColumns(z);
317
+ const model = {
318
+ meanRhs: parsed.rhs, precisionRhs: parsedZ?.rhs, factorLevels, contrasts,
319
+ variables: [...new Set([...d.terms.variables.slice(1), ...zVars])], x, z, y, weights, rows, xScaled: sx.scaled,
320
+ };
321
+ const fitModel = { ...model, x: sx.scaled, z: sz.scaled };
322
+ const back = blockDiagonal(sx.map, sz.map);
323
+ // R's starting values: weighted least squares of g(y) on X; phi from the delta method (Ferrari and Cribari-Neto 2004)
324
+ const gy = y.map((v) => l1.fun(v));
325
+ const XtX = Array.from({ length: p }, (_, a) => Array.from({ length: p }, (_, b) => sx.scaled.reduce((s, r, i) => s + weights[i] * r[a] * r[b], 0)));
326
+ const XtXi = spdInverse(XtX);
327
+ if (XtXi === null)
328
+ throw new RangeError("the mean model's matrix is rank-deficient");
329
+ const beta0 = matVec(XtXi, Array.from({ length: p }, (_, a) => sx.scaled.reduce((s, r, i) => s + weights[i] * r[a] * gy[i], 0)));
330
+ const eta0 = sx.scaled.map((r) => dot(r, beta0));
331
+ const sw = weights.reduce((s, v) => s + v, 0);
332
+ const sse = eta0.reduce((s, e, i) => s + weights[i] * (gy[i] - e) ** 2, 0) / (sw - p);
333
+ let phiSum = 0;
334
+ eta0.forEach((e, i) => { const m = l1.inv(e), s2 = sse * l1.d1(e) ** 2; phiSum += weights[i] * (m * (1 - m) / s2 - 1); });
335
+ // R's phi0 can be negative (weights summing to less than p, responses near 0 or 1, where R still fits): then the
336
+ // method of moments on y
337
+ let phi0 = phiSum / sw;
338
+ if (!(phi0 > 0) || !Number.isFinite(phi0)) {
339
+ const my = y.reduce((s, v, i) => s + weights[i] * v, 0) / sw, vy = y.reduce((s, v, i) => s + weights[i] * (v - my) ** 2, 0) / sw;
340
+ phi0 = vy > 0 && my * (1 - my) / vy - 1 > 0 ? my * (1 - my) / vy - 1 : 1;
341
+ }
342
+ let th = [...beta0, l2.fun(phi0), ...new Array(q - 1).fill(0)];
343
+ let cur = evaluate(th, fitModel, l1, l2);
344
+ if (!Number.isFinite(cur.ll))
345
+ throw new RangeError("initial value in 'vmmin' is not finite");
346
+ // Fisher scoring with step halving
347
+ let iterations = 0, converged = false;
348
+ const fisher = (target, accept) => {
349
+ for (let it = 0; it < maxit; it++) {
350
+ const Fi = spdInverse(cur.info);
351
+ if (Fi === null)
352
+ break;
353
+ const step = matVec(Fi, target(cur, th));
354
+ let t = 1, next, cand = th;
355
+ for (let h = 0; h < 60; h++) {
356
+ cand = th.map((v, j) => v + t * step[j]);
357
+ const e = evaluate(cand, fitModel, l1, l2);
358
+ if (Number.isFinite(e.ll) && e.phi.every((f) => f > 0) && accept(e, cur)) {
359
+ next = e;
360
+ break;
361
+ }
362
+ t /= 2;
363
+ }
364
+ iterations++;
365
+ if (next === undefined)
366
+ break;
367
+ const small = step.every((s, j) => Math.abs(t * s) <= 1e-12 * Math.max(1, Math.abs(th[j])));
368
+ th = cand;
369
+ cur = next;
370
+ if (small) {
371
+ converged = true;
372
+ break;
373
+ }
374
+ }
375
+ };
376
+ fisher((e) => e.score, (next, prev) => next.ll >= prev.ll - 1e-12 * Math.abs(prev.ll));
377
+ const warnings = [...d.warnings];
378
+ let bias;
379
+ if (type !== "ML") {
380
+ const Fi = spdInverse(cur.info);
381
+ if (Fi === null)
382
+ throw new RangeError("the expected information is singular");
383
+ if (type === "BC") {
384
+ const A = adjustment(th, fitModel, l1, l2, Fi);
385
+ const b = matVec(Fi, A).map((v) => -v);
386
+ th = th.map((v, j) => v - b[j]);
387
+ bias = matVec(back, b);
388
+ cur = evaluate(th, fitModel, l1, l2);
389
+ }
390
+ else {
391
+ converged = false;
392
+ fisher((e, t) => { const Fn = spdInverse(e.info); const A = adjustment(t, fitModel, l1, l2, Fn); return e.score.map((s, j) => s + A[j]); }, () => true);
393
+ }
394
+ }
395
+ if (!converged && type !== "BC")
396
+ warnings.push("the Fisher scoring did not converge");
397
+ const vcovScaled = spdInverse(cur.info);
398
+ if (vcovScaled === null)
399
+ throw new RangeError("the expected information is singular");
400
+ const vcov = back.map((r) => back.map((c) => r.reduce((acc, v, a) => acc + v * c.reduce((t, u, b2) => t + vcovScaled[a][b2] * u, 0), 0)));
401
+ th = matVec(back, th);
402
+ // pseudo R^2: squared weighted correlation of eta and g(y)
403
+ const mE = cur.e1.reduce((s, v, i) => s + weights[i] * v, 0) / sw, mY = gy.reduce((s, v, i) => s + weights[i] * v, 0) / sw;
404
+ let sxy = 0, sxx = 0, syy = 0;
405
+ cur.e1.forEach((e, i) => { const w = weights[i]; sxy += w * (e - mE) * (gy[i] - mY); sxx += w * (e - mE) ** 2; syy += w * (gy[i] - mY) ** 2; });
406
+ const nobs = weights.filter((w) => w > 0).length;
407
+ const precisionNames = parsedZ === undefined && linkPhiName === "identity" ? ["(phi)"] : zNames.map((nm) => `(phi)_${nm}`);
408
+ const result = {
409
+ coefficients: { mean: th.slice(0, p), precision: th.slice(p) }, meanNames: d.colNames.slice(), precisionNames,
410
+ names: [...d.colNames, ...precisionNames], vcov, loglik: cur.ll, pseudoRSquared: (sxy * sxy) / (sxx * syy),
411
+ fitted: cur.mu, linearPredictor: cur.e1, precision: cur.phi, link: linkName, linkPhi: linkPhiName, type,
412
+ n: y.length, nobs, dfNull: nobs - 2, dfResidual: nobs - k, iterations, converged, model, warnings,
413
+ };
414
+ if (bias !== undefined)
415
+ result.bias = bias;
416
+ return result;
417
+ }
418
+ /**
419
+ * Summary of a {@link betareg} fit: Wald tests of the mean and precision coefficients. Equivalent to
420
+ * `betareg::summary.betareg()` in R.
421
+ * @example
422
+ * ```ts
423
+ * const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
424
+ * betaregSummary(fit).mean.p; // [2.355e-12, 2.267e-14]
425
+ * ```
426
+ * @category Regression
427
+ */
428
+ export function betaregSummary(fit) {
429
+ const all = [...fit.coefficients.mean, ...fit.coefficients.precision];
430
+ const se = fit.vcov.map((r, j) => Math.sqrt(r[j]));
431
+ const table = (from, to, names) => {
432
+ const estimate = all.slice(from, to), s = se.slice(from, to), z = estimate.map((v, j) => v / s[j]);
433
+ return { names: names.slice(), estimate, se: s, z, p: z.map((v) => 2 * pnorm(-Math.abs(v))) };
434
+ };
435
+ const p = fit.coefficients.mean.length;
436
+ const r = betaregResiduals(fit, { type: "quantile" }).slice().sort((a, b) => a - b);
437
+ const quantile = (pr) => { const h = (r.length - 1) * pr, lo = Math.floor(h); return r[lo] + (h - lo) * ((r[lo + 1] ?? r[lo]) - r[lo]); };
438
+ return {
439
+ mean: table(0, p, fit.meanNames), precision: table(p, all.length, fit.precisionNames), loglik: fit.loglik,
440
+ df: all.length, aic: -2 * fit.loglik + 2 * all.length, pseudoRSquared: fit.pseudoRSquared, type: fit.type,
441
+ link: fit.link, linkPhi: fit.linkPhi, residuals: [0, 0.25, 0.5, 0.75, 1].map(quantile),
442
+ };
443
+ }
444
+ /**
445
+ * Wald confidence intervals of all coefficients of a {@link betareg} fit. Equivalent to R's
446
+ * `confint()`.
447
+ * @example
448
+ * ```ts
449
+ * const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
450
+ * betaregConfint(fit, { level: 0.9 });
451
+ * // { names: ["(Intercept)", "x", "(phi)"], lower: [-1.9023, 0.26223, 11.375], upper: [-1.1794, 0.40625, 112.68] }
452
+ * ```
453
+ * @category Regression
454
+ */
455
+ export function betaregConfint(fit, options = {}) {
456
+ checkOptions(options, BETAREG_CONFINT_KEYS, "betaregConfint"); // generated: option-keys.mjs
457
+ const level = options.level ?? 0.95;
458
+ if (!(level > 0 && level < 1))
459
+ throw new RangeError("'level' must be between 0 and 1");
460
+ const zq = qnorm((1 + level) / 2);
461
+ const all = [...fit.coefficients.mean, ...fit.coefficients.precision];
462
+ const se = fit.vcov.map((r, j) => Math.sqrt(r[j]));
463
+ return { names: fit.names.slice(), lower: all.map((v, j) => v - zq * se[j]), upper: all.map((v, j) => v + zq * se[j]) };
464
+ }
465
+ /**
466
+ * Predictions of a {@link betareg} fit: means, linear predictors, precisions, variances, or the density,
467
+ * distribution function or quantiles of the fitted beta distributions. Equivalent to
468
+ * `betareg::predict.betareg()` in R.
469
+ * @example
470
+ * ```ts
471
+ * const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
472
+ * betaregPredict(fit, { newdata: { x: [2.5, 9] } }); // [0.33064, 0.81265]
473
+ * betaregPredict(fit, { type: "quantile", at: [0.1, 0.9] }); // one row per observation: [[0.16414, 0.30026], ...]
474
+ * ```
475
+ * @category Regression
476
+ */
477
+ export function betaregPredict(fit, options = {}) {
478
+ checkOptions(options, BETAREG_PREDICT_KEYS, "betaregPredict"); // generated: option-keys.mjs
479
+ const type = options.type ?? "response";
480
+ const types = ["response", "link", "precision", "variance", "parameters", "density", "probability", "quantile"];
481
+ if (!types.includes(type))
482
+ throw new RangeError(`'arg' should be one of ${types.map((t) => `“${t}”`).join(", ")}`);
483
+ const l1 = meanLink(fit.link), l2 = phiLink(fit.linkPhi);
484
+ let e1, e2;
485
+ if (options.newdata === undefined) {
486
+ e1 = fit.linearPredictor.slice();
487
+ e2 = fit.precision.map((f) => l2.fun(f));
488
+ }
489
+ else {
490
+ const data = options.newdata, m = fit.model;
491
+ const nRows = dataRowCount(data, m.variables);
492
+ if (nRows === undefined)
493
+ throw new TypeError("cannot determine the number of rows in newdata");
494
+ const build = (rhs, names, constant) => {
495
+ if (constant || rhs === undefined)
496
+ return Array.from({ length: nRows }, () => [1]);
497
+ const dd = design({ response: undefined, rhs }, data, { levels: m.factorLevels, contrasts: m.contrasts });
498
+ if (dd.frame.rows.length !== nRows)
499
+ throw new RangeError("newdata has missing values");
500
+ const cols = names.map((nm) => dd.colNames.indexOf(nm));
501
+ if (cols.some((j) => j < 0))
502
+ throw new RangeError("newdata does not produce the fitted model matrix columns");
503
+ return dd.x.map((r) => cols.map((j) => r[j]));
504
+ };
505
+ const X = build(m.meanRhs, fit.meanNames, false);
506
+ const Z = build(m.precisionRhs, fit.precisionNames.map((nm) => (nm === "(phi)" ? "(Intercept)" : nm.slice(6))), m.precisionRhs === undefined);
507
+ e1 = X.map((r) => dot(r, fit.coefficients.mean));
508
+ e2 = Z.map((r) => dot(r, fit.coefficients.precision));
509
+ }
510
+ const mu = e1.map((e) => l1.inv(e)), phi = e2.map((e) => l2.inv(e));
511
+ switch (type) {
512
+ case "response": return mu;
513
+ case "link": return e1;
514
+ case "precision": return phi;
515
+ case "variance": return mu.map((m, i) => (m * (1 - m)) / (1 + phi[i]));
516
+ case "parameters": return mu.map((m, i) => [m, phi[i]]);
517
+ default: {
518
+ const at = typeof options.at === "number" ? [options.at] : Array.from(options.at ?? [0.5]);
519
+ const f = (v, i) => {
520
+ const a = mu[i] * phi[i], b = (1 - mu[i]) * phi[i];
521
+ return type === "density" ? dbeta1(v, a, b, false) : type === "probability" ? pbeta1(v, a, b, true, false) : qbeta1(v, a, b, true, false);
522
+ };
523
+ const elementwise = options.elementwise ?? (at.length === mu.length);
524
+ if (elementwise) {
525
+ if (at.length !== mu.length && at.length !== 1)
526
+ throw new RangeError("'at' must have one value per row for elementwise evaluation");
527
+ return mu.map((_, i) => f(at.length === 1 ? at[0] : at[i], i));
528
+ }
529
+ return mu.map((_, i) => at.map((v) => f(v, i)));
530
+ }
531
+ }
532
+ }
533
+ /**
534
+ * Residuals of a {@link betareg} fit (Espinheira, Ferrari and Cribari-Neto 2008; quantile residuals of Dunn and Smyth
535
+ * 1996). Every type but `"response"` is multiplied by the square root of the case weight, as R. Equivalent to
536
+ * `betareg::residuals.betareg()` in R.
537
+ * @example
538
+ * ```ts
539
+ * const fit = betareg("y ~ x", { y: [0.21, 0.35, 0.3, 0.52, 0.48, 0.66, 0.6, 0.81], x: [1, 2, 3, 4, 5, 6, 7, 8] });
540
+ * betaregResiduals(fit, { type: "sweighted2" }).slice(0, 3); // [-0.38464, 1.1271, -1.2608]
541
+ * ```
542
+ * @category Regression
543
+ */
544
+ export function betaregResiduals(fit, options = {}) {
545
+ checkOptions(options, BETAREG_RESIDUALS_KEYS, "betaregResiduals"); // generated: option-keys.mjs
546
+ const type = options.type ?? "quantile";
547
+ const types = ["quantile", "deviance", "pearson", "response", "weighted", "sweighted", "sweighted2"];
548
+ if (!types.includes(type))
549
+ throw new RangeError(`'arg' should be one of ${types.map((t) => `“${t}”`).join(", ")}`);
550
+ const { y, weights } = fit.model, mu = fit.fitted, phi = fit.precision;
551
+ if (type === "response")
552
+ return y.map((v, i) => v - mu[i]);
553
+ const h = type === "sweighted2" ? betaregHatvalues(fit) : undefined;
554
+ return y.map((v, i) => {
555
+ const m = mu[i], f = phi[i], a = m * f, b = (1 - m) * f, sw = Math.sqrt(weights[i]);
556
+ let r;
557
+ switch (type) {
558
+ case "quantile":
559
+ r = qnorm(pbeta1(v, a, b, true, false));
560
+ break;
561
+ case "pearson":
562
+ r = (v - m) / Math.sqrt((m * (1 - m)) / (1 + f));
563
+ break;
564
+ // |l(y | mean y) - l(y | mean mu)|: mean y is not the maximum, the difference can be negative (R takes abs)
565
+ case "deviance":
566
+ r = Math.sign(v - m) * Math.sqrt(2 * Math.abs(dbeta1(v, v * f, (1 - v) * f, true) - dbeta1(v, a, b, true)));
567
+ break;
568
+ default: {
569
+ const ys = Math.log(v) - Math.log1p(-v), ms = digamma(a) - digamma(b), vv = trigamma(a) + trigamma(b);
570
+ r = type === "weighted" ? (ys - ms) / Math.sqrt(f * vv) : type === "sweighted" ? (ys - ms) / Math.sqrt(vv) : (ys - ms) / Math.sqrt(vv * (1 - h[i]));
571
+ }
572
+ }
573
+ return sw * r;
574
+ });
575
+ }
576
+ /** Diagonal of the hat matrix W^1/2 X (X'WX)^-1 X' W^1/2, W = w phi (psi'(a) + psi'(b)) (dmu/deta)^2 */
577
+ function betaregHatvalues(fit) {
578
+ const { xScaled: x, weights } = fit.model, l1 = meanLink(fit.link), p = x[0].length;
579
+ const W = fit.fitted.map((m, i) => {
580
+ const f = fit.precision[i];
581
+ return weights[i] * f * (trigamma(m * f) + trigamma((1 - m) * f)) * l1.d1(fit.linearPredictor[i]) ** 2;
582
+ });
583
+ const XtWX = Array.from({ length: p }, (_, a) => Array.from({ length: p }, (_, b) => x.reduce((s, r, i) => s + W[i] * r[a] * r[b], 0)));
584
+ const inv = spdInverse(XtWX);
585
+ if (inv === null)
586
+ return x.map(() => NaN);
587
+ return x.map((r, i) => W[i] * dot(r, matVec(inv, r)));
588
+ }
@@ -1,14 +1,16 @@
1
1
  // The options a formula fit was given (weights, offset, family, contrasts, levels, ...), for the refits of step,
2
- // drop1 and add1. Kept beside the result, not in it, so that the result's shape does not change.
2
+ // drop1, add1 and mediate's bootstrap. Kept beside the result, not in it, so that the result's shape does not change:
3
+ // a non-enumerable property under a registered symbol, so that a fit made by one bundle of rStats.js (dist/rstats.js)
4
+ // is recognised by another (dist/causal.js), and a copy of the result (spread, structuredClone, JSON) does not carry it.
3
5
  //
4
6
  // Written for rStats.js (no ported code).
5
- const FIT_OPTIONS = new WeakMap();
7
+ const KEY = Symbol.for("rstats.js fit options");
6
8
  /** Records the options of a fit (a shallow copy) and returns the fit */
7
9
  export function setFitOptions(fit, options) {
8
- FIT_OPTIONS.set(fit, { ...options });
10
+ Object.defineProperty(fit, KEY, { value: Object.freeze({ ...options }), enumerable: false, configurable: true, writable: false });
9
11
  return fit;
10
12
  }
11
13
  /** The options a fit was given, if it came from lm or glm with a formula */
12
14
  export function fitOptions(fit) {
13
- return FIT_OPTIONS.get(fit);
15
+ return fit[KEY];
14
16
  }