@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,186 @@
1
+ import type { DataFrame } from "./modelFrame.js";
2
+ /**
3
+ * A contingency table of any number of dimensions: `counts` in R's order (the first index varies fastest), `dim`
4
+ * the number of levels of each dimension, and optionally the names of the dimensions and of their levels.
5
+ * @category Regression
6
+ */
7
+ export interface ArrayTable {
8
+ /** The counts, the first index varying fastest. */
9
+ counts: readonly number[];
10
+ /** The number of levels of each dimension. */
11
+ dim: readonly number[];
12
+ /** Names of the dimensions. */
13
+ names?: readonly string[];
14
+ /** Names of the levels of each dimension. */
15
+ levels?: readonly (readonly string[])[];
16
+ }
17
+ /**
18
+ * A table as nested arrays, the first index outermost (`t[i][j][k]`).
19
+ * @category Regression
20
+ */
21
+ export type NestedTable = readonly (number | NestedTable)[];
22
+ /**
23
+ * Options for {@link loglin}.
24
+ * @category Regression
25
+ */
26
+ export interface LoglinOptions {
27
+ /** Starting table (R's order, default all 1); zeros mark structural zeros, kept zero in the fit. */
28
+ start?: readonly number[];
29
+ /** Convergence bound on the largest absolute difference between observed and fitted margins (default 0.1). */
30
+ eps?: number;
31
+ /** Maximum number of iterations (default 20). */
32
+ iter?: number;
33
+ }
34
+ /**
35
+ * Result of {@link loglin}.
36
+ * @category Regression
37
+ */
38
+ export interface LoglinResult {
39
+ /** Likelihood-ratio and Pearson statistics, and their degrees of freedom (no adjustment for structural zeros). */
40
+ lrt: number;
41
+ /** Pearson's statistic. */
42
+ pearson: number;
43
+ /** Degrees of freedom. */
44
+ df: number;
45
+ /** The margins fitted, with names where the table has them. */
46
+ margin: (string | number)[][];
47
+ /** The fitted table (R's order). */
48
+ fit: number[];
49
+ /**
50
+ * Zero-sum parameters of log(fit): "(Intercept)", one entry per term ("A", "A.B"), each in R's order; all NaN when
51
+ * a fitted value is 0 (as R's NA).
52
+ */
53
+ param: Record<string, number[]>;
54
+ /** The names of `param` in R's order (an object puts names that are numbers first). */
55
+ paramNames: string[];
56
+ /** Iterations (as R prints them). */
57
+ iterations: number;
58
+ /** The deviation of the last iteration (NaN without margins). */
59
+ deviation: number;
60
+ /** Warnings. */
61
+ warnings: string[];
62
+ }
63
+ /**
64
+ * Fits a hierarchical log-linear model to a contingency table by iterative proportional fitting (Haberman 1972),
65
+ * given the margins to fit (the maximal terms, e.g. `[["A", "B"], ["A", "C"]]` for [AB][AC]). Margins are names of
66
+ * dimensions or 1-based numbers, as in R. Equivalent to R's `loglin()`. It returns the fit and
67
+ * the parameters (R's `fit = TRUE, param = TRUE`).
68
+ *
69
+ * The iterations stop when the largest absolute difference between observed and fitted margins falls below `eps`
70
+ * (0.1 by default, a loose bound, as R) or after `iter` cycles.
71
+ * @example
72
+ * ```ts
73
+ * const t = { counts: [10, 20, 30, 40], dim: [2, 2], names: ["A", "B"] };
74
+ * loglin(t, [["A"], ["B"]]).lrt; // 0.80435 (the independence model)
75
+ * ```
76
+ * @category Regression
77
+ */
78
+ export declare function loglin(table: ArrayTable | NestedTable, margin: readonly (readonly (string | number)[] | string | number)[], options?: LoglinOptions): LoglinResult;
79
+ /**
80
+ * Options for {@link loglm}.
81
+ * @category Regression
82
+ */
83
+ export interface LoglmOptions {
84
+ /** Starting table (R's order of the table), zeros for structural zeros; with a table `data` only. */
85
+ start?: readonly number[];
86
+ /** Convergence bound (default 0.1), passed to {@link loglin}. */
87
+ eps?: number;
88
+ /** Maximum number of iterations (default 40). */
89
+ iter?: number;
90
+ /** The order of the levels of factors of a data frame (default: sorted). */
91
+ levels?: Record<string, readonly string[]>;
92
+ }
93
+ /**
94
+ * Result of {@link loglm}.
95
+ * @category Regression
96
+ */
97
+ export interface LoglmResult extends LoglinResult {
98
+ /** The formula. */
99
+ formula: string;
100
+ /** The likelihood-ratio statistic (the deviance against the saturated model). */
101
+ deviance: number;
102
+ /** The table fitted: counts (R's order), dims, names and levels. */
103
+ frequencies: LoglmFrequencies;
104
+ /** Cells of the table. */
105
+ nobs: number;
106
+ }
107
+ /**
108
+ * The table of a {@link loglm} fit.
109
+ * @category Regression
110
+ */
111
+ export interface LoglmFrequencies {
112
+ /** The counts (R's order). */
113
+ counts: number[];
114
+ /** The number of levels of each dimension. */
115
+ dim: number[];
116
+ /** Names of the dimensions. */
117
+ names: string[];
118
+ /** Names of the levels. */
119
+ levels: string[][];
120
+ }
121
+ /**
122
+ * Log-linear model given by a formula: a front end to {@link loglin}. The right-hand side gives the margins (its
123
+ * maximal terms; `a:b`, `a*b` and `a/b` are the same margin). `data` is a table with named dimensions (numbers in
124
+ * the formula stand for dimensions), or a data frame with the frequencies on the left of the formula, where cells
125
+ * absent from the data are structural zeros and each takes one degree of freedom off. Equivalent to R's
126
+ * `MASS::loglm()`.
127
+ * @example
128
+ * ```ts
129
+ * const t = { counts: [10, 20, 30, 40, 12, 18, 25, 35], dim: [2, 2, 2], names: ["A", "B", "C"] };
130
+ * loglm("~ A*B + C", t).deviance; // 0.54958
131
+ * ```
132
+ * @category Regression
133
+ */
134
+ export declare function loglm(formula: string, data: ArrayTable | NestedTable | DataFrame, options?: LoglmOptions): LoglmResult;
135
+ /**
136
+ * Options for {@link loglmResiduals}.
137
+ * @category Regression
138
+ */
139
+ export interface LoglmResidualsOptions {
140
+ /** `"deviance"` (default), `"pearson"` or `"response"`. */
141
+ type?: "deviance" | "pearson" | "response";
142
+ }
143
+ /**
144
+ * Residuals of a {@link loglm} fit, one per cell (R's order). Equivalent to `MASS::residuals.loglm()` in R.
145
+ * @example
146
+ * ```ts
147
+ * const t = { counts: [10, 20, 30, 40], dim: [2, 2], names: ["A", "B"] };
148
+ * loglmResiduals(loglm("~ A + B", t), { type: "pearson" }); // [-0.57735, 0.4714, 0.37796, -0.30861]
149
+ * ```
150
+ * @category Regression
151
+ */
152
+ export declare function loglmResiduals(fit: LoglmResult, options?: LoglmResidualsOptions): number[];
153
+ /**
154
+ * Result of {@link loglmAnova}: the models in the order given, then the saturated model.
155
+ * @category Regression
156
+ */
157
+ export interface LoglmAnovaResult {
158
+ /** "Model 1", ..., "Saturated". */
159
+ rows: string[];
160
+ /** The formulas ("" for the saturated model). */
161
+ formulas: string[];
162
+ /** Deviances. */
163
+ deviance: number[];
164
+ /** Residual degrees of freedom. */
165
+ df: number[];
166
+ /**
167
+ * Changes from the previous row (NaN for the first), and the chi-squared p-values of the changes, computed as R's
168
+ * `1 - pchisq()` (a p-value below about 1e-16 is 0).
169
+ */
170
+ deltaDeviance: number[];
171
+ /** Changes of the degrees of freedom. */
172
+ deltaDf: number[];
173
+ /** p-values. */
174
+ p: number[];
175
+ }
176
+ /**
177
+ * Likelihood-ratio tests between nested {@link loglm} fits and of the last against the saturated model. Equivalent
178
+ * to `MASS::anova.loglm()` in R.
179
+ * @example
180
+ * ```ts
181
+ * const t = { counts: [10, 20, 30, 40, 12, 18, 25, 35], dim: [2, 2, 2], names: ["A", "B", "C"] };
182
+ * loglmAnova(loglm("~ A + B + C", t), loglm("~ A*B + C", t)).p; // [NaN, 0.46019, 0.90787]
183
+ * ```
184
+ * @category Regression
185
+ */
186
+ export declare function loglmAnova(...fits: LoglmResult[]): LoglmAnovaResult;
@@ -0,0 +1,349 @@
1
+ // Log-linear models: stats' loglin (iterative proportional fitting) and MASS's loglm (its formula front end) with
2
+ // anova and residuals. Behaviour: oracle/tobit-betareg-loglin-behaviour.md (clean room: from the documentation and
3
+ // the output of R; no source of R or of a package was read). Written for rStats.js.
4
+ import { pchisq } from "../distributions/chisq.js";
5
+ import { parseFormula, termsOf } from "./formula.js";
6
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
7
+ import { checkOptions } from "../internal/checkOptions.js";
8
+ const LOGLIN_KEYS = ["start", "eps", "iter"];
9
+ const LOGLM_KEYS = ["start", "eps", "iter", "levels"];
10
+ const LOGLM_RESIDUALS_KEYS = ["type"];
11
+ function toTable(t) {
12
+ if (Array.isArray(t)) {
13
+ const dim = [];
14
+ let cur = t;
15
+ while (Array.isArray(cur)) {
16
+ dim.push(cur.length);
17
+ cur = cur[0];
18
+ }
19
+ const counts = new Array(dim.reduce((a, b) => a * b, 1));
20
+ const strides = dim.map((_, j) => dim.slice(0, j).reduce((a, b) => a * b, 1));
21
+ const walk = (node, depth, offset) => {
22
+ if (depth === dim.length) {
23
+ counts[offset] = Number(node);
24
+ return;
25
+ }
26
+ if (!Array.isArray(node) || node.length !== dim[depth])
27
+ throw new RangeError("the nested arrays must form a rectangular table");
28
+ node.forEach((child, i) => walk(child, depth + 1, offset + i * strides[depth]));
29
+ };
30
+ walk(t, 0, 0);
31
+ return { counts, dim, names: undefined, levels: undefined };
32
+ }
33
+ const a = t;
34
+ const size = a.dim.reduce((x, y) => x * y, 1);
35
+ if (a.counts.length !== size)
36
+ throw new RangeError("the length of 'counts' must be the product of 'dim'");
37
+ if (a.names !== undefined && a.names.length !== a.dim.length)
38
+ throw new RangeError("'names' must have one name per dimension");
39
+ return { counts: Array.from(a.counts), dim: Array.from(a.dim), names: a.names?.slice(), levels: a.levels?.map((l) => l.slice()) };
40
+ }
41
+ /** Sums of `x` (R's order, dims `dim`) over the dimensions not in `keep` (0-based, in the order given). */
42
+ function marginSums(x, dim, keep) {
43
+ const outDim = keep.map((k) => dim[k]);
44
+ const out = new Array(outDim.reduce((a, b) => a * b, 1)).fill(0);
45
+ const idx = new Array(dim.length).fill(0);
46
+ for (let c = 0; c < x.length; c++) {
47
+ let o = 0, s = 1;
48
+ for (let j = 0; j < keep.length; j++) {
49
+ o += idx[keep[j]] * s;
50
+ s *= outDim[j];
51
+ }
52
+ out[o] += x[c];
53
+ for (let j = 0; j < dim.length; j++) {
54
+ if (++idx[j] < dim[j])
55
+ break;
56
+ idx[j] = 0;
57
+ }
58
+ }
59
+ return out;
60
+ }
61
+ /** Index of each cell in the margin `keep`. */
62
+ function marginIndex(dim, keep) {
63
+ const out = [], idx = new Array(dim.length).fill(0), size = dim.reduce((a, b) => a * b, 1);
64
+ for (let c = 0; c < size; c++) {
65
+ let o = 0, s = 1;
66
+ for (const k of keep) {
67
+ o += idx[k] * s;
68
+ s *= dim[k];
69
+ }
70
+ out.push(o);
71
+ for (let j = 0; j < dim.length; j++) {
72
+ if (++idx[j] < dim[j])
73
+ break;
74
+ idx[j] = 0;
75
+ }
76
+ }
77
+ return out;
78
+ }
79
+ function ipf(counts, dim, margins, start, eps, iter) {
80
+ // the start is first scaled to the table's total (R: counts of 1e-300 converge in one cycle, log 27)
81
+ const total = counts.reduce((a, b) => a + b, 0), s0 = start.reduce((a, b) => a + b, 0);
82
+ let fit = start.map((v) => (v / s0) * total);
83
+ if (margins.length === 0)
84
+ return { fit, iterations: 0, deviation: NaN, converged: true };
85
+ const obs = margins.map((m) => marginSums(counts, dim, m)), index = margins.map((m) => marginIndex(dim, m));
86
+ let it = 0, deviation = 0;
87
+ // a cycle adjusts each margin in turn; its deviation is the largest |observed - fitted| margin difference seen just
88
+ // before the adjustments (so a model fitted in one cycle reports two)
89
+ while (it < iter) {
90
+ it++;
91
+ deviation = 0;
92
+ margins.forEach((m, k) => {
93
+ const cur = marginSums(fit, dim, m), o = obs[k];
94
+ for (let j = 0; j < cur.length; j++)
95
+ deviation = Math.max(deviation, Math.abs(o[j] - cur[j]));
96
+ const ratio = cur.map((c, j) => (c === 0 ? 0 : o[j] / c));
97
+ fit = fit.map((v, c) => v * ratio[index[k][c]]);
98
+ });
99
+ if (deviation < eps)
100
+ return { fit, iterations: it, deviation, converged: true };
101
+ }
102
+ return { fit, iterations: it, deviation, converged: false };
103
+ }
104
+ /** All non-empty subsets of the margins (the terms of the hierarchical model), by size, then by dimensions. */
105
+ function modelTerms(margins) {
106
+ const seen = new Map();
107
+ for (const m of margins) {
108
+ const s = [...m].sort((a, b) => a - b);
109
+ for (let mask = 1; mask < 1 << s.length; mask++) {
110
+ const t = s.filter((_, j) => mask & (1 << j));
111
+ seen.set(t.join(","), t);
112
+ }
113
+ }
114
+ return [...seen.values()].sort((a, b) => a.length - b.length || compareColex(a, b));
115
+ }
116
+ // R's order of the terms of a size: by the last dimension, then the one before (P.Q, Q.R, P.S, R.S)
117
+ const compareColex = (a, b) => { for (let j = a.length - 1; j >= 0; j--)
118
+ if (a[j] !== b[j])
119
+ return a[j] - b[j]; return 0; };
120
+ /** The zero-sum parameters of log(fit): for each term, the alternating sum of the marginal means of log(fit). */
121
+ function parameters(fit, dim, terms, dimNames) {
122
+ // a fitted zero (a structural zero) makes every parameter NA in R
123
+ const lf = fit.some((v) => !(v > 0)) ? fit.map(() => NaN) : fit.map(Math.log), size = fit.length;
124
+ const means = (keep) => {
125
+ const cells = keep.reduce((a, k) => a * dim[k], 1);
126
+ return marginSums(lf, dim, keep).map((v) => v / (size / cells));
127
+ };
128
+ const out = { "(Intercept)": [lf.reduce((a, b) => a + b, 0) / size] };
129
+ for (const t of terms) {
130
+ const outDim = t.map((k) => dim[k]), cells = outDim.reduce((a, b) => a * b, 1);
131
+ const eff = new Array(cells).fill(0);
132
+ for (let mask = 0; mask < 1 << t.length; mask++) {
133
+ const sub = t.filter((_, j) => mask & (1 << j)), sign = (t.length - sub.length) % 2 === 0 ? 1 : -1;
134
+ const m = means(sub), subPos = sub.map((k) => t.indexOf(k));
135
+ const idx = new Array(t.length).fill(0);
136
+ for (let c = 0; c < cells; c++) {
137
+ let o = 0, s = 1;
138
+ for (let j = 0; j < sub.length; j++) {
139
+ o += idx[subPos[j]] * s;
140
+ s *= dim[sub[j]];
141
+ }
142
+ eff[c] += sign * m[o];
143
+ for (let j = 0; j < t.length; j++) {
144
+ if (++idx[j] < outDim[j])
145
+ break;
146
+ idx[j] = 0;
147
+ }
148
+ }
149
+ }
150
+ out[t.map((k) => dimNames[k]).join(".")] = eff;
151
+ }
152
+ return out;
153
+ }
154
+ // The cells of the statistics are those with a positive start (a structural zero is left out even when its count is
155
+ // not 0; a sampling zero fitted as 0 makes Pearson's statistic NaN, as R). (o - f) ((o - f) / f) keeps counts near
156
+ // 1e300 from overflowing (R's statistics are NaN there)
157
+ function statistics(counts, fit, start) {
158
+ let lrt = 0, pearson = 0;
159
+ counts.forEach((o, c) => {
160
+ if (!(start[c] > 0))
161
+ return;
162
+ const f = fit[c];
163
+ pearson += (o - f) * ((o - f) / f);
164
+ if (o > 0)
165
+ lrt += o * (Math.log(o) - Math.log(f));
166
+ });
167
+ return { lrt: 2 * lrt, pearson };
168
+ }
169
+ function resolveMargin(m, t) {
170
+ const parts = Array.isArray(m) ? m : [m];
171
+ return parts.map((v) => {
172
+ const k = typeof v === "number" ? v - 1 : t.names?.indexOf(v) ?? -1;
173
+ if (!Number.isInteger(k) || k < 0 || k >= t.dim.length)
174
+ throw new RangeError("'margin' must contain names or numbers corresponding to 'table'");
175
+ return k;
176
+ });
177
+ }
178
+ function fitLoglin(t, margins, start, eps, iter) {
179
+ if (!(eps > 0))
180
+ throw new RangeError("'eps' must be positive");
181
+ // (R errors for iter = 0: "incorrect specification of 'table' or 'start'")
182
+ if (!Number.isInteger(iter) || iter < 1)
183
+ throw new RangeError("'iter' must be a positive integer");
184
+ const r = ipf(t.counts, t.dim, margins, start, eps, iter);
185
+ const dimNames = t.dim.map((_, k) => t.names?.[k] ?? String(k + 1));
186
+ const terms = modelTerms(margins);
187
+ const cells = t.counts.length;
188
+ const df = cells - 1 - terms.reduce((a, term) => a + term.reduce((p, k) => p * (t.dim[k] - 1), 1), 0);
189
+ const { lrt, pearson } = statistics(t.counts, r.fit, start);
190
+ return {
191
+ lrt, pearson, df, margin: margins.map((m) => m.map((k) => t.names?.[k] ?? k + 1)), fit: r.fit,
192
+ param: parameters(r.fit, t.dim, terms, dimNames), paramNames: ["(Intercept)", ...terms.map((term) => term.map((k) => dimNames[k]).join("."))], iterations: r.iterations, deviation: r.deviation,
193
+ warnings: r.converged ? [] : ["algorithm did not converge"],
194
+ };
195
+ }
196
+ /**
197
+ * Fits a hierarchical log-linear model to a contingency table by iterative proportional fitting (Haberman 1972),
198
+ * given the margins to fit (the maximal terms, e.g. `[["A", "B"], ["A", "C"]]` for [AB][AC]). Margins are names of
199
+ * dimensions or 1-based numbers, as in R. Equivalent to R's `loglin()`. It returns the fit and
200
+ * the parameters (R's `fit = TRUE, param = TRUE`).
201
+ *
202
+ * The iterations stop when the largest absolute difference between observed and fitted margins falls below `eps`
203
+ * (0.1 by default, a loose bound, as R) or after `iter` cycles.
204
+ * @example
205
+ * ```ts
206
+ * const t = { counts: [10, 20, 30, 40], dim: [2, 2], names: ["A", "B"] };
207
+ * loglin(t, [["A"], ["B"]]).lrt; // 0.80435 (the independence model)
208
+ * ```
209
+ * @category Regression
210
+ */
211
+ export function loglin(table, margin, options = {}) {
212
+ checkOptions(options, LOGLIN_KEYS, "loglin"); // generated: option-keys.mjs
213
+ const t = toTable(table);
214
+ if (t.counts.some((v) => !(v >= 0)))
215
+ throw new RangeError("the counts must be non-negative numbers");
216
+ const start = options.start === undefined ? t.counts.map(() => 1) : Array.from(options.start);
217
+ if (start.length !== t.counts.length)
218
+ throw new RangeError("'start' and 'table' must be same length");
219
+ const margins = margin.map((m) => resolveMargin(m, t));
220
+ return fitLoglin(t, margins, start, options.eps ?? 0.1, options.iter ?? 20);
221
+ }
222
+ /**
223
+ * Log-linear model given by a formula: a front end to {@link loglin}. The right-hand side gives the margins (its
224
+ * maximal terms; `a:b`, `a*b` and `a/b` are the same margin). `data` is a table with named dimensions (numbers in
225
+ * the formula stand for dimensions), or a data frame with the frequencies on the left of the formula, where cells
226
+ * absent from the data are structural zeros and each takes one degree of freedom off. Equivalent to R's
227
+ * `MASS::loglm()`.
228
+ * @example
229
+ * ```ts
230
+ * const t = { counts: [10, 20, 30, 40, 12, 18, 25, 35], dim: [2, 2, 2], names: ["A", "B", "C"] };
231
+ * loglm("~ A*B + C", t).deviance; // 0.54958
232
+ * ```
233
+ * @category Regression
234
+ */
235
+ export function loglm(formula, data, options = {}) {
236
+ checkOptions(options, LOGLM_KEYS, "loglm"); // generated: option-keys.mjs
237
+ const isTable = Array.isArray(data) || (typeof data.dim === "object" && Array.isArray(data.counts));
238
+ // numbers in the formula stand for dimensions: they become names .v1, .v2, ...
239
+ // (not the power of ^2)
240
+ const f = formula.replace(/(?<!\^\s*)(?<![A-Za-z0-9._])(\d+)(?![A-Za-z0-9._])/g, (_, d) => `.v${d}`);
241
+ const parsed = parseFormula(f);
242
+ let t, start, structural = 0;
243
+ if (isTable) {
244
+ t = toTable(data);
245
+ const names = t.dim.map((_, k) => t.names?.[k] ?? `.v${k + 1}`);
246
+ t.names = t.names === undefined ? names : t.names.slice();
247
+ t.levels = t.levels ?? t.dim.map((n) => Array.from({ length: n }, (_, i) => String(i + 1)));
248
+ start = options.start === undefined ? t.counts.map(() => 1) : Array.from(options.start);
249
+ if (start.length !== t.counts.length)
250
+ throw new RangeError("'start' and 'table' must be same length");
251
+ }
252
+ else {
253
+ if (parsed.response === undefined)
254
+ throw new TypeError("a data frame needs the frequencies on the left of the formula");
255
+ const df = data;
256
+ const terms0 = termsOf(parsed, Object.keys(df));
257
+ const vars = terms0.variables.slice(1);
258
+ const freq = df[parsed.response];
259
+ if (freq === undefined)
260
+ throw new RangeError(`object '${parsed.response}' not found`);
261
+ const n = freq.length;
262
+ const levels = vars.map((v) => {
263
+ const col = df[v];
264
+ if (col === undefined)
265
+ throw new RangeError(`object '${v}' not found`);
266
+ const given = options.levels?.[v];
267
+ return given !== undefined ? Array.from(given) : [...new Set(Array.from(col, (x) => String(x)))].sort();
268
+ });
269
+ const dim = levels.map((l) => l.length), size = dim.reduce((a, b) => a * b, 1);
270
+ const counts = new Array(size).fill(0), present = new Array(size).fill(false);
271
+ for (let i = 0; i < n; i++) {
272
+ let o = 0, s = 1;
273
+ vars.forEach((v, j) => { const lv = levels[j].indexOf(String(df[v][i])); if (lv < 0)
274
+ throw new RangeError(`level of ${v} not in 'levels'`); o += lv * s; s *= dim[j]; });
275
+ counts[o] += Number(freq[i]);
276
+ present[o] = true;
277
+ }
278
+ structural = present.filter((p) => !p).length;
279
+ start = present.map((p) => (p ? 1 : 0));
280
+ t = { counts, dim, names: vars, levels };
281
+ }
282
+ const terms = termsOf(parsed, t.names);
283
+ const vars = terms.variables.slice(terms.response === -1 ? 0 : 1);
284
+ // the maximal terms, in the order of the terms
285
+ const sets = terms.terms.map((term) => term.map((v) => terms.variables[v]));
286
+ const maximal = sets.filter((s, i) => !sets.some((o, j) => j !== i && o.length > s.length && s.every((v) => o.includes(v))));
287
+ // a name, or .vk for the k-th dimension
288
+ const dimOf = (v) => {
289
+ const byNumber = /^\.v(\d+)$/.exec(v);
290
+ const k = byNumber !== null && !t.names.includes(v) ? Number(byNumber[1]) - 1 : t.names.indexOf(v);
291
+ if (k < 0 || k >= t.dim.length)
292
+ throw new RangeError(`'${v}' is not a dimension of the table`);
293
+ return k;
294
+ };
295
+ vars.forEach(dimOf);
296
+ const margins = maximal.map((s) => s.map(dimOf));
297
+ const r = fitLoglin(t, margins, start, options.eps ?? 0.1, options.iter ?? 40);
298
+ const names = t.names.map((nm) => nm);
299
+ return {
300
+ ...r, df: r.df - structural, formula, deviance: r.lrt,
301
+ frequencies: { counts: t.counts, dim: t.dim, names, levels: t.levels }, nobs: t.counts.length,
302
+ };
303
+ }
304
+ /**
305
+ * Residuals of a {@link loglm} fit, one per cell (R's order). Equivalent to `MASS::residuals.loglm()` in R.
306
+ * @example
307
+ * ```ts
308
+ * const t = { counts: [10, 20, 30, 40], dim: [2, 2], names: ["A", "B"] };
309
+ * loglmResiduals(loglm("~ A + B", t), { type: "pearson" }); // [-0.57735, 0.4714, 0.37796, -0.30861]
310
+ * ```
311
+ * @category Regression
312
+ */
313
+ export function loglmResiduals(fit, options = {}) {
314
+ checkOptions(options, LOGLM_RESIDUALS_KEYS, "loglmResiduals"); // generated: option-keys.mjs
315
+ const type = options.type ?? "deviance";
316
+ if (type !== "deviance" && type !== "pearson" && type !== "response")
317
+ throw new RangeError("'arg' should be one of “deviance”, “pearson”, “response”");
318
+ return fit.frequencies.counts.map((o, c) => {
319
+ const f = fit.fit[c];
320
+ if (type === "response")
321
+ return o - f;
322
+ if (type === "pearson")
323
+ return (o - f) / Math.sqrt(f);
324
+ return Math.sign(o - f) * Math.sqrt(2 * Math.abs((o > 0 ? o * Math.log(o / f) : 0) - (o - f)));
325
+ });
326
+ }
327
+ /**
328
+ * Likelihood-ratio tests between nested {@link loglm} fits and of the last against the saturated model. Equivalent
329
+ * to `MASS::anova.loglm()` in R.
330
+ * @example
331
+ * ```ts
332
+ * const t = { counts: [10, 20, 30, 40, 12, 18, 25, 35], dim: [2, 2, 2], names: ["A", "B", "C"] };
333
+ * loglmAnova(loglm("~ A + B + C", t), loglm("~ A*B + C", t)).p; // [NaN, 0.46019, 0.90787]
334
+ * ```
335
+ * @category Regression
336
+ */
337
+ export function loglmAnova(...fits) {
338
+ if (fits.length < 1)
339
+ throw new RangeError("give at least one fit");
340
+ const deviance = [...fits.map((f) => f.deviance), 0], df = [...fits.map((f) => f.df), 0];
341
+ const deltaDeviance = deviance.map((d, i) => (i === 0 ? NaN : deviance[i - 1] - d));
342
+ const deltaDf = df.map((d, i) => (i === 0 ? NaN : df[i - 1] - d));
343
+ return {
344
+ rows: [...fits.map((_, i) => `Model ${i + 1}`), "Saturated"], formulas: [...fits.map((f) => f.formula), ""],
345
+ // R computes 1 - pchisq(...): p-values below about 1e-16 are 0 and small ones lose digits (2.8967876430918693e-7
346
+ // where the upper tail is 2.896787643364249e-7). Kept as R (demo example loglm-anova, log 26)
347
+ deviance, df, deltaDeviance, deltaDf, p: deltaDeviance.map((d, i) => (i === 0 ? NaN : 1 - pchisq(d, deltaDf[i]))),
348
+ };
349
+ }
@@ -26,7 +26,10 @@ export interface SurvregOptions {
26
26
  strata?: readonly (string | number | boolean)[];
27
27
  scale?: number;
28
28
  init?: readonly number[];
29
+ /** Degrees of freedom of the t distribution (default 4, at least 3); `parms` is the same, as R names it (give one). */
29
30
  df?: number;
31
+ /** R's name for `df`: the degrees of freedom of the t distribution (give one of the two). */
32
+ parms?: number;
30
33
  control?: SurvregControl;
31
34
  intercept?: boolean;
32
35
  confLevel?: number;
@@ -44,45 +47,85 @@ export interface SurvregTable {
44
47
  * @category Survival analysis
45
48
  */
46
49
  export interface SurvregResult {
50
+ /** The regression coefficients (intercept first when present). */
47
51
  coefficients: number[];
52
+ /** Their names. */
48
53
  coefNames: string[];
54
+ /** The scale of each stratum (fixed or estimated). */
49
55
  scale: number[];
56
+ /** The summary table: coefficients and log scales with standard errors, z and p. */
50
57
  table: SurvregTable;
58
+ /** The levels of the strata. */
51
59
  strataLevels: (string | number | boolean)[];
60
+ /** Whether an offset was given. */
52
61
  hasOffset: boolean;
62
+ /** The intercept-only model's intercept and log scale. */
53
63
  icoef: number[];
64
+ /** Covariance of the coefficients and log scales. */
54
65
  var: number[][];
66
+ /** Log-likelihoods of the intercept-only model and of the model. */
55
67
  loglik: [number, number];
68
+ /** Iterations. */
56
69
  iter: number;
70
+ /** Degrees of freedom of the model (coefficients and estimated scales). */
57
71
  df: number;
72
+ /** Degrees of freedom of the intercept-only model. */
58
73
  idf: number;
74
+ /** Residual degrees of freedom. */
59
75
  dfResidual: number;
76
+ /** Observations used. */
60
77
  n: number;
78
+ /** Linear predictors of the observations used. */
61
79
  linearPredictors: number[];
80
+ /** Means of the columns of the model matrix. */
62
81
  means: number[];
82
+ /** The score at the estimates. */
63
83
  score: number[];
84
+ /** Row names of the table: the coefficients, then Log(scale) or the strata. */
64
85
  tableRowNames: string[];
86
+ /** Estimates of the table's rows. */
65
87
  value: number[];
88
+ /** Their standard errors. */
66
89
  se: number[];
90
+ /** Their z statistics. */
67
91
  z: number[];
92
+ /** Their p-values. */
68
93
  p: number[];
94
+ /** Likelihood-ratio statistic of the model against the intercept-only model. */
69
95
  chi: number;
96
+ /** Its degrees of freedom. */
70
97
  chiDf: number;
98
+ /** Its p-value. */
71
99
  chiP: number;
100
+ /** The distribution. */
72
101
  dist: SurvregDistribution;
102
+ /** Degrees of freedom of the t distribution. */
73
103
  distributionDf: number;
104
+ /** The distribution's parameter (R's `parms`). */
74
105
  parms: number;
106
+ /** Whether the model has an intercept. */
75
107
  intercept: boolean;
108
+ /** The model matrix of the observations used. */
76
109
  x: number[][];
110
+ /** Offsets of the observations used. */
77
111
  offset: number[];
112
+ /** 0-based indices of the observations used. */
78
113
  rows: number[];
114
+ /** Weights of the observations used. */
79
115
  weights: number[];
116
+ /** Stratum of each observation used (0-based). */
80
117
  strata: number[];
118
+ /** Response on the scale of the distribution (log time for the log distributions). */
81
119
  y: number[];
120
+ /** Lower ends of the observations on that scale. */
82
121
  lower: number[];
122
+ /** Upper ends. */
83
123
  upper: number[];
124
+ /** Censoring status (0 right, 1 exact, 2 left, 3 interval). */
84
125
  status: number[];
126
+ /** The type of the survival data. */
85
127
  type: SurvregType;
128
+ /** Warnings. */
86
129
  warnings: string[];
87
130
  }
88
131
  /** Prediction options for {@link survregPredict}.
@@ -12,7 +12,8 @@ import { midpoint } from "../internal/extremes.js";
12
12
  // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
13
13
  import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
14
14
  const SURVREG_KEYS = /* @__PURE__ */ new Set([
15
- "type", "time2", "dist", "weights", "offset", "strata", "scale", "init", "df", "control", "intercept", "confLevel",
15
+ "type", "time2", "dist", "weights", "offset", "strata", "scale", "init", "df", "parms", "control", "intercept",
16
+ "confLevel",
16
17
  ]);
17
18
  const SURVREG_CONTROL_KEYS = ["maxiter", "relTolerance", "tolerChol"];
18
19
  const SURVREG_PREDICT_KEYS = ["type", "p", "newX", "newStrata", "newOffset", "seFit"];
@@ -426,7 +427,7 @@ function fitCore(X, y, lo, hi, status, weights, offset, strata, k, d, nu, fixed,
426
427
  export function survreg(time, event, x = [], options = {}) {
427
428
  checkOptions(options, SURVREG_KEYS, "survreg"); // generated: option-keys.mjs
428
429
  checkOptions(nestedOptions(options, "control"), SURVREG_CONTROL_KEYS, "survreg", "control"); // generated: option-keys.mjs
429
- const type = options.type ?? "right", d = options.dist ?? "weibull", nu = options.df ?? 4, intercept = options.intercept ?? true;
430
+ const type = options.type ?? "right", d = options.dist ?? "weibull", nu = options.df ?? options.parms ?? 4, intercept = options.intercept ?? true;
430
431
  const n0 = time.length, events = event === undefined ? Array(n0).fill(1) : Array.from(event, Number);
431
432
  if (events.length !== n0 || x.length !== 0 && x.length !== n0)
432
433
  throw new RangeError("variable lengths differ");
@@ -444,7 +445,9 @@ export function survreg(time, event, x = [], options = {}) {
444
445
  throw new RangeError("Invalid scale value");
445
446
  if (d === "t" && (!(nu >= 3) || !Number.isFinite(nu)))
446
447
  throw new RangeError("Degrees of freedom must be >=3");
447
- if (d !== "t" && options.df !== undefined)
448
+ if (options.df !== undefined && options.parms !== undefined)
449
+ throw new RangeError("give the degrees of freedom of the t distribution as 'df' or as 'parms', not both");
450
+ if (d !== "t" && (options.df !== undefined || options.parms !== undefined))
448
451
  throw new RangeError("Extreme value distribution has no optional parameters");
449
452
  const logTime = ["weibull", "exponential", "rayleigh", "loggaussian", "lognormal", "loglogistic"].includes(d);
450
453
  const fixed0 = options.scale !== undefined && options.scale > 0 ? options.scale : undefined;