@numero-uno-jpn/rstats 1.13.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 (63) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/README.ja.md +3 -3
  3. package/README.md +3 -3
  4. package/dist/causal.js +2 -2
  5. package/dist/chunks/{chunk-JJGRQ22M.js → chunk-2426YL2X.js} +2 -2
  6. package/dist/chunks/{chunk-GRXOLZ6J.js → chunk-3746VXPM.js} +2 -2
  7. package/dist/chunks/{chunk-2N7PIFPJ.js → chunk-3DA7CMFN.js} +2 -2
  8. package/dist/chunks/{chunk-24UIPUSE.js → chunk-3XUHCWLU.js} +1 -1
  9. package/dist/chunks/{chunk-JTARV4D3.js → chunk-4O6XLQBN.js} +2 -2
  10. package/dist/chunks/{chunk-TQ4P6W3P.js → chunk-62Y36UKH.js} +2 -2
  11. package/dist/chunks/{chunk-KOF2HBUV.js → chunk-6HUTVWPO.js} +2 -2
  12. package/dist/chunks/{chunk-CCYGRSQW.js → chunk-6VY3XNAF.js} +2 -2
  13. package/dist/chunks/{chunk-VO65CBCV.js → chunk-7BBIQY4W.js} +2 -2
  14. package/dist/chunks/{chunk-CKQOWTX7.js → chunk-7FGVMDJE.js} +2 -2
  15. package/dist/chunks/{chunk-2SOBG73L.js → chunk-7VMGP2U7.js} +2 -2
  16. package/dist/chunks/{chunk-LS55YUPZ.js → chunk-A5DZG7FH.js} +2 -2
  17. package/dist/chunks/{chunk-QWXSJEDI.js → chunk-AONDWNMF.js} +2 -2
  18. package/dist/chunks/{chunk-XRB552MP.js → chunk-AQHG7BEZ.js} +2 -2
  19. package/dist/chunks/{chunk-3T4TVNXS.js → chunk-B6NPCYFO.js} +2 -2
  20. package/dist/chunks/{chunk-NWWY2WMF.js → chunk-BCXYAILN.js} +2 -2
  21. package/dist/chunks/{chunk-C7NEFIAH.js → chunk-CKUBQW2A.js} +2 -2
  22. package/dist/chunks/{chunk-5Y425VAJ.js → chunk-D25AVVVI.js} +2 -2
  23. package/dist/chunks/{chunk-NRBTDLVW.js → chunk-DZQWGBTW.js} +2 -2
  24. package/dist/chunks/{chunk-UMLJFZJ5.js → chunk-EDRBKZ3C.js} +2 -2
  25. package/dist/chunks/{chunk-IIKFLH2E.js → chunk-EWNJT27V.js} +2 -2
  26. package/dist/chunks/{chunk-DZLOU6HK.js → chunk-F6KKW5YN.js} +2 -2
  27. package/dist/chunks/{chunk-RGEW3YLB.js → chunk-FPJ2CWLK.js} +2 -2
  28. package/dist/chunks/{chunk-ST6I33C6.js → chunk-H5GBKP57.js} +1 -1
  29. package/dist/chunks/{chunk-CEY7FHMZ.js → chunk-I2OTBVRK.js} +2 -2
  30. package/dist/chunks/{chunk-EWJS4VYF.js → chunk-IXFWR3LH.js} +2 -2
  31. package/dist/chunks/{chunk-M3LK23YR.js → chunk-JCGCJT7T.js} +1 -1
  32. package/dist/chunks/{chunk-GQ4HYF4L.js → chunk-KITNZUYC.js} +2 -2
  33. package/dist/chunks/{chunk-TTBKW2KL.js → chunk-MCEZRRQO.js} +2 -2
  34. package/dist/chunks/{chunk-7V6FRF32.js → chunk-MJHFGGPU.js} +2 -2
  35. package/dist/chunks/{chunk-CAOEREY3.js → chunk-MXOBCQQP.js} +2 -2
  36. package/dist/chunks/{chunk-OWD2GUXJ.js → chunk-NA7EDZ4Q.js} +2 -2
  37. package/dist/chunks/{chunk-2BXB6DRK.js → chunk-PHDTVTKV.js} +1 -1
  38. package/dist/chunks/{chunk-P6HSXCGZ.js → chunk-QLKZ2OFQ.js} +2 -2
  39. package/dist/chunks/{chunk-OVJU5WCL.js → chunk-SDIIGAY5.js} +2 -2
  40. package/dist/chunks/{chunk-CBAEKGP7.js → chunk-SEKOIW43.js} +2 -2
  41. package/dist/chunks/{chunk-AH6IVJRF.js → chunk-TGXUU5NB.js} +1 -1
  42. package/dist/chunks/{chunk-7ZKPFHAO.js → chunk-VWCCPBBG.js} +2 -2
  43. package/dist/chunks/{chunk-CSZCDPF3.js → chunk-XXH5OIUO.js} +2 -2
  44. package/dist/chunks/{chunk-Y4UWFH4Q.js → chunk-Y7VD43TO.js} +2 -2
  45. package/dist/chunks/{chunk-XRBNTYQW.js → chunk-YLUF4WTL.js} +2 -2
  46. package/dist/chunks/{chunk-P2UT6OCU.js → chunk-ZJJJDLRL.js} +2 -2
  47. package/dist/chunks/{chunk-DQ2MIFRQ.js → chunk-ZWSHIUBZ.js} +2 -2
  48. package/dist/descriptive.js +2 -2
  49. package/dist/distributions.js +2 -2
  50. package/dist/entries/regression.d.ts +1 -0
  51. package/dist/entries/regression.js +2 -0
  52. package/dist/linalg.js +2 -2
  53. package/dist/mixed.js +2 -2
  54. package/dist/models/multinom.d.ts +250 -0
  55. package/dist/models/multinom.js +520 -0
  56. package/dist/multivariate.js +2 -2
  57. package/dist/numerics.js +2 -2
  58. package/dist/regression.js +3 -3
  59. package/dist/rstats.js +1 -1
  60. package/dist/special.js +2 -2
  61. package/dist/tests.js +2 -2
  62. package/dist/timeseries.js +2 -2
  63. package/package.json +1 -1
@@ -0,0 +1,520 @@
1
+ // Multinomial logistic regression (baseline-category logits), nnet's multinom and its methods. The behaviour is in
2
+ // oracle/multinom-behaviour.md, from nnet's documentation and published output; Agresti (2013), "Categorical Data
3
+ // Analysis", 3rd ed., section 8.1. Written for rStats.js (no ported code).
4
+ //
5
+ // The maximum is found by Newton's method on the (penalised) log-likelihood to machine precision; nnet's BFGS stops
6
+ // earlier (about 1e-5 from the maximum by default), so the fixtures compare with R converged tightly.
7
+ import { pnorm, qnorm } from "../distributions/normal.js";
8
+ import { pchisq } from "../distributions/chisq.js";
9
+ import { runif } from "../random/continuous.js";
10
+ import { reported, unreported } from "../internal/warnings.js";
11
+ import { ldexp } from "../internal/summary.js";
12
+ import { parseFormula } from "./formula.js";
13
+ import { design } from "./modelMatrix.js";
14
+ import { dataRowCount } from "./inputRows.js";
15
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
16
+ import { checkOptions } from "../internal/checkOptions.js";
17
+ const MULTINOM_KEYS = ["weights", "decay", "levels", "contrasts", "maxit"];
18
+ const MULTINOM_CONFINT_KEYS = ["level"];
19
+ const MULTINOM_PREDICT_KEYS = ["newdata", "type"];
20
+ /** The penalised −log L, its gradient and Hessian (unpenalised and penalised) at the coefficients `b` (category-major) */
21
+ function evaluate(x, y, w, K, b, penalty) {
22
+ const p = x[0].length, P = (K - 1) * p;
23
+ let f = 0;
24
+ const g = new Array(P).fill(0);
25
+ const H = Array.from({ length: P }, () => new Array(P).fill(0));
26
+ const prob = new Array(K);
27
+ for (let i = 0; i < x.length; i++) {
28
+ const wi = w[i];
29
+ if (wi === 0)
30
+ continue;
31
+ const xi = x[i];
32
+ // softmax with the reference's logit 0, shifted by the largest
33
+ let top = 0;
34
+ const eta = [0];
35
+ for (let k = 1; k < K; k++) {
36
+ let e = 0;
37
+ for (let j = 0; j < p; j++)
38
+ e += xi[j] * b[(k - 1) * p + j];
39
+ eta.push(e);
40
+ if (e > top)
41
+ top = e;
42
+ }
43
+ let s = 0;
44
+ for (let k = 0; k < K; k++) {
45
+ prob[k] = Math.exp(eta[k] - top);
46
+ s += prob[k];
47
+ }
48
+ for (let k = 0; k < K; k++)
49
+ prob[k] /= s;
50
+ f -= wi * (eta[y[i]] - top - Math.log(s));
51
+ for (let k = 1; k < K; k++) {
52
+ const r = wi * (prob[k] - (y[i] === k ? 1 : 0));
53
+ for (let j = 0; j < p; j++)
54
+ g[(k - 1) * p + j] += r * xi[j];
55
+ for (let l = 1; l < K; l++) {
56
+ const c = wi * ((k === l ? prob[k] : 0) - prob[k] * prob[l]);
57
+ if (c === 0)
58
+ continue;
59
+ for (let j = 0; j < p; j++) {
60
+ const row = H[(k - 1) * p + j], cj = c * xi[j];
61
+ for (let jj = 0; jj < p; jj++)
62
+ row[(l - 1) * p + jj] += cj * xi[jj];
63
+ }
64
+ }
65
+ }
66
+ }
67
+ // the decay penalty b_k^T Pen b_k for each category's block
68
+ const Hp = H.map((row) => row.slice());
69
+ for (let k = 0; k < K - 1; k++)
70
+ for (let a = 0; a < p; a++)
71
+ for (let c = 0; c < p; c++) {
72
+ const v = penalty[a][c];
73
+ if (v === 0)
74
+ continue;
75
+ f += b[k * p + a] * v * b[k * p + c];
76
+ g[k * p + a] += 2 * v * b[k * p + c];
77
+ Hp[k * p + a][k * p + c] += 2 * v;
78
+ }
79
+ return { f, g, H, Hp };
80
+ }
81
+ /** Inverse of a symmetric positive definite matrix by Cholesky; null when it is not positive definite */
82
+ function spdInverse(A) {
83
+ const n = A.length;
84
+ const L = Array.from({ length: n }, () => new Array(n).fill(0));
85
+ for (let i = 0; i < n; i++) {
86
+ for (let j = 0; j <= i; j++) {
87
+ let s = A[i][j];
88
+ for (let k = 0; k < j; k++)
89
+ s -= L[i][k] * L[j][k];
90
+ if (i === j) {
91
+ if (!(s > 1e-14 * Math.abs(A[i][i])) || !Number.isFinite(s))
92
+ return null;
93
+ L[i][i] = Math.sqrt(s);
94
+ }
95
+ else
96
+ L[i][j] = s / L[j][j];
97
+ }
98
+ }
99
+ // inverse of L, then L^-T L^-1
100
+ const Li = Array.from({ length: n }, () => new Array(n).fill(0));
101
+ for (let i = 0; i < n; i++) {
102
+ Li[i][i] = 1 / L[i][i];
103
+ for (let j = 0; j < i; j++) {
104
+ let s = 0;
105
+ for (let k = j; k < i; k++)
106
+ s -= L[i][k] * Li[k][j];
107
+ Li[i][j] = s / L[i][i];
108
+ }
109
+ }
110
+ const V = Array.from({ length: n }, () => new Array(n).fill(0));
111
+ for (let i = 0; i < n; i++)
112
+ for (let j = 0; j <= i; j++) {
113
+ let s = 0;
114
+ for (let k = i; k < n; k++)
115
+ s += Li[k][i] * Li[k][j];
116
+ V[i][j] = s;
117
+ V[j][i] = s;
118
+ }
119
+ return V;
120
+ }
121
+ /** Indices of the columns that are neither constant nor in the span of the intercept and the earlier ones */
122
+ function estimable(x, intercept) {
123
+ const n = x.length, p = x[0]?.length ?? 0;
124
+ const basis = intercept >= 0 ? [new Array(n).fill(1 / Math.sqrt(n))] : [];
125
+ const kept = intercept >= 0 ? [intercept] : [];
126
+ for (let j = 0; j < p; j++) {
127
+ if (j === intercept)
128
+ continue;
129
+ const v = x.map((row) => row[j]);
130
+ const norm0 = Math.hypot(...v);
131
+ for (let pass = 0; pass < 2; pass++)
132
+ for (const e of basis) {
133
+ let dot = 0;
134
+ for (let i = 0; i < n; i++)
135
+ dot += e[i] * v[i];
136
+ for (let i = 0; i < n; i++)
137
+ v[i] -= dot * e[i];
138
+ }
139
+ const norm = Math.hypot(...v);
140
+ if (!(norm0 > 0) || !(norm > 1e-7 * norm0))
141
+ continue;
142
+ basis.push(v.map((e) => e / norm));
143
+ kept.push(j);
144
+ }
145
+ return kept.sort((a, c) => a - c);
146
+ }
147
+ /** Probabilities of every level at the coefficients (original units) for rows x */
148
+ function probabilities(x, coef) {
149
+ return x.map((xi) => {
150
+ const eta = [0, ...coef.map((row) => row.reduce((a, c, j) => a + c * xi[j], 0))];
151
+ const top = Math.max(...eta);
152
+ const e = eta.map((v) => Math.exp(v - top));
153
+ const s = e.reduce((a, v) => a + v, 0);
154
+ return e.map((v) => v / s);
155
+ });
156
+ }
157
+ /**
158
+ * Multinomial logistic regression: baseline-category logits for a response with two or more levels, the first level
159
+ * the reference. Equivalent to `nnet::multinom()` in R. The call followed is
160
+ * `multinom(y ~ ..., data, weights, decay, Hess = TRUE)`.
161
+ *
162
+ * The coefficients maximise the (weighted) log-likelihood less `decay` times the sum of squares of all coefficients,
163
+ * by Newton's method to machine precision; R's BFGS stops earlier (by default about 1e-5 from the maximum). The
164
+ * standard errors come from the Hessian of −log L (without the decay term, as R). A numeric response is made a factor;
165
+ * an unused level is dropped with R's warning; rows with missing values are dropped.
166
+ * @category Regression
167
+ * @example
168
+ * ```ts
169
+ * const data = { y: ["a", "b", "c", "b", "a", "c", "c", "a", "b", "a"], x: [1, 2, 3, 1.5, 2.2, 2.8, 1.9, 1.2, 3.1, 2.5] };
170
+ * const fit = multinom("y ~ x", data);
171
+ * fit.coefficients; // [[-2.503002448686904, 1.1313364602572131], [-4.9150873979421785, 2.1386561772142767]] (rows b, c)
172
+ * fit.deviance; // 18.97233634263671
173
+ * ```
174
+ */
175
+ export function multinom(formula, data, options = {}) {
176
+ checkOptions(options, MULTINOM_KEYS, "multinom"); // generated: option-keys.mjs
177
+ const { decay = 0, maxit = 100 } = options;
178
+ if (!(decay >= 0) || !Number.isFinite(decay))
179
+ throw new RangeError("'decay' must be a non-negative number");
180
+ if (!Number.isInteger(maxit) || maxit < 1)
181
+ throw new RangeError("'maxit' must be a positive integer");
182
+ const parsed = parseFormula(formula);
183
+ if (parsed.response === undefined)
184
+ throw new TypeError("the formula must have a response");
185
+ const designOptions = { anyResponse: true };
186
+ if (options.weights !== undefined)
187
+ designOptions.weights = options.weights;
188
+ if (options.levels !== undefined)
189
+ designOptions.levels = options.levels;
190
+ if (options.contrasts !== undefined)
191
+ designOptions.contrasts = options.contrasts;
192
+ const d = design(parsed, data, designOptions);
193
+ const response = d.frame.variables[0];
194
+ if (response === undefined)
195
+ throw new TypeError("the formula must have a response");
196
+ // a numeric response becomes a factor of its sorted distinct values, as R's as.factor
197
+ let levels, codes;
198
+ if (response.kind === "factor") {
199
+ levels = response.levels.slice();
200
+ codes = response.codes.slice();
201
+ }
202
+ else {
203
+ const distinct = [...new Set(response.values)].sort((a, b) => a - b);
204
+ levels = distinct.map(String);
205
+ codes = response.values.map((v) => distinct.indexOf(v));
206
+ }
207
+ const weights = d.frame.weights ?? new Array(codes.length).fill(1);
208
+ if (weights.some((v) => !Number.isFinite(v) || v < 0))
209
+ throw new RangeError("weights must be finite and non-negative");
210
+ // unused levels are dropped, as R ("group ‘D’ is empty")
211
+ const warnings = [...d.warnings];
212
+ const used = levels.map((_, k) => codes.some((c) => c === k));
213
+ for (let k = 0; k < levels.length; k++)
214
+ if (!used[k])
215
+ warnings.push(`group ‘${levels[k]}’ is empty`);
216
+ const remap = levels.map((_, k) => used.slice(0, k).filter(Boolean).length);
217
+ levels = levels.filter((_, k) => used[k]);
218
+ const y = codes.map((c) => remap[c]);
219
+ const K = levels.length;
220
+ if (K < 2)
221
+ throw new RangeError("need two or more classes to fit a multinom model");
222
+ const x = d.x;
223
+ if (x.some((row) => row.some((v) => !Number.isFinite(v))))
224
+ throw new RangeError("NA/NaN/Inf in the model matrix");
225
+ const p = x[0]?.length ?? 0;
226
+ if (p === 0)
227
+ throw new RangeError("the model has no coefficients");
228
+ const intercept = d.terms.intercept ? 0 : -1;
229
+ // each column other than the intercept is centred (with an intercept) and divided by a power of 2: the fit is well
230
+ // scaled for columns near 1e300 or 1e-300 and for a large common offset (1e15 + small differences); the original
231
+ // coefficients follow exactly in the scale, and the intercept absorbs the centring
232
+ const centre = Array.from({ length: p }, (_, j) => (j === intercept || intercept < 0 ? 0 : x.reduce((a, r) => a + r[j], 0) / x.length));
233
+ const exps = Array.from({ length: p }, (_, j) => {
234
+ if (j === intercept)
235
+ return 0;
236
+ let top = 0;
237
+ for (const row of x)
238
+ top = Math.max(top, Math.abs(row[j] - centre[j]));
239
+ return top > 0 ? Math.floor(Math.log2(top)) : 0;
240
+ });
241
+ const scaled = x.map((row) => row.map((v, j) => (j === intercept ? v : ldexp(v - centre[j], -exps[j]))));
242
+ // the estimable columns: not constant and not in the span of the intercept and the earlier columns (R's fit cannot
243
+ // identify them; rStats.js leaves them out with NaN coefficients, as polr)
244
+ const kept = estimable(scaled, intercept);
245
+ const dropped = d.colNames.filter((_, j) => !kept.includes(j));
246
+ if (dropped.length > 0)
247
+ warnings.push(`design appears to be rank-deficient, so dropping some coefs: ${dropped.join(", ")}`);
248
+ const q = kept.length, Q = (K - 1) * q;
249
+ const xs = scaled.map((row) => kept.map((j) => row[j]));
250
+ // original coefficients of a category: b_j = b'_j 2^-e_j (j not the intercept), b_0 = b'_0 - sum_j c_j b_j; the decay
251
+ // penalty decay |b|^2 is the quadratic form decay b'^T M^T M b' with M that map
252
+ const M = kept.map((ja) => kept.map((jb) => {
253
+ if (ja === jb)
254
+ return ja === intercept ? 1 : ldexp(1, -exps[ja]);
255
+ if (ja === intercept && jb !== intercept)
256
+ return -centre[jb] * ldexp(1, -exps[jb]);
257
+ return 0;
258
+ }));
259
+ const pen = kept.map((_, a) => kept.map((__, b) => (decay === 0 ? 0 : decay * M.reduce((sum, row) => sum + row[a] * row[b], 0))));
260
+ // start: the intercepts at the log odds of the levels against the reference (weighted), the rest 0
261
+ const counts = new Array(K).fill(0);
262
+ y.forEach((c, i) => { counts[c] += weights[i]; });
263
+ let b = new Array(Q).fill(0);
264
+ const ii = kept.indexOf(intercept);
265
+ if (ii >= 0 && counts.every((c) => c > 0))
266
+ for (let k = 1; k < K; k++)
267
+ b[(k - 1) * q + ii] = Math.log(counts[k] / counts[0]);
268
+ const totalWeight = weights.reduce((a, v) => a + v, 0);
269
+ const tol = 1e-10 * totalWeight;
270
+ let cur = evaluate(xs, y, weights, K, b, pen);
271
+ let converged = false, iter = 0;
272
+ for (; iter < maxit; iter++) {
273
+ if (Math.max(...cur.g.map(Math.abs)) <= tol) {
274
+ converged = true;
275
+ break;
276
+ }
277
+ const Hi = spdInverse(cur.Hp);
278
+ if (Hi === null)
279
+ break;
280
+ const step = Hi.map((row) => -row.reduce((a, v, r) => a + v * cur.g[r], 0));
281
+ // the decrease near the maximum falls below the rounding of the objective: a rise within it is accepted
282
+ const slack = 1e-12 * Math.abs(cur.f);
283
+ let t = 1, next = b.map((v, r) => v + step[r]), nxt = evaluate(xs, y, weights, K, next, pen);
284
+ while (!(nxt.f <= cur.f + slack) && t > 1e-10) {
285
+ t /= 2;
286
+ next = b.map((v, r) => v + t * step[r]);
287
+ nxt = evaluate(xs, y, weights, K, next, pen);
288
+ }
289
+ if (!(nxt.f <= cur.f + slack))
290
+ break;
291
+ const moved = step.some((v, r) => Math.abs(t * v) > 1e-15 * Math.max(1, Math.abs(b[r])));
292
+ b = next;
293
+ cur = nxt;
294
+ if (!moved) {
295
+ converged = Math.max(...cur.g.map(Math.abs)) <= 1e-7 * totalWeight;
296
+ iter++;
297
+ break;
298
+ }
299
+ }
300
+ // separated data: the likelihood rises towards a limit as some coefficients grow without bound, and the fitted
301
+ // probabilities reach 0 or 1 numerically (glm's test); the maximum does not exist
302
+ const fittedScaled = probabilities(xs, Array.from({ length: K - 1 }, (_, k) => b.slice(k * q, (k + 1) * q)));
303
+ if (converged && fittedScaled.some((r) => r.some((v) => v < 10 * Number.EPSILON))) {
304
+ converged = false;
305
+ warnings.push("fitted probabilities numerically 0 or 1 occurred: the maximum of the likelihood does not exist (separated data)");
306
+ }
307
+ else if (!converged)
308
+ warnings.push("the Newton iterations did not converge: the maximum of the likelihood may not exist (separated data)");
309
+ // back to the original units (NaN for the dropped columns)
310
+ const orig = (k) => kept.map((_, a) => M[a].reduce((sum, m, c) => sum + m * b[k * q + c], 0));
311
+ const coefficients = Array.from({ length: K - 1 }, (_, k) => {
312
+ const o = orig(k);
313
+ return Array.from({ length: p }, (_, j) => (kept.includes(j) ? o[kept.indexOf(j)] : NaN));
314
+ });
315
+ // the Hessian and the variance in the original units: H = Minv^T H' Minv, V = M V' M^T (block by block), with
316
+ // Minv[0][j] = c_j and Minv[j][j] = 2^e_j; a standard error from its own scaled variance (no under- or overflow)
317
+ const Minv = kept.map((ja) => kept.map((jb) => (ja === jb ? (ja === intercept ? 1 : ldexp(1, exps[ja]))
318
+ : ja === intercept && jb !== intercept ? centre[jb] : 0)));
319
+ const P = (K - 1) * p;
320
+ const full = (k, j) => k * p + j;
321
+ const hessian = Array.from({ length: P }, () => new Array(P).fill(NaN));
322
+ const vcov = Array.from({ length: P }, () => new Array(P).fill(NaN));
323
+ const Vs = spdInverse(cur.H);
324
+ for (let k = 0; k < K - 1; k++)
325
+ for (let l = 0; l < K - 1; l++) {
326
+ for (let a = 0; a < q; a++)
327
+ for (let c = 0; c < q; c++) {
328
+ let h = 0, v = 0;
329
+ for (let u = 0; u < q; u++)
330
+ for (let w2 = 0; w2 < q; w2++) {
331
+ const hu = cur.H[k * q + u][l * q + w2];
332
+ if (Minv[u][a] !== 0 && Minv[w2][c] !== 0)
333
+ h += Minv[u][a] * hu * Minv[w2][c];
334
+ if (Vs !== null && M[a][u] !== 0 && M[c][w2] !== 0)
335
+ v += M[a][u] * Vs[k * q + u][l * q + w2] * M[c][w2];
336
+ }
337
+ hessian[full(k, kept[a])][full(l, kept[c])] = h;
338
+ vcov[full(k, kept[a])][full(l, kept[c])] = Vs === null ? NaN : v;
339
+ }
340
+ }
341
+ const se = coefficients.map((row, k) => row.map((_, j) => {
342
+ const a = kept.indexOf(j);
343
+ if (a < 0 || Vs === null)
344
+ return NaN;
345
+ const vs = Vs[k * q + a][k * q + a];
346
+ return j === intercept ? Math.sqrt(vcov[full(k, j)][full(k, j)]) : ldexp(Math.sqrt(vs), -exps[j]);
347
+ }));
348
+ const value = cur.f;
349
+ const edf = Q;
350
+ // probabilities from the internal units (a column 1e15 + small differences keeps its digits)
351
+ const scaledCoef = Array.from({ length: K - 1 }, (_, k) => b.slice(k * q, (k + 1) * q));
352
+ const factorLevels = {};
353
+ for (let i = 1; i < d.terms.variables.length; i++) {
354
+ const variable = d.frame.variables[i];
355
+ if (variable?.kind === "factor")
356
+ factorLevels[d.terms.variables[i]] = variable.levels;
357
+ }
358
+ return reported("multinom", {
359
+ levels, columnNames: d.colNames.slice(), coefficients, se, vcov, hessian,
360
+ parameterNames: levels.slice(1).flatMap((lv) => d.colNames.map((c) => `${lv}:${c}`)),
361
+ value, deviance: 2 * value, logLik: -value, edf, aic: 2 * value + 2 * edf,
362
+ fittedValues: probabilities(xs, scaledCoef), n: y.length, decay, converged, iter,
363
+ model: { formula, rhs: parsed.rhs, predictorVariables: d.terms.variables.slice(1), factorLevels,
364
+ contrasts: (options.contrasts ?? {}), x, y, weights, rows: d.frame.rows,
365
+ internal: { centre, exps, kept, intercept, scaledCoef } },
366
+ warnings,
367
+ });
368
+ }
369
+ /**
370
+ * Summary of a multinomial logistic regression: Wald tests of the coefficients, odds ratios and pseudo R². Equivalent
371
+ * to `nnet::summary.multinom()` in R. The call followed is `summary(fit, Wald.ratios = TRUE)`, with the p-values, odds
372
+ * ratios and pseudo R² as ReactiveStat computes them (the null model `multinom(y ~ 1)` on the same rows, n the number
373
+ * of rows).
374
+ * @category Regression
375
+ */
376
+ export function multinomSummary(fit) {
377
+ const { coefficients, se } = fit;
378
+ const zValue = coefficients.map((row, k) => row.map((c, j) => c / se[k][j]));
379
+ const nullFit = unreported(() => multinomNull(fit));
380
+ const n = fit.n, ll = fit.logLik, l0 = nullFit;
381
+ // -expm1: 1 - exp(x) loses every digit when x is tiny (weights near 1e-200 give a log-likelihood near 1e-198)
382
+ const coxSnell = -Math.expm1((2 / n) * (l0 - ll));
383
+ return {
384
+ coefficients: coefficients.map((r) => r.slice()), se: se.map((r) => r.slice()), zValue,
385
+ pValue: zValue.map((row) => row.map((z) => 2 * pnorm(-Math.abs(z)))),
386
+ oddsRatios: coefficients.map((row) => row.map(Math.exp)),
387
+ deviance: fit.deviance, aic: fit.aic, logLik: ll, nullLogLik: l0, mcFadden: 1 - ll / l0, coxSnell,
388
+ nagelkerke: coxSnell / -Math.expm1((2 / n) * l0),
389
+ };
390
+ }
391
+ /** The maximised log-likelihood of the intercept-only model: the weighted proportions of the levels */
392
+ function multinomNull(fit) {
393
+ const K = fit.levels.length, w = fit.model.weights, y = fit.model.y;
394
+ const counts = new Array(K).fill(0);
395
+ y.forEach((c, i) => { counts[c] += w[i]; });
396
+ const total = counts.reduce((a, v) => a + v, 0);
397
+ return counts.reduce((a, c) => (c > 0 ? a + c * Math.log(c / total) : a), 0);
398
+ }
399
+ /**
400
+ * Variance matrix of the coefficients of a multinomial logistic regression. Equivalent to `nnet::vcov.multinom()` in R.
401
+ * @category Regression
402
+ */
403
+ export function multinomVcov(fit) {
404
+ return { vcov: fit.vcov.map((r) => r.slice()), names: fit.parameterNames.slice() };
405
+ }
406
+ /**
407
+ * Wald confidence intervals of the coefficients of a multinomial logistic regression. Equivalent to
408
+ * `nnet::confint.multinom()` in R. The limits are coefficient ± qnorm((1 + level) / 2) se.
409
+ * @category Regression
410
+ */
411
+ export function multinomConfint(fit, options = {}) {
412
+ checkOptions(options, MULTINOM_CONFINT_KEYS, "multinomConfint"); // generated: option-keys.mjs
413
+ const { level = 0.95 } = options;
414
+ if (!(level > 0 && level < 1))
415
+ throw new RangeError("'level' must be between 0 and 1");
416
+ const z = qnorm((1 + level) / 2);
417
+ return {
418
+ lower: fit.coefficients.map((row, k) => row.map((c, j) => c - z * fit.se[k][j])),
419
+ upper: fit.coefficients.map((row, k) => row.map((c, j) => c + z * fit.se[k][j])),
420
+ level,
421
+ };
422
+ }
423
+ /**
424
+ * Predictions of a multinomial logistic regression: probabilities of the levels, or the most probable level. Equivalent
425
+ * to `nnet::predict.multinom()` in R.
426
+ *
427
+ * Ties are broken as R's `max.col`: probabilities within 1e-5 (relative) of the row's largest are tied, and the k-th
428
+ * tied level replaces the choice when k u < 1, u a uniform of {@link runif} (one per tie after the first), so the
429
+ * classes are R's after the same `setSeed`.
430
+ * @category Regression
431
+ */
432
+ export function multinomPredict(fit, options = {}) {
433
+ checkOptions(options, MULTINOM_PREDICT_KEYS, "multinomPredict"); // generated: option-keys.mjs
434
+ const type = options.type ?? "class";
435
+ if (type !== "class" && type !== "probs")
436
+ throw new RangeError(`unknown prediction type '${String(type)}'`);
437
+ let probs;
438
+ if (options.newdata === undefined)
439
+ probs = fit.fittedValues.map((r) => r.slice());
440
+ else {
441
+ const model = fit.model, data = options.newdata;
442
+ if (dataRowCount(data, model.predictorVariables) === undefined)
443
+ throw new TypeError("cannot determine the number of rows in newdata");
444
+ for (const [name, levels] of Object.entries(model.factorLevels)) {
445
+ const column = data[name];
446
+ if (column === undefined)
447
+ throw new RangeError(`object '${name}' not found`);
448
+ for (const raw of column) {
449
+ if (raw === null || (typeof raw === "number" && Number.isNaN(raw)))
450
+ continue;
451
+ const value = typeof raw === "boolean" ? (raw ? "TRUE" : "FALSE") : String(raw);
452
+ if (!levels.includes(value))
453
+ throw new RangeError(`factor ${name} has new level ${value}`);
454
+ }
455
+ }
456
+ const d = design({ response: undefined, rhs: model.rhs }, data, { levels: model.factorLevels, contrasts: model.contrasts });
457
+ const columns = fit.columnNames.map((name) => d.colNames.indexOf(name));
458
+ if (columns.some((j) => j < 0))
459
+ throw new RangeError("newdata does not produce the fitted model matrix columns");
460
+ const { centre, exps, kept, intercept, scaledCoef } = model.internal;
461
+ probs = probabilities(d.x.map((row) => kept.map((j) => {
462
+ const v = row[columns[j]];
463
+ return j === intercept ? v : ldexp(v - centre[j], -exps[j]);
464
+ })), scaledCoef);
465
+ }
466
+ if (type === "probs")
467
+ return probs;
468
+ return probs.map((r) => {
469
+ const top = Math.max(...r.map(Math.abs));
470
+ const tol = 1e-5 * top;
471
+ let best = 0, ties = 1;
472
+ for (let j = 1; j < r.length; j++) {
473
+ if (r[j] > r[best] + tol) {
474
+ best = j;
475
+ ties = 1;
476
+ }
477
+ else if (r[j] >= r[best] - tol) {
478
+ ties++;
479
+ if (ties * runif(1)[0] < 1)
480
+ best = j;
481
+ }
482
+ }
483
+ return fit.levels[best];
484
+ });
485
+ }
486
+ /**
487
+ * Likelihood-ratio tests of nested multinomial logistic regressions. Equivalent to `nnet::anova.multinom()` in R. The
488
+ * models are ordered by their residual degrees of freedom (largest first), whatever the order given.
489
+ * @category Regression
490
+ */
491
+ export function multinomAnova(...fits) {
492
+ if (fits.length < 2)
493
+ throw new RangeError("give at least two fits");
494
+ const n = fits[0].n, K = fits[0].levels.length;
495
+ if (fits.some((f) => f.n !== n || f.levels.length !== K))
496
+ throw new RangeError("the models must be fitted to the same data");
497
+ const rows = fits.map((f) => ({ f, residDf: n * (K - 1) - f.edf }))
498
+ .sort((a, b) => b.residDf - a.residDf);
499
+ const out = { model: [], residDf: [], residDev: [], test: [], df: [], lrStat: [], pValue: [] };
500
+ rows.forEach(({ f, residDf }, i) => {
501
+ const rhs = f.model.formula.slice(f.model.formula.indexOf("~") + 1).trim().replace(/\s+/g, " ");
502
+ out.model.push(rhs);
503
+ out.residDf.push(residDf);
504
+ out.residDev.push(f.deviance);
505
+ if (i === 0) {
506
+ out.test.push("");
507
+ out.df.push(NaN);
508
+ out.lrStat.push(NaN);
509
+ out.pValue.push(NaN);
510
+ return;
511
+ }
512
+ const prev = rows[i - 1];
513
+ const df = prev.residDf - residDf, lr = prev.f.deviance - f.deviance;
514
+ out.test.push(`${i} vs ${i + 1}`);
515
+ out.df.push(df);
516
+ out.lrStat.push(lr);
517
+ out.pValue.push(pchisq(lr, df, { lowerTail: false }));
518
+ });
519
+ return out;
520
+ }