@numero-uno-jpn/rstats 0.16.0 → 1.0.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 (243) hide show
  1. package/CHANGELOG.md +205 -0
  2. package/README.ja.md +57 -23
  3. package/README.md +60 -23
  4. package/dist/chunks/{chunk-5UQCRBAG.js → chunk-3W5NFFAA.js} +1 -1
  5. package/dist/chunks/chunk-4F2IALD4.js +3 -0
  6. package/dist/chunks/{chunk-QNNL7AZ3.js → chunk-4OLDGML4.js} +2 -2
  7. package/dist/chunks/chunk-63OPBEYO.js +2 -0
  8. package/dist/chunks/chunk-6XJBCRBV.js +2 -0
  9. package/dist/chunks/chunk-BQSIBJVX.js +2 -0
  10. package/dist/chunks/chunk-BWKHYRM6.js +3 -0
  11. package/dist/chunks/{chunk-W26LRYOJ.js → chunk-CKV4JWW2.js} +1 -1
  12. package/dist/chunks/chunk-DCAWMF4K.js +2 -0
  13. package/dist/chunks/chunk-F7YGX7PN.js +2 -0
  14. package/dist/chunks/chunk-H7I32ZZE.js +2 -0
  15. package/dist/chunks/chunk-IEOD5GWC.js +3 -0
  16. package/dist/chunks/chunk-KICBQGFN.js +2 -0
  17. package/dist/chunks/chunk-LROMWFAK.js +2 -0
  18. package/dist/chunks/chunk-NSWENS3S.js +2 -0
  19. package/dist/chunks/chunk-O2SQMGE3.js +2 -0
  20. package/dist/chunks/chunk-QQX46TCI.js +2 -0
  21. package/dist/chunks/chunk-QZK3CCBA.js +2 -0
  22. package/dist/chunks/chunk-UJ66VQIG.js +2 -0
  23. package/dist/chunks/chunk-UKNDX4BA.js +2 -0
  24. package/dist/chunks/chunk-WIBKS73G.js +2 -0
  25. package/dist/chunks/{chunk-URIO5LY5.js → chunk-WQWZ7FND.js} +2 -2
  26. package/dist/chunks/chunk-WWVMVZUL.js +2 -0
  27. package/dist/chunks/chunk-YG5S5AVP.js +2 -0
  28. package/dist/chunks/chunk-YHNMBYSW.js +2 -0
  29. package/dist/data/grouping.js +6 -2
  30. package/dist/descriptive/basic.js +20 -0
  31. package/dist/descriptive/cov.js +11 -0
  32. package/dist/descriptive/dataFrames.js +13 -5
  33. package/dist/descriptive/factanal.d.ts +2 -0
  34. package/dist/descriptive/factanal.js +10 -2
  35. package/dist/descriptive/hist.js +6 -0
  36. package/dist/descriptive/moments.js +14 -0
  37. package/dist/descriptive/omega.js +8 -3
  38. package/dist/descriptive/pivot.d.ts +4 -1
  39. package/dist/descriptive/pivot.js +27 -13
  40. package/dist/descriptive/quantile.js +8 -0
  41. package/dist/descriptive/rank.js +4 -0
  42. package/dist/descriptive/table.d.ts +20 -1
  43. package/dist/descriptive/table.js +14 -14
  44. package/dist/descriptive.js +2 -2
  45. package/dist/distributions/arcsine.js +8 -0
  46. package/dist/distributions/beta.js +9 -0
  47. package/dist/distributions/binomial.js +9 -0
  48. package/dist/distributions/cauchy.js +9 -0
  49. package/dist/distributions/chisq.js +9 -0
  50. package/dist/distributions/exponential.js +9 -0
  51. package/dist/distributions/f.js +9 -0
  52. package/dist/distributions/gamma.js +8 -0
  53. package/dist/distributions/geometric.js +9 -0
  54. package/dist/distributions/hypergeometric.js +8 -0
  55. package/dist/distributions/invgamma.js +8 -0
  56. package/dist/distributions/kumaraswamy.js +9 -0
  57. package/dist/distributions/laplace.js +9 -0
  58. package/dist/distributions/logistic.js +9 -0
  59. package/dist/distributions/lognormal.js +8 -0
  60. package/dist/distributions/multinomial.js +4 -0
  61. package/dist/distributions/negbinomial.js +8 -0
  62. package/dist/distributions/normal.js +8 -0
  63. package/dist/distributions/pareto.js +8 -0
  64. package/dist/distributions/poisson.js +9 -0
  65. package/dist/distributions/signrank.js +9 -0
  66. package/dist/distributions/summary.d.ts +2 -1
  67. package/dist/distributions/summary.js +31 -1
  68. package/dist/distributions/t.js +9 -0
  69. package/dist/distributions/triangular.js +9 -0
  70. package/dist/distributions/tukey.js +6 -0
  71. package/dist/distributions/uniform.js +8 -0
  72. package/dist/distributions/weibull.js +8 -0
  73. package/dist/distributions/wilcox.js +9 -0
  74. package/dist/distributions.js +2 -2
  75. package/dist/entries/descriptive.d.ts +3 -1
  76. package/dist/entries/descriptive.js +1 -1
  77. package/dist/entries/distributions.d.ts +1 -0
  78. package/dist/entries/distributions.js +2 -0
  79. package/dist/entries/linalg.d.ts +3 -1
  80. package/dist/entries/mixed.d.ts +9 -0
  81. package/dist/entries/mixed.js +8 -1
  82. package/dist/entries/numerics.d.ts +2 -1
  83. package/dist/entries/tests.d.ts +8 -5
  84. package/dist/entries/tests.js +3 -1
  85. package/dist/htest/agreement.d.ts +13 -0
  86. package/dist/htest/agreement.js +46 -7
  87. package/dist/htest/ansariTest.d.ts +2 -1
  88. package/dist/htest/ansariTest.js +43 -12
  89. package/dist/htest/aov.d.ts +28 -22
  90. package/dist/htest/aov.js +42 -13
  91. package/dist/htest/binomTest.js +6 -0
  92. package/dist/htest/brunnerMunzelTest.js +5 -0
  93. package/dist/htest/chisqTest.d.ts +3 -1
  94. package/dist/htest/chisqTest.js +21 -3
  95. package/dist/htest/cor.d.ts +7 -1
  96. package/dist/htest/cor.js +40 -7
  97. package/dist/htest/core/simulate.d.ts +6 -0
  98. package/dist/htest/core/simulate.js +20 -0
  99. package/dist/htest/effectSize.d.ts +3 -0
  100. package/dist/htest/effectSize.js +28 -8
  101. package/dist/htest/fisherTest.d.ts +2 -1
  102. package/dist/htest/fisherTest.js +52 -6
  103. package/dist/htest/ksTest.d.ts +4 -0
  104. package/dist/htest/ksTest.js +13 -4
  105. package/dist/htest/leveneTest.d.ts +2 -0
  106. package/dist/htest/leveneTest.js +9 -3
  107. package/dist/htest/mantelhaenTest.js +7 -0
  108. package/dist/htest/mcnemarTest.js +8 -0
  109. package/dist/htest/multipleComparisons.d.ts +16 -25
  110. package/dist/htest/multipleComparisons.js +26 -43
  111. package/dist/htest/normalityTests.js +10 -4
  112. package/dist/htest/onewayTest.js +10 -0
  113. package/dist/htest/pAdjust.js +4 -0
  114. package/dist/htest/pairwise.d.ts +2 -0
  115. package/dist/htest/pairwise.js +29 -6
  116. package/dist/htest/poissonTest.js +6 -0
  117. package/dist/htest/polycor.js +20 -10
  118. package/dist/htest/power.d.ts +4 -0
  119. package/dist/htest/power.js +16 -2
  120. package/dist/htest/propTest.d.ts +3 -0
  121. package/dist/htest/propTest.js +23 -2
  122. package/dist/htest/pwr.d.ts +38 -1
  123. package/dist/htest/pwr.js +38 -15
  124. package/dist/htest/rankTests.js +7 -1
  125. package/dist/htest/tTest.d.ts +2 -0
  126. package/dist/htest/tTest.js +9 -0
  127. package/dist/htest/testFormula.js +11 -11
  128. package/dist/htest/trendTests.d.ts +21 -1
  129. package/dist/htest/trendTests.js +13 -18
  130. package/dist/htest/types.d.ts +2 -0
  131. package/dist/htest/varTest.js +7 -0
  132. package/dist/htest/wilcoxTest.js +51 -9
  133. package/dist/internal/checkOptions.d.ts +11 -0
  134. package/dist/internal/checkOptions.js +31 -0
  135. package/dist/internal/optionalArgs.d.ts +12 -0
  136. package/dist/internal/optionalArgs.js +46 -0
  137. package/dist/internal/warnings.d.ts +66 -0
  138. package/dist/internal/warnings.js +122 -0
  139. package/dist/linalg/basic.js +7 -0
  140. package/dist/linalg/chol.js +6 -0
  141. package/dist/linalg/eigen.js +4 -0
  142. package/dist/linalg/expm.js +4 -0
  143. package/dist/linalg/kappa.js +6 -0
  144. package/dist/linalg/lu.js +5 -0
  145. package/dist/linalg/norm.js +4 -0
  146. package/dist/linalg/ops.d.ts +27 -2
  147. package/dist/linalg/ops.js +14 -13
  148. package/dist/linalg/qr.js +14 -0
  149. package/dist/linalg/solve.js +9 -0
  150. package/dist/linalg/svd.js +6 -2
  151. package/dist/linalg.js +2 -2
  152. package/dist/mixed.js +5 -4
  153. package/dist/models/anovaSequential.d.ts +16 -1
  154. package/dist/models/anovaSequential.js +50 -7
  155. package/dist/models/aovEz.js +16 -11
  156. package/dist/models/aovStrata.js +15 -4
  157. package/dist/models/carAnova.js +11 -17
  158. package/dist/models/coxph.d.ts +6 -0
  159. package/dist/models/coxph.js +21 -6
  160. package/dist/models/formula.d.ts +5 -2
  161. package/dist/models/formula.js +31 -8
  162. package/dist/models/glm.d.ts +22 -2
  163. package/dist/models/glm.js +32 -22
  164. package/dist/models/glmAnova.js +8 -3
  165. package/dist/models/glmConfint.js +6 -2
  166. package/dist/models/glmFamily.d.ts +1 -6
  167. package/dist/models/glmFamily.js +3 -22
  168. package/dist/models/glmer.d.ts +255 -0
  169. package/dist/models/glmer.js +635 -0
  170. package/dist/models/glmerAnova.d.ts +81 -0
  171. package/dist/models/glmerAnova.js +139 -0
  172. package/dist/models/glmerDeviance.d.ts +98 -0
  173. package/dist/models/glmerDeviance.js +576 -0
  174. package/dist/models/glmerFamily.d.ts +57 -0
  175. package/dist/models/glmerFamily.js +236 -0
  176. package/dist/models/glmerGradient.d.ts +46 -0
  177. package/dist/models/glmerGradient.js +301 -0
  178. package/dist/models/glmerStructure.d.ts +45 -0
  179. package/dist/models/glmerStructure.js +168 -0
  180. package/dist/models/glmerSummary.d.ts +102 -0
  181. package/dist/models/glmerSummary.js +94 -0
  182. package/dist/models/lm.js +13 -3
  183. package/dist/models/lmer.d.ts +27 -6
  184. package/dist/models/lmer.js +75 -321
  185. package/dist/models/lmerAnova.d.ts +52 -3
  186. package/dist/models/lmerAnova.js +101 -45
  187. package/dist/models/lmerTest.d.ts +12 -5
  188. package/dist/models/lmerTest.js +39 -18
  189. package/dist/models/mauchly.d.ts +2 -0
  190. package/dist/models/mauchly.js +7 -2
  191. package/dist/models/mixedDeviance.d.ts +28 -2
  192. package/dist/models/mixedDeviance.js +84 -56
  193. package/dist/models/mixedMinimiser.d.ts +83 -0
  194. package/dist/models/mixedMinimiser.js +438 -0
  195. package/dist/models/mixedPredict.d.ts +121 -0
  196. package/dist/models/mixedPredict.js +530 -0
  197. package/dist/models/mixedStructure.d.ts +62 -3
  198. package/dist/models/mixedStructure.js +74 -29
  199. package/dist/models/modelFrame.js +2 -2
  200. package/dist/models/modelMatrix.d.ts +8 -1
  201. package/dist/models/modelMatrix.js +56 -39
  202. package/dist/models/survival.d.ts +6 -0
  203. package/dist/models/survival.js +9 -2
  204. package/dist/numerics/deriv.js +8 -0
  205. package/dist/numerics/integrate.js +8 -0
  206. package/dist/numerics/interp.d.ts +32 -7
  207. package/dist/numerics/interp.js +27 -9
  208. package/dist/numerics/ode.js +4 -0
  209. package/dist/numerics.js +2 -2
  210. package/dist/optim/optim.js +17 -2
  211. package/dist/random/beta.js +5 -0
  212. package/dist/random/continuous.js +17 -0
  213. package/dist/random/extra.js +13 -0
  214. package/dist/random/gamma.js +11 -0
  215. package/dist/random/poisson.js +5 -0
  216. package/dist/random/rng.js +4 -0
  217. package/dist/random/sample.js +6 -0
  218. package/dist/rstats.js +17 -14
  219. package/dist/special/besselIK.js +7 -0
  220. package/dist/special/choose.js +7 -0
  221. package/dist/special/psigamma.js +7 -0
  222. package/dist/special.js +2 -2
  223. package/dist/tests.js +14 -11
  224. package/llms.txt +15 -4
  225. package/package.json +19 -10
  226. package/dist/chunks/chunk-2D2IQWUQ.js +0 -2
  227. package/dist/chunks/chunk-6CSTWA5E.js +0 -2
  228. package/dist/chunks/chunk-72Y3HZID.js +0 -2
  229. package/dist/chunks/chunk-BG2KLEHM.js +0 -2
  230. package/dist/chunks/chunk-CMEKBNHQ.js +0 -2
  231. package/dist/chunks/chunk-FLJNSXSW.js +0 -2
  232. package/dist/chunks/chunk-GM53LWSR.js +0 -2
  233. package/dist/chunks/chunk-JBCA56ZS.js +0 -3
  234. package/dist/chunks/chunk-K3RJAD2T.js +0 -2
  235. package/dist/chunks/chunk-KAZRWIB5.js +0 -2
  236. package/dist/chunks/chunk-KBVVIMXX.js +0 -3
  237. package/dist/chunks/chunk-N3SIFCZX.js +0 -2
  238. package/dist/chunks/chunk-SC6CV4Z3.js +0 -2
  239. package/dist/chunks/chunk-SYWOBOTR.js +0 -2
  240. package/dist/chunks/chunk-VTUGG2SV.js +0 -2
  241. package/dist/chunks/chunk-XHETEYVC.js +0 -2
  242. package/dist/chunks/chunk-YRZWONZB.js +0 -3
  243. package/dist/chunks/chunk-ZGABZMWX.js +0 -2
@@ -23,6 +23,10 @@ import { mauchlyPValue, sphericityW } from "./mauchly.js";
23
23
  import { compareCodePoints } from "./modelFrame.js";
24
24
  import { modelMatrix } from "./modelMatrix.js";
25
25
  import { scaledTables } from "./scaledTables.js";
26
+ import { reported, unreported } from "../internal/warnings.js";
27
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
28
+ import { checkOptions } from "../internal/checkOptions.js";
29
+ const AOV_EZ_KEYS = ["id", "dv", "between", "within", "type", "correction", "es", "observed"];
26
30
  const list = (v) => (v === undefined ? [] : typeof v === "string" ? [v] : [...v]);
27
31
  /** Eigenvalues of the error SSP matrix below this fraction of the largest one count as 0 */
28
32
  const REL_RANK_TOL = 1e-12;
@@ -34,7 +38,7 @@ const ABS_RANK_TOL = 1e-24;
34
38
  function column(data, name) {
35
39
  const c = Object.prototype.hasOwnProperty.call(data, name) ? data[name] : undefined;
36
40
  if (c === undefined)
37
- throw new Error(`object '${name}' not found`);
41
+ throw new RangeError(`object '${name}' not found`);
38
42
  return Array.from(c);
39
43
  }
40
44
  const label = (v) => (typeof v === "boolean" ? (v ? "TRUE" : "FALSE") : levelText(v));
@@ -58,7 +62,7 @@ function anovaTable(rows, errorSS, es, observed, unscale) {
58
62
  const isObserved = (name) => observed.some((o) => inTerm(o, name));
59
63
  for (const o of observed) {
60
64
  if (!rows.some((r) => inTerm(o, r.name)))
61
- throw new Error(`Observed variable not in data: ${o}`);
65
+ throw new RangeError(`Observed variable not in data: ${o}`);
62
66
  }
63
67
  const distinctError = [...errorSS.values()].reduce((s, v) => s + v, 0);
64
68
  const O = rows.reduce((s, r) => (isObserved(r.name) ? s + r.ss : s), 0);
@@ -97,6 +101,7 @@ function anovaTable(rows, errorSS, es, observed, unscale) {
97
101
  * @category Linear models and ANOVA
98
102
  */
99
103
  export function aovEz(data, options) {
104
+ checkOptions(options, AOV_EZ_KEYS, "aovEz"); // generated: option-keys.mjs
100
105
  const between = list(options.between);
101
106
  const within = list(options.within);
102
107
  if (between.length === 0 && within.length === 0)
@@ -105,11 +110,11 @@ export function aovEz(data, options) {
105
110
  for (const [name, names] of [["between", between], ["within", within]]) {
106
111
  const repeated = names.filter((n, i) => names.indexOf(n) !== i);
107
112
  if (repeated.length > 0)
108
- throw new Error(`duplicated factor names in '${name}': ${[...new Set(repeated)].join(", ")}`);
113
+ throw new RangeError(`duplicated factor names in '${name}': ${[...new Set(repeated)].join(", ")}`);
109
114
  }
110
115
  const both = between.filter((n) => within.includes(n));
111
116
  if (both.length > 0)
112
- throw new Error(`factors in both 'between' and 'within': ${both.join(", ")}`);
117
+ throw new RangeError(`factors in both 'between' and 'within': ${both.join(", ")}`);
113
118
  const type = options.type ?? 3;
114
119
  if (type !== 2 && type !== 3)
115
120
  throw new RangeError(`invalid type (${String(type)}): use 2 or 3`);
@@ -242,8 +247,8 @@ export function aovEz(data, options) {
242
247
  const blevelOpt = Object.fromEntries(between.map((b, k) => [b, blevels[k]]));
243
248
  const rankDeficient = "Rank deficient model matrix; insufficient data to estimate full model.";
244
249
  if (nc === 1)
245
- return betweenOnly();
246
- return withinAnalysis();
250
+ return reported("aovEz", betweenOnly());
251
+ return reported("aovEz", withinAnalysis());
247
252
  /** Without within-subject factors (or a single within cell): lm on one value per subject and car's Anova */
248
253
  function betweenOnly() {
249
254
  // a response name that is none of the between factors (with factors y and y_, "y_" replaced the factor y_, #295)
@@ -251,12 +256,12 @@ export function aovEz(data, options) {
251
256
  while (between.includes(dvName))
252
257
  dvName += "_";
253
258
  const frame = { ...bdata, [dvName]: Y.map((r) => r[0][0]) };
254
- const fit = lm(`${dvName} ~ ${between.length > 0 ? between.join(" * ") : "1"}`, frame, { contrasts: sum, levels: blevelOpt });
259
+ const fit = unreported(() => lm(`${dvName} ~ ${between.length > 0 ? between.join(" * ") : "1"}`, frame, { contrasts: sum, levels: blevelOpt }));
255
260
  if (fit.rank < fit.coefNames.length)
256
261
  throw new Error(rankDeficient);
257
262
  if (fit.dfResidual <= 0)
258
263
  throw new RangeError(`no residual degrees of freedom: ${Y.length} subject(s) for ${fit.rank} parameter(s)`);
259
- const tab = Anova(fit, { type });
264
+ const tab = unreported(() => Anova(fit, { type }));
260
265
  warnings.push(...tab.warnings.filter((w) => !warnings.includes(w)));
261
266
  const rdf = fit.dfResidual;
262
267
  const rows = tab.rowNames.flatMap((name, i) => {
@@ -282,7 +287,7 @@ export function aovEz(data, options) {
282
287
  const dataSS = Y.reduce((s, r) => r.reduce((t, v) => t + v[0] * v[0], s), 0);
283
288
  // without between factors (an empty data frame) the model matrix is the column of ones
284
289
  const X = between.length > 0
285
- ? modelMatrix(`~ ${between.join(" * ")}`, bdata, { contrasts: sum, levels: blevelOpt })
290
+ ? unreported(() => modelMatrix(`~ ${between.join(" * ")}`, bdata, { contrasts: sum, levels: blevelOpt }))
286
291
  : { colNames: ["(Intercept)"], assign: [0], x: subjects.map(() => [1]), termLabels: [], factors: [] };
287
292
  const px = X.colNames.length;
288
293
  if (n === 0 || qr(X.x).rank < px)
@@ -307,10 +312,10 @@ export function aovEz(data, options) {
307
312
  };
308
313
  // the within design over the cells
309
314
  const cdata = Object.fromEntries(within.map((w, k) => [w, cells.map((c) => c[k])]));
310
- const W = modelMatrix(`~ ${within.join(" * ")}`, cdata, {
315
+ const W = unreported(() => modelMatrix(`~ ${within.join(" * ")}`, cdata, {
311
316
  contrasts: Object.fromEntries(within.map((w) => [w, "contr.sum"])),
312
317
  levels: Object.fromEntries(within.map((w, k) => [w, wlevels[k]])),
313
- });
318
+ }));
314
319
  const wterms = [0, ...W.termLabels.map((_, j) => j + 1)];
315
320
  const wlabs = ["(Intercept)", ...W.termLabels];
316
321
  const cross = (C) => {
@@ -20,11 +20,12 @@ import { ddAdd, ddMul } from "../special/dd.js";
20
20
  import { ddLeastSquares, ddLeastSquaresMulti, ddSumSquares } from "./ddLeastSquares.js";
21
21
  import { termsOf } from "./formula.js";
22
22
  import { design } from "./modelMatrix.js";
23
+ import { rssWithinRounding } from "./anovaSequential.js";
23
24
  import { scaledTables } from "./scaledTables.js";
24
25
  /** Squared length of a column's projection on a stratum, relative to its own, below which it is not in the stratum */
25
26
  const STRATUM_TOL = 1e-14;
26
27
  /** The table of a stratum: terms that have columns in it, then Residuals when its df is positive */
27
- function stratumTable(name, zy, zcols, assign, labels, columnSS, k) {
28
+ function stratumTable(name, zy, zcols, assign, labels, columnSS, k, wy) {
28
29
  // zy is the response scaled by 2^-k: F and p come from it, the sums of squares are scaled back by 2^2k (the second
29
30
  // table keeps them as fitted, for the effect sizes: see scaledTables.ts)
30
31
  const scaleBack = (v) => ldexp(v, 2 * k);
@@ -49,8 +50,16 @@ function stratumTable(name, zy, zcols, assign, labels, columnSS, k) {
49
50
  row.ss = ddAdd(row.ss, ddMul(qty[k], qty[k]));
50
51
  });
51
52
  const rdf = dim - rank;
52
- const rss = ddSumSquares(qty, rank)[0];
53
- const rows = terms.filter((r) => r.term !== 0);
53
+ let rss = ddSumSquares(qty, rank)[0];
54
+ let rows = terms.filter((r) => r.term !== 0);
55
+ // A residual sum of squares at the level of rounding (below 1e-24 times the sum of squares of the response wy, as in
56
+ // anova and Anova: rssWithinRounding) is the residue of an exact fit in the stratum: it is taken as 0 (F = Inf),
57
+ // with the sums of squares of the terms at that level (0 / 0: F = NaN). R keeps the residue (F = 2.9e33). Other
58
+ // strata keep their bits
59
+ if (rdf > 0 && rssWithinRounding(wy, rss)) {
60
+ rss = 0;
61
+ rows = rows.map((r) => (rssWithinRounding(wy, r.ss[0]) ? { ...r, ss: [0, 0] } : r));
62
+ }
54
63
  const rowNames = rows.map((r) => labels[r.term - 1]);
55
64
  const build = (back) => {
56
65
  if (rdf > 0) {
@@ -119,6 +128,8 @@ export function aovStrataFit(formula, parsed, treatment, errorRhs, data, options
119
128
  // the response scaled by 2^-k (exact, src/internal/summary.ts), so that its sums of squares stay in range
120
129
  const { groups: scaledY, k: yScale } = scaleToUnit([y]);
121
130
  const { fit, qtv } = ddLeastSquaresMulti(kept.map((j) => toDD(ecols[j])), toDD(scaledY[0]), tcols);
131
+ // the scaled response with weights 1, for the check of a residual sum of squares at the level of rounding
132
+ const wy = scaledY[0].map((v) => [1, v]);
122
133
  // the squared length of each treatment column (the scale of its threshold in stratumTable)
123
134
  const columnSS = tcols.map((c) => ddSumSquares(c)[0]);
124
135
  // the strata: positions of Q's columns by term of the error model, then the rest
@@ -133,7 +144,7 @@ export function aovStrataFit(formula, parsed, treatment, errorRhs, data, options
133
144
  });
134
145
  if (n > re)
135
146
  groups.push({ name: "Within", idx: Array.from({ length: n - re }, (_, i) => re + i) });
136
- const both = groups.map((g) => stratumTable(g.name, g.idx.map((i) => fit.qty[i]), qtv.map((c) => g.idx.map((i) => c[i])), dt.assign, dt.terms.termLabels, columnSS, yScale));
147
+ const both = groups.map((g) => stratumTable(g.name, g.idx.map((i) => fit.qty[i]), qtv.map((c) => g.idx.map((i) => c[i])), dt.assign, dt.terms.termLabels, columnSS, yScale, wy));
137
148
  const strata = both.map((b) => b[0]);
138
149
  const result = { formula, multistratum: true, strata, rows: dt.frame.rows, warnings };
139
150
  scaledTables.set(result, both.map((b) => b[1]));
@@ -12,7 +12,11 @@ import { ldexp } from "../internal/summary.js";
12
12
  import { qr } from "../linalg/qr.js";
13
13
  import { ddAdd, ddMul, ddMulNum } from "../special/dd.js";
14
14
  import { ddLeastSquares, ddSqrtWeights } from "./ddLeastSquares.js";
15
- import { responseScale, scaledRss } from "./anovaSequential.js";
15
+ import { evenWeightExponent, responseScale, rssWithinRounding, scaledRss, weightedResponse } from "./anovaSequential.js";
16
+ import { reported } from "../internal/warnings.js";
17
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
18
+ import { checkOptions } from "../internal/checkOptions.js";
19
+ const ANOVA_KEYS = ["type"];
16
20
  /**
17
21
  * The sum of the squared effects of the columns `added` after the columns `base`, and the number of added columns
18
22
  * that are not aliased (the decrease of the residual sum of squares and the increase of the rank), for the response
@@ -66,6 +70,7 @@ function addedSS(fit, base, added, k, kw = 0) {
66
70
  * @category Linear models and ANOVA
67
71
  */
68
72
  export function Anova(fit, options = {}) {
73
+ checkOptions(options, ANOVA_KEYS, "Anova"); // generated: option-keys.mjs
69
74
  if (typeof fit !== "object" || fit === null || !Array.isArray(fit.effects)) {
70
75
  throw new TypeError("Anova() needs a fit from lm() with a formula");
71
76
  }
@@ -87,13 +92,9 @@ export function Anova(fit, options = {}) {
87
92
  // is 0 within rounding error below 1e-24 times the (weighted, uncentred) sum of squares of the response, residuals
88
93
  // below 1e-12 of the response's size (the level of aovEz's dataSS). sqrt(eps) times the centred total rejected data
89
94
  // with R^2 above 1 - 1.5e-8 that car computes (revision of review 4)
90
- const wy = fit.y.flatMap((v, i) => ((fit.weights?.[i] ?? 1) === 0 ? [] : [[fit.weights?.[i] ?? 1, ldexp(v, -k)]]));
95
+ const wy = weightedResponse(fit, k);
91
96
  // Where a sum over the weights overflows (the total of the weights of 1e308, #347), the weights are divided by an
92
97
  // even power of 2 2^kw: the sums of squares are then in units of 2^(2k + kw). kw is 0 otherwise (the same bits)
93
- const evenWeightExponent = () => {
94
- const e = Math.floor(Math.log2(wy.reduce((a, [w]) => Math.max(a, w), 0)));
95
- return e - (((e % 2) + 2) % 2);
96
- };
97
98
  const weightedTss = (kw) => {
98
99
  const ws = wy.map(([w, v]) => [ldexp(w, -kw), v]);
99
100
  const sw = ws.reduce((a, [w]) => a + w, 0);
@@ -103,19 +104,12 @@ export function Anova(fit, options = {}) {
103
104
  let kw = 0;
104
105
  let tss = weightedTss(0);
105
106
  if (!Number.isFinite(tss)) {
106
- kw = evenWeightExponent();
107
+ kw = evenWeightExponent(wy);
107
108
  tss = weightedTss(kw);
108
109
  }
109
110
  // (kw from the centred total as before, which the sums of squares of the terms use; the uncentred sum, at most
110
111
  // 16 times the total weight, takes its own even power of 2 where it overflows)
111
- const weightedSs = (kv) => wy.reduce((a, [w, v]) => a + ldexp(w, -kv) * v * v, 0);
112
- let kss = kw;
113
- let ss = weightedSs(kss);
114
- if (!Number.isFinite(ss)) {
115
- kss = evenWeightExponent();
116
- ss = weightedSs(kss);
117
- }
118
- if (!(ldexp(rss, -kss) >= 1e-24 * ss) || rss === 0)
112
+ if (rssWithinRounding(wy, rss, kw) || rss === 0)
119
113
  throw new Error("residual sum of squares is 0 (within rounding error)");
120
114
  // the fit's warnings (from its model matrix and summary) first, as for aov with Error(); R gives them when fitting
121
115
  const warnings = [...fit.warnings];
@@ -159,7 +153,7 @@ export function Anova(fit, options = {}) {
159
153
  };
160
154
  rows = termRows(kw);
161
155
  if (kw === 0 && fit.weights !== undefined && rows.some((r) => !Number.isFinite(r.ss))) {
162
- kw = evenWeightExponent();
156
+ kw = evenWeightExponent(wy);
163
157
  rows = termRows(kw);
164
158
  }
165
159
  const back = (v) => ldexp(v, 2 * k + kw);
@@ -170,5 +164,5 @@ export function Anova(fit, options = {}) {
170
164
  return [back(ss), df, f, pf1(f, df, rdf, false, false)];
171
165
  });
172
166
  table.push([back(rssW), rdf, NaN, NaN]);
173
- return { colNames: ["Sum Sq", "Df", "F value", "Pr(>F)"], rowNames: [...names, "Residuals"], table, warnings };
167
+ return reported("Anova", { colNames: ["Sum Sq", "Df", "F value", "Pr(>F)"], rowNames: [...names, "Residuals"], table, warnings }, fit);
174
168
  }
@@ -80,6 +80,12 @@ export interface CoxphResult {
80
80
  z: number[];
81
81
  /** Two-sided p-values `Pr(>|z|)` */
82
82
  p: number[];
83
+ /** Alias of `se`: the same array. */
84
+ stdError: number[];
85
+ /** Alias of `z`: the same array. */
86
+ zValue: number[];
87
+ /** Alias of `p`: the same array. */
88
+ pValue: number[];
83
89
  /** Lower confidence limits of exp(coef) */
84
90
  lower: number[];
85
91
  /** Upper confidence limits of exp(coef) */
@@ -14,8 +14,12 @@ import { qnorm } from "../distributions/normal.js";
14
14
  import { numberLevels } from "../internal/levels.js";
15
15
  import { ldexp, mean, scaleToUnit } from "../internal/summary.js";
16
16
  import { mergeTiedTimes } from "./tiedTimes.js";
17
- import { Warnings } from "./glmFamily.js";
17
+ import { reported, Warnings } from "../internal/warnings.js";
18
18
  import { maxOf } from "../internal/extremes.js";
19
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
20
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
21
+ const COXPH_KEYS = ["ties", "weights", "strata", "init", "control", "nocenter", "confLevel"];
22
+ const COXPH_CONTROL_KEYS = ["eps", "iterMax", "tolerChol", "tolerInf"];
19
23
  const isMissingLabel = (v) => v === null || v === undefined || (typeof v === "number" && Number.isNaN(v));
20
24
  const compareLabels = (a, b) => typeof a === "number" && typeof b === "number" ? a - b : String(a) < String(b) ? -1 : String(a) > String(b) ? 1 : 0;
21
25
  /** Distance of eta from the shift of the risk sums beyond which exp would leave (or near) the doubles (e^709.8 overflows) */
@@ -245,6 +249,9 @@ function zeroEventResult(rows, p) {
245
249
  const n = rows.length;
246
250
  const nans = () => new Array(p).fill(NaN);
247
251
  const test = chisqTest(0, 0);
252
+ const se = new Array(p).fill(0);
253
+ const z = nans();
254
+ const pz = nans();
248
255
  return {
249
256
  coefficients: nans(),
250
257
  var: Array.from({ length: p }, () => new Array(p).fill(0)),
@@ -256,9 +263,12 @@ function zeroEventResult(rows, p) {
256
263
  n,
257
264
  nevent: 0,
258
265
  linearPredictors: new Array(n).fill(0),
259
- se: new Array(p).fill(0),
260
- z: nans(),
261
- p: nans(),
266
+ se,
267
+ z,
268
+ p: pz,
269
+ stdError: se,
270
+ zValue: z,
271
+ pValue: pz,
262
272
  lower: nans(),
263
273
  upper: nans(),
264
274
  logtest: test,
@@ -293,6 +303,8 @@ function zeroEventResult(rows, p) {
293
303
  * @category Survival analysis
294
304
  */
295
305
  export function coxph(time, status, x, options = {}) {
306
+ checkOptions(options, COXPH_KEYS, "coxph"); // generated: option-keys.mjs
307
+ checkOptions(nestedOptions(options, "control"), COXPH_CONTROL_KEYS, "coxph", "control"); // generated: option-keys.mjs
296
308
  const { ties = "efron", weights, strata, init, control = {}, nocenter = [-1, 0, 1], confLevel = 0.95 } = options;
297
309
  const { eps = 1e-9, iterMax = 20, tolerChol = 2 ** -39 } = control;
298
310
  const tolerInf = control.tolerInf ?? Math.sqrt(eps);
@@ -567,7 +579,7 @@ export function coxph(time, status, x, options = {}) {
567
579
  const lower = coefficients.map((c, j) => Math.exp(c - q * se[j]));
568
580
  const upper = coefficients.map((c, j) => Math.exp(c + q * se[j]));
569
581
  const lr = -2 * (loglik[0] - loglik[1]);
570
- return {
582
+ return reported("coxph", {
571
583
  coefficients,
572
584
  var: variance,
573
585
  loglik,
@@ -581,6 +593,9 @@ export function coxph(time, status, x, options = {}) {
581
593
  se,
582
594
  z,
583
595
  p: pz,
596
+ stdError: se,
597
+ zValue: z,
598
+ pValue: pz,
584
599
  lower,
585
600
  upper,
586
601
  logtest: chisqTest(lr, k),
@@ -588,5 +603,5 @@ export function coxph(time, status, x, options = {}) {
588
603
  waldtest: chisqTest(wald, k),
589
604
  rsq: { rsq: 1 - Math.exp(-lr / n), maxrsq: 1 - Math.exp((2 * loglik[0]) / n) },
590
605
  warnings: warnings.list,
591
- };
606
+ });
592
607
  }
@@ -33,8 +33,10 @@ export type FormulaNode = {
33
33
  };
34
34
  /** A parsed formula before expansion. */
35
35
  export interface ParsedFormula {
36
- /** The response's name (undefined for `~ rhs`). */
36
+ /** The response's name (undefined for `~ rhs`); for `cbind(a, b) ~ rhs`, the first column `a`. */
37
37
  response: string | undefined;
38
+ /** The two columns of a response `cbind(a, b)` (only with `allowCbind`). */
39
+ responseColumns?: [string, string];
38
40
  /** The right-hand side. */
39
41
  rhs: FormulaNode;
40
42
  }
@@ -44,8 +46,9 @@ export interface ParsedFormula {
44
46
  *
45
47
  * @param allowError Accept `Error(...)` terms (aov only).
46
48
  * @param allowBars Accept the random-effects terms `(lhs | group)` and `(lhs || group)` (mixed models only).
49
+ * @param allowCbind Accept the response `cbind(a, b)` with two column names (generalised linear mixed models only).
47
50
  */
48
- export declare function parseFormula(formula: string, allowError?: boolean, allowBars?: boolean): ParsedFormula;
51
+ export declare function parseFormula(formula: string, allowError?: boolean, allowBars?: boolean, allowCbind?: boolean): ParsedFormula;
49
52
  /** The `Error()` terms of a right-hand side (summands, possibly in parentheses) and the right-hand side without them. */
50
53
  export declare function splitErrorTerms(rhs: FormulaNode): {
51
54
  treatment: FormulaNode | undefined;
@@ -12,6 +12,10 @@
12
12
  // "Formulas with random-effects terms") are parsed only when asked for: `|` and `||` bind more loosely than every
13
13
  // other operator, `splitBarTerms` separates them from the fixed-effects part, and `deparseFormula` prints a node as
14
14
  // R deparses it (for the terms' labels).
15
+ //
16
+ // The two-column binomial response of generalised linear mixed models, `cbind(successes, failures) ~ ...`, is parsed
17
+ // only when asked for, as the one function call allowed, on the left-hand side and with two column names (rStats.js's
18
+ // choice G1 in oracle/glmer-behaviour.md; R evaluates any expression there).
15
19
  import { formatR } from "../htest/core/simulate.js";
16
20
  const invalid = (why) => new SyntaxError(`invalid formula: ${why}`);
17
21
  /**
@@ -21,7 +25,7 @@ const invalid = (why) => new SyntaxError(`invalid formula: ${why}`);
21
25
  * digits, but no combining marks and nothing outside the BMP (R on Linux takes both, from glibc's tables).
22
26
  */
23
27
  const NAME = /^(?:[\p{L}\p{Nl}.]|(?![0-9])\p{Nd})[\p{L}\p{Nl}\p{Nd}\p{M}._]*/u;
24
- function tokenize(s, allowBars) {
28
+ function tokenize(s, allowBars, allowComma = false) {
25
29
  const out = [];
26
30
  let i = 0;
27
31
  while (i < s.length) {
@@ -53,7 +57,7 @@ function tokenize(s, allowBars) {
53
57
  i += text.length;
54
58
  continue;
55
59
  }
56
- if ("~+-*/:^()".includes(c)) {
60
+ if ("~+-*/:^()".includes(c) || (allowComma && c === ",")) {
57
61
  out.push({ kind: "op", text: c });
58
62
  i++;
59
63
  continue;
@@ -72,11 +76,12 @@ const UNARY = 5;
72
76
  *
73
77
  * @param allowError Accept `Error(...)` terms (aov only).
74
78
  * @param allowBars Accept the random-effects terms `(lhs | group)` and `(lhs || group)` (mixed models only).
79
+ * @param allowCbind Accept the response `cbind(a, b)` with two column names (generalised linear mixed models only).
75
80
  */
76
- export function parseFormula(formula, allowError = false, allowBars = false) {
81
+ export function parseFormula(formula, allowError = false, allowBars = false, allowCbind = false) {
77
82
  if (typeof formula !== "string")
78
83
  throw new TypeError("the formula must be a string");
79
- const toks = tokenize(formula, allowBars);
84
+ const toks = tokenize(formula, allowBars, allowCbind);
80
85
  let pos = 0;
81
86
  const peek = () => toks[pos];
82
87
  const next = () => toks[pos++];
@@ -129,7 +134,21 @@ export function parseFormula(formula, allowError = false, allowBars = false) {
129
134
  return left;
130
135
  }
131
136
  let response;
132
- if (!isOp(peek(), "~")) {
137
+ let responseColumns;
138
+ const t0 = toks[0];
139
+ if (allowCbind && t0.kind === "name" && t0.text === "cbind" && isOp(toks[1], "(")) {
140
+ // cbind(a, b) ~: two column names (a comma is a token only here; anywhere else it is unexpected)
141
+ const a = toks[2];
142
+ const b = toks[4];
143
+ const isName = (t) => t.kind === "name" && t.text !== "." && !/^\.[0-9]/.test(t.text);
144
+ if (!(isName(a) && isOp(toks[3], ",") && isName(b) && isOp(toks[5], ")") && isOp(toks[6], "~"))) {
145
+ throw invalid("the response cbind() must have two column names: cbind(successes, failures)");
146
+ }
147
+ responseColumns = [a.text, b.text];
148
+ response = responseColumns[0];
149
+ pos = 6;
150
+ }
151
+ else if (!isOp(peek(), "~")) {
133
152
  const t = next();
134
153
  if (t.kind !== "name" || t.text === "." || !isOp(peek(), "~"))
135
154
  throw invalid("the response must be a variable name followed by '~'");
@@ -139,7 +158,7 @@ export function parseFormula(formula, allowError = false, allowBars = false) {
139
158
  const rhs = expr(0);
140
159
  if (peek().kind !== "end")
141
160
  throw invalid("unexpected input after the formula");
142
- return { response, rhs };
161
+ return responseColumns === undefined ? { response, rhs } : { response, responseColumns, rhs };
143
162
  }
144
163
  /** The `Error()` terms of a right-hand side (summands, possibly in parentheses) and the right-hand side without them. */
145
164
  export function splitErrorTerms(rhs) {
@@ -431,9 +450,13 @@ export function expandRhs(rhs, index, dot) {
431
450
  * @param rhs The right-hand side to expand (default: the parsed formula's).
432
451
  */
433
452
  export function termsOf(parsed, columns, rhs = parsed.rhs) {
434
- const { response } = parsed;
435
- const dot = columns.filter((c) => c !== response);
453
+ const { response, responseColumns } = parsed;
454
+ // (`.` stands for the columns that are not in the response, both of cbind(a, b))
455
+ const dot = columns.filter((c) => c !== response && !(responseColumns?.includes(c) ?? false));
456
+ // the response first; the second column of cbind(a, b) next, so that the model frame drops its missing rows too
436
457
  const variables = response === undefined ? [] : [response];
458
+ if (responseColumns !== undefined && responseColumns[1] !== response)
459
+ variables.push(responseColumns[1]);
437
460
  collectVariables(parsed.rhs, dot, variables);
438
461
  const index = (name) => variables.indexOf(name);
439
462
  const expanded = expandRhs(rhs, index, dot);
@@ -1,7 +1,8 @@
1
1
  import type { MatrixInput } from "../linalg/matrix.js";
2
2
  import { type QR } from "../linalg/qr.js";
3
3
  import type { Sample } from "../htest/types.js";
4
- import { Warnings, type Family, type GlmFamilyName, type GlmFamilySpec, type GlmLink } from "./glmFamily.js";
4
+ import { type Family, type GlmFamilyName, type GlmFamilySpec, type GlmLink } from "./glmFamily.js";
5
+ import { Warnings } from "../internal/warnings.js";
5
6
  export type { GlmFamilyName, GlmFamilySpec, GlmLink, GlmLinkName, QuasiVariance } from "./glmFamily.js";
6
7
  /**
7
8
  * Options for {@link glm}.
@@ -274,9 +275,18 @@ export declare function glmSummary(given: GlmResult, options?: GlmSummaryOptions
274
275
  * @category Generalized linear models
275
276
  */
276
277
  export type GlmResidualType = "deviance" | "pearson" | "working" | "response";
278
+ /**
279
+ * Options for {@link glmResiduals}.
280
+ *
281
+ * @category Generalized linear models
282
+ */
283
+ export interface GlmResidualsOptions {
284
+ /** Kind of residuals. Default `"deviance"`. */
285
+ type?: GlmResidualType;
286
+ }
277
287
  /**
278
288
  * Residuals of a generalized linear model, one per row, for a `glm` fit (default `"deviance"`). Equivalent to R's
279
- * `residuals(fit, type)`.
289
+ * `residuals(fit, type)`. The kind is the second argument or the option `type` (giving both is a RangeError).
280
290
  *
281
291
  * @example
282
292
  * ```ts
@@ -288,6 +298,16 @@ export type GlmResidualType = "deviance" | "pearson" | "working" | "response";
288
298
  * @category Generalized linear models
289
299
  */
290
300
  export declare function glmResiduals(fit: GlmResult, type?: GlmResidualType): number[];
301
+ /**
302
+ * Residuals of a generalized linear model, with the kind in the options: `glmResiduals(fit, { type: "pearson" })`.
303
+ *
304
+ * @example
305
+ * ```ts
306
+ * const fit = glm([1, 2, 3, 4, 5, 6], [0, 0, 1, 0, 1, 1], { family: "binomial" });
307
+ * glmResiduals(fit, { type: "pearson" }); // [-0.21925, -0.40231, 1.3546, -1.3546, 0.40231, 0.21925]
308
+ * ```
309
+ */
310
+ export declare function glmResiduals(fit: GlmResult, options: GlmResidualsOptions): number[];
291
311
  /**
292
312
  * Diagonal of the hat matrix of the last weighted least squares step, for the rows of non-zero prior weight, for a
293
313
  * `glm` fit. Equivalent to R's `hatvalues()`.
@@ -10,11 +10,24 @@ import { pt1 } from "../distributions/t.js";
10
10
  import { pnorm } from "../distributions/normal.js";
11
11
  import { chol2invColumns } from "../internal/scaledInverse.js";
12
12
  import { qr, qrCoef, qrQy } from "../linalg/qr.js";
13
- import { familyAic, makeFamily, prepareResponse, Warnings, withWarnings, } from "./glmFamily.js";
13
+ import { familyAic, makeFamily, prepareResponse, } from "./glmFamily.js";
14
14
  import { maxOf } from "../internal/extremes.js";
15
+ import { reported, Warnings, withWarnings } from "../internal/warnings.js";
16
+ import { optionalArgs } from "../internal/optionalArgs.js";
15
17
  import { ldexp, ldexpWide, scaleToUnit } from "../internal/summary.js";
16
18
  import { NON_ESTIMABLE_WARNING, nonEstimableRows } from "./estimable.js";
17
19
  import { checkDot, checkedDot } from "../linalg/dot.js";
20
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
21
+ import { checkOptions, nestedOptions } from "../internal/checkOptions.js";
22
+ import { optionsIn } from "../internal/optionalArgs.js";
23
+ const GLM_KEYS = ["family", "link", "weights", "offset", "start", "epsilon", "maxit", "intercept"];
24
+ const GLM_FAMILY_KEYS = ["family", "link", "variance"];
25
+ const GLM_FAMILY_LINK_KEYS = ["power"];
26
+ const GLM_SUMMARY_KEYS = ["dispersion"];
27
+ const GLM_RESIDUALS_KEYS = ["type"];
28
+ const GLM_RSTANDARD_KEYS = ["dispersion"];
29
+ const GLM_COOKS_DISTANCE_KEYS = ["dispersion"];
30
+ const GLM_PREDICT_KEYS = ["newdata", "newoffset", "type", "dispersion"];
18
31
  const EPS = 2 ** -52;
19
32
  function deparseNames(names) {
20
33
  const q = names.map((s) => `"${s}"`);
@@ -381,6 +394,10 @@ export function refit(model, cols, warnings, control = {}) {
381
394
  * @category Generalized linear models
382
395
  */
383
396
  export function glm(x, y, options = {}) {
397
+ checkOptions(options, GLM_KEYS, "glm"); // generated: option-keys.mjs
398
+ checkOptions(nestedOptions(options, "family"), GLM_FAMILY_KEYS, "glm", "family"); // generated: option-keys.mjs
399
+ checkOptions(nestedOptions(options, "family.link"), GLM_FAMILY_LINK_KEYS, "glm", "family.link"); // generated: option-keys.mjs
400
+ checkOptions(nestedOptions(options, "link"), GLM_FAMILY_LINK_KEYS, "glm", "link"); // generated: option-keys.mjs
384
401
  const intercept = options.intercept ?? true;
385
402
  const xr = toRows(x);
386
403
  // the shape of all the rows given, before the rows with a missing value are dropped (#463)
@@ -445,7 +462,7 @@ export function glm(x, y, options = {}) {
445
462
  // (exact; src/internal/summary.ts), so that the deviance stays in range; see scaledView
446
463
  const k = !yIsMatrix && scalesWithResponse(familySpec) ? scaleToUnit([yGiven]).k : 0;
447
464
  if (k === 0)
448
- return fitModel(model);
465
+ return reported("glm", fitModel(model));
449
466
  const down = (v) => ldexp(v, -k);
450
467
  const scaled = fitModel({
451
468
  ...model,
@@ -453,7 +470,7 @@ export function glm(x, y, options = {}) {
453
470
  offset: offset.map(down),
454
471
  start: model.start?.map(down),
455
472
  });
456
- return unscaledResult(scaled, k, { ...model, yScale: k });
473
+ return reported("glm", unscaledResult(scaled, k, { ...model, yScale: k }));
457
474
  }
458
475
  /** The fit of a model (the part of glm after its checks) */
459
476
  function fitModel(model) {
@@ -676,6 +693,7 @@ export function scaledDispersion(d, k) {
676
693
  * @category Generalized linear models
677
694
  */
678
695
  export function glmSummary(given, options = {}) {
696
+ checkOptions(options, GLM_SUMMARY_KEYS, "glmSummary"); // generated: option-keys.mjs
679
697
  // computed on the scaled fit (scaledView); estimates, standard errors and the dispersion scaled back
680
698
  const { fit, k } = scaledView(given);
681
699
  const warnings = new Warnings();
@@ -702,7 +720,7 @@ export function glmSummary(given, options = {}) {
702
720
  }
703
721
  const up = (v) => ldexp(v, k);
704
722
  const up2 = (v) => ldexp(v, 2 * k);
705
- return {
723
+ return reported("glmSummary", {
706
724
  dispersion: s === 0 ? up2(dispersion) : options.dispersion,
707
725
  estimate: estimate.map(up),
708
726
  // (with s != 0 in the original units at once: sqrt(inv m) 2^(s + k - e))
@@ -717,22 +735,11 @@ export function glmSummary(given, options = {}) {
717
735
  : inv.map((r, j) => r.map((v, l) => ldexpWide(v * dispersion, 2 * (s + k) - e[j] - e[l]))),
718
736
  dfResidual: fit.dfResidual,
719
737
  warnings: warnings.list,
720
- };
738
+ }, given);
721
739
  }
722
- /**
723
- * Residuals of a generalized linear model, one per row, for a `glm` fit (default `"deviance"`). Equivalent to R's
724
- * `residuals(fit, type)`.
725
- *
726
- * @example
727
- * ```ts
728
- * const fit = glm([1, 2, 3, 4, 5, 6], [0, 0, 1, 0, 1, 1], { family: "binomial" });
729
- * glmResiduals(fit); // [-0.30644, -0.54776, 1.4436, -1.4436, 0.54776, 0.30644]
730
- * glmResiduals(fit, "pearson"); // [-0.21925, -0.40231, 1.3546, -1.3546, 0.40231, 0.21925]
731
- * ```
732
- *
733
- * @category Generalized linear models
734
- */
735
- export function glmResiduals(fit, type = "deviance") {
740
+ export function glmResiduals(fit, ...args) {
741
+ checkOptions(optionsIn(args), GLM_RESIDUALS_KEYS, "glmResiduals"); // generated: option-keys.mjs
742
+ const type = optionalArgs(["type"], args).type ?? "deviance";
736
743
  // of the scaled fit (scaledView), scaled back: for the families that are scaled, every kind has the response's units
737
744
  const v = scaledView(fit);
738
745
  return residualsOf(v.fit, type).map((r) => ldexp(r, v.k));
@@ -805,6 +812,7 @@ function median(v) {
805
812
  * @category Generalized linear models
806
813
  */
807
814
  export function glmRstandard(given, options = {}) {
815
+ checkOptions(options, GLM_RSTANDARD_KEYS, "glmRstandard"); // generated: option-keys.mjs
808
816
  // on the scaled fit (scaledView): the standardized residuals have no units
809
817
  const { fit, k } = scaledView(given);
810
818
  const h = glmHatvalues(fit);
@@ -830,6 +838,7 @@ export function glmRstandard(given, options = {}) {
830
838
  * @category Generalized linear models
831
839
  */
832
840
  export function glmCooksDistance(given, options = {}) {
841
+ checkOptions(options, GLM_COOKS_DISTANCE_KEYS, "glmCooksDistance"); // generated: option-keys.mjs
833
842
  // on the scaled fit (scaledView): Cook's distances have no units
834
843
  const { fit, k } = scaledView(given);
835
844
  const h = glmHatvalues(fit);
@@ -875,6 +884,7 @@ function cookScaled(r, h, d, p) {
875
884
  * @category Generalized linear models
876
885
  */
877
886
  export function glmPredict(given, options = {}) {
887
+ checkOptions(options, GLM_PREDICT_KEYS, "glmPredict"); // generated: option-keys.mjs
878
888
  // on the scaled fit (scaledView), with the new offset and the dispersion scaled alike; predictions and standard
879
889
  // errors scaled back (the families that are scaled use the identity link)
880
890
  const { fit, k } = scaledView(given);
@@ -939,10 +949,10 @@ export function glmPredict(given, options = {}) {
939
949
  const nonEstimable = options.newdata === undefined ? [] : nonEstimableRows(fit.qr, rank, X);
940
950
  const extra = nonEstimable.length > 0 ? { nonEstimable, warnings: [NON_ESTIMABLE_WARNING] } : {};
941
951
  if (type === "link")
942
- return { fit: eta.map(up), seFit: se.map(upSe), ...extra };
943
- return withWarnings(new Warnings(), () => ({
952
+ return reported("glmPredict", { fit: eta.map(up), seFit: se.map(upSe), ...extra }, given);
953
+ return reported("glmPredict", withWarnings(new Warnings(), () => ({
944
954
  fit: eta.map((e) => up(fam.linkinv(e))),
945
955
  seFit: se.map((s, i) => upSe(s * Math.abs(fam.muEta(eta[i])))),
946
956
  ...extra,
947
- }));
957
+ })), given);
948
958
  }
@@ -10,8 +10,12 @@ import { pgamma1 } from "../distributions/gamma.js";
10
10
  import { ldexp, ldexpWide } from "../internal/summary.js";
11
11
  import { nestedColumns } from "./estimable.js";
12
12
  import { glmDispersion, refit, scaledDispersion, scaledView } from "./glm.js";
13
- import { makeFamily, Warnings } from "./glmFamily.js";
13
+ import { makeFamily } from "./glmFamily.js";
14
+ import { reported, Warnings } from "../internal/warnings.js";
14
15
  import { scoreStatistic } from "./glmConfint.js";
16
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
17
+ import { checkOptions } from "../internal/checkOptions.js";
18
+ const GLM_ANOVA_KEYS = ["test", "dispersion"];
15
19
  /** Upper tail of chi-squared with df degrees of freedom */
16
20
  const pchisqUpper = (q, df) => pgamma1(q, df / 2, 2, false, false);
17
21
  /**
@@ -48,6 +52,7 @@ const rao = (small, large) => scoreStatistic(large.x, small.fit.workingResiduals
48
52
  * @category Generalized linear models
49
53
  */
50
54
  export function glmAnova(fits, options = {}) {
55
+ checkOptions(options, GLM_ANOVA_KEYS, "glmAnova"); // generated: option-keys.mjs
51
56
  const given = Array.isArray(fits) ? fits : [fits];
52
57
  if (given.length === 0)
53
58
  throw new RangeError("no fits to compare");
@@ -61,7 +66,7 @@ export function glmAnova(fits, options = {}) {
61
66
  const shift = user?.s ?? 0;
62
67
  const table = glmAnovaScaled(list, Array.isArray(fits) && list.length > 1, { ...options, ...(user === undefined ? {} : { dispersion: user.m }) }, shift);
63
68
  if (k === 0 && shift === 0)
64
- return table;
69
+ return reported("glmAnova", table, ...given);
65
70
  const squared = new Set(["Deviance", "Resid. Dev", "Rao", "Cp"]);
66
71
  const cols = table.colNames.map((c) => squared.has(c));
67
72
  const scaledBack = table.table.map((r) => r.map((v, j) => (cols[j] ? ldexp(v, 2 * k) : v)));
@@ -74,7 +79,7 @@ export function glmAnova(fits, options = {}) {
74
79
  for (const r of scaledBack)
75
80
  r[cp] = r[dev] + 2 * (n - r[dfRes]) * options.dispersion;
76
81
  }
77
- return { ...table, table: scaledBack };
82
+ return reported("glmAnova", { ...table, table: scaledBack }, ...given);
78
83
  }
79
84
  function glmAnovaScaled(list, compare, options, shift = 0) {
80
85
  const warnings = new Warnings();