@numero-uno-jpn/rstats 1.2.0 → 1.4.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 (89) hide show
  1. package/CHANGELOG.md +128 -0
  2. package/README.ja.md +28 -11
  3. package/README.md +27 -10
  4. package/dist/chunks/{chunk-RRO4LMCB.js → chunk-27VFB3SA.js} +2 -2
  5. package/dist/chunks/{chunk-BKV3FINA.js → chunk-56GFP4UU.js} +2 -2
  6. package/dist/chunks/{chunk-JWBSEL3V.js → chunk-5SW3L6J3.js} +2 -2
  7. package/dist/chunks/{chunk-NSU6U3ET.js → chunk-6FZAJQ4H.js} +2 -2
  8. package/dist/chunks/{chunk-VERBXW6E.js → chunk-BQJFFGYP.js} +2 -2
  9. package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-F6Z3GLWA.js} +2 -2
  10. package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-GBSMRVUY.js} +2 -2
  11. package/dist/chunks/{chunk-7WG7X2UI.js → chunk-GEF2YRBV.js} +2 -2
  12. package/dist/chunks/{chunk-L23RSC2N.js → chunk-GIER5WMB.js} +2 -2
  13. package/dist/chunks/{chunk-IAWXF73N.js → chunk-GLGOV3A5.js} +2 -2
  14. package/dist/chunks/{chunk-F3EQLL4F.js → chunk-H72MW7YP.js} +2 -2
  15. package/dist/chunks/{chunk-T5DRIITM.js → chunk-HWB7XRX2.js} +2 -2
  16. package/dist/chunks/chunk-J72MLFUG.js +2 -0
  17. package/dist/chunks/{chunk-TNETWBF5.js → chunk-PZ66PUWC.js} +2 -2
  18. package/dist/chunks/{chunk-IMPRIQE5.js → chunk-RUZATICF.js} +1 -1
  19. package/dist/chunks/{chunk-BI7NYJWP.js → chunk-RY7CCWVU.js} +1 -1
  20. package/dist/chunks/{chunk-7INBXTVV.js → chunk-S2YCFUCA.js} +2 -2
  21. package/dist/chunks/chunk-SVS54D6Z.js +2 -0
  22. package/dist/chunks/{chunk-HBHMEPGY.js → chunk-TEHMTQNB.js} +3 -3
  23. package/dist/chunks/chunk-UMMCVF53.js +2 -0
  24. package/dist/chunks/{chunk-5SGTWSCB.js → chunk-UNP4HBPP.js} +2 -2
  25. package/dist/chunks/{chunk-A66M3ZEA.js → chunk-V2KVTAVV.js} +2 -2
  26. package/dist/chunks/{chunk-EEU7D4RU.js → chunk-WWJGCBWH.js} +1 -1
  27. package/dist/chunks/chunk-X7K6EF7S.js +2 -0
  28. package/dist/chunks/{chunk-73LNRWU3.js → chunk-YBOSCQF2.js} +1 -1
  29. package/dist/chunks/{chunk-6FZHTD5G.js → chunk-ZQSOMEIM.js} +2 -2
  30. package/dist/chunks/{chunk-4AOTAT3O.js → chunk-ZRFZ5UIB.js} +2 -2
  31. package/dist/descriptive.js +2 -2
  32. package/dist/distributions.js +2 -2
  33. package/dist/entries/tests.d.ts +13 -0
  34. package/dist/entries/tests.js +13 -0
  35. package/dist/htest/agreement.d.ts +2 -2
  36. package/dist/htest/blandAltman.d.ts +100 -0
  37. package/dist/htest/blandAltman.js +159 -0
  38. package/dist/htest/diagnosticTests.d.ts +91 -0
  39. package/dist/htest/diagnosticTests.js +116 -0
  40. package/dist/htest/iccPsych.d.ts +106 -0
  41. package/dist/htest/iccPsych.js +332 -0
  42. package/dist/htest/ksTest.d.ts +1 -1
  43. package/dist/htest/mcreg.d.ts +209 -0
  44. package/dist/htest/mcreg.js +735 -0
  45. package/dist/htest/roc.d.ts +287 -0
  46. package/dist/htest/roc.js +635 -0
  47. package/dist/htest/rocTest.d.ts +139 -0
  48. package/dist/htest/rocTest.js +444 -0
  49. package/dist/htest/tTOST.d.ts +202 -0
  50. package/dist/htest/tTOST.js +558 -0
  51. package/dist/htest/trendTests.d.ts +1 -1
  52. package/dist/htest/trendTests.js +1 -1
  53. package/dist/internal/summary.js +5 -0
  54. package/dist/linalg/qr.d.ts +3 -0
  55. package/dist/linalg/qr.js +3 -0
  56. package/dist/linalg.js +2 -2
  57. package/dist/mixed.js +2 -2
  58. package/dist/models/coeftest.d.ts +139 -0
  59. package/dist/models/coeftest.js +237 -0
  60. package/dist/models/competingRisks.d.ts +188 -0
  61. package/dist/models/competingRisks.js +673 -0
  62. package/dist/models/coxZph.d.ts +67 -0
  63. package/dist/models/coxZph.js +479 -0
  64. package/dist/models/coxph.d.ts +107 -16
  65. package/dist/models/coxph.js +641 -72
  66. package/dist/models/glm.d.ts +11 -1
  67. package/dist/models/glm.js +19 -2
  68. package/dist/models/inputRows.d.ts +10 -0
  69. package/dist/models/inputRows.js +23 -0
  70. package/dist/models/lm.d.ts +8 -0
  71. package/dist/models/lm.js +14 -2
  72. package/dist/models/rmst2.d.ts +126 -0
  73. package/dist/models/rmst2.js +365 -0
  74. package/dist/models/sandwich.d.ts +177 -0
  75. package/dist/models/sandwich.js +923 -0
  76. package/dist/models/survival.d.ts +65 -24
  77. package/dist/models/survival.js +407 -72
  78. package/dist/models/survreg.d.ts +160 -0
  79. package/dist/models/survreg.js +809 -0
  80. package/dist/numerics.js +2 -2
  81. package/dist/random/rng.d.ts +8 -1
  82. package/dist/random/rng.js +14 -1
  83. package/dist/rstats.js +16 -16
  84. package/dist/special.js +2 -2
  85. package/dist/tests.js +13 -13
  86. package/llms.txt +25 -0
  87. package/package.json +1 -1
  88. package/dist/chunks/chunk-47IIPUFN.js +0 -2
  89. package/dist/chunks/chunk-CQB4BJBR.js +0 -2
@@ -0,0 +1,332 @@
1
+ // The six intraclass correlations of Shrout and Fleiss (psych's ICC): one-way and two-way, single and average
2
+ // raters, with their F tests and confidence intervals, from the ANOVA mean squares or from REML variance components.
3
+ //
4
+ // Written for rStats.js from oracle/methodcomparison-behaviour.md, section 3 (no R or package code), and the papers:
5
+ // - Shrout PE, Fleiss JL (1979) Intraclass correlations: uses in assessing rater reliability. Psychological Bulletin
6
+ // 86:420-428: the six forms, their F tests and intervals, ICC2's interval with Satterthwaite's df v.
7
+ // - The REML estimates of the balanced crossed model y = mu + s_i + r_j + e_ij: the REML likelihood of balanced data is
8
+ // that of the three independent mean squares MS_t ~ lambda_t chi^2(df_t)/df_t, lambda_B = k s2_s + s2_e, lambda_J =
9
+ // n s2_r + s2_e, lambda_E = s2_e (Searle, Casella and McCulloch 1992, Variance Components, ch. 6). The constraints
10
+ // s2_s, s2_r >= 0 are lambda_E <= lambda_B and lambda_E <= lambda_J, and the maximum under this order is the
11
+ // weighted isotonic regression of the mean squares with weights df_t (Robertson, Wright and Dykstra 1988, Order
12
+ // Restricted Statistical Inference, ch. 1): the residual mean square is pooled with each of the others, smallest
13
+ // first, that lies below the pooled value. Without pooling these are the ANOVA mean squares.
14
+ import { pf1, qf1 } from "../distributions/f.js";
15
+ import { ldexp, ldexpWide, scaleToUnit } from "../internal/summary.js";
16
+ import { reported } from "../internal/warnings.js";
17
+ import { ddAdd, ddDivNum, ddMul, ddSub } from "../special/dd.js";
18
+ import { checkConfLevelOpen } from "./types.js";
19
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
20
+ import { checkOptions } from "../internal/checkOptions.js";
21
+ const ICC_KEYS = ["alpha", "confLevel", "lmer"];
22
+ const NAMES = {
23
+ ICC1: "Single_raters_absolute",
24
+ ICC2: "Single_random_raters",
25
+ ICC3: "Single_fixed_raters",
26
+ ICC1k: "Average_raters_absolute",
27
+ ICC2k: "Average_random_raters",
28
+ ICC3k: "Average_fixed_raters",
29
+ };
30
+ /** a - b exactly, as an unevaluated sum [s, e] (Knuth's two-sum; error-free whatever the double-double switch) */
31
+ function exactDiff(a, b) {
32
+ const s = a - b;
33
+ const bb = s - a;
34
+ return [s, a - (s - bb) + (-b - bb)];
35
+ }
36
+ /** Whether the ratings are additive, x_ij - x_i1 = x_1j - x_11 for all i, j (the residual mean square is then 0) */
37
+ function isAdditive(rows) {
38
+ const r0 = rows[0];
39
+ return rows.every((r) => r.every((v, j) => {
40
+ const [s1, e1] = exactDiff(v, r[0]);
41
+ const [s2, e2] = exactDiff(r0[j], r0[0]);
42
+ return s1 === s2 && e1 === e2;
43
+ }));
44
+ }
45
+ const sameArray = (a, b) => a.every((v, i) => v === b[i]);
46
+ /** Mean of double-doubles */
47
+ function meanOfDD(v) {
48
+ let s = [0, 0];
49
+ for (const u of v)
50
+ s = ddAdd(s, u);
51
+ return ddDivNum(s, v.length);
52
+ }
53
+ const sDiv = (s, d) => ({ v: ddDivNum(s.v, d), e: s.e });
54
+ /**
55
+ * The values brought to the largest scale among them (zeros do not count), as doubles `at` in units 2^E: the smaller
56
+ * ones lose only the digits (or the whole value) that are negligible beside the largest
57
+ */
58
+ function inCommon(...s) {
59
+ const nz = s.filter((t) => t.v[0] !== 0);
60
+ const E = nz.length === 0 ? 0 : Math.max(...nz.map((t) => t.e));
61
+ return s.map((t) => ({ at: ldexpWide(t.v[0], t.e - E), E }));
62
+ }
63
+ /** a + b, at the larger of their scales (in double-double) */
64
+ function sAdd(a, b) {
65
+ if (b.v[0] === 0)
66
+ return a;
67
+ if (a.v[0] === 0)
68
+ return b;
69
+ const E = Math.max(a.e, b.e);
70
+ const to = (t) => [ldexpWide(t.v[0], t.e - E), ldexpWide(t.v[1], t.e - E)];
71
+ return { v: ddAdd(to(a), to(b)), e: E };
72
+ }
73
+ /** a/b (Infinity for b = 0 < a, NaN for 0/0), formed from the ratio of the parts and one power of 2 */
74
+ const sRatio = (a, b) => ldexpWide(a.v[0] / b.v[0], a.e - b.e);
75
+ const sLess = (a, b) => {
76
+ const [x, y] = inCommon(a, b);
77
+ return x.at < y.at;
78
+ };
79
+ const sLessEq = (a, b) => {
80
+ const [x, y] = inCommon(a, b);
81
+ return x.at <= y.at;
82
+ };
83
+ /** Sum of squared deviations of the means m from g, times w, in double-double */
84
+ function ssOfMeans(m, g, w) {
85
+ let s = [0, 0];
86
+ for (const v of m) {
87
+ const d = ddSub(v, g);
88
+ s = ddAdd(s, ddMul(d, d));
89
+ }
90
+ return ddMul(s, [w, 0]);
91
+ }
92
+ /**
93
+ * The six intraclass correlations of Shrout and Fleiss (1979), with their F tests and confidence intervals.
94
+ * Equivalent to `psych::ICC(x, alpha, lmer)` in R. Only complete data are accepted.
95
+ *
96
+ * `x` is an n × k matrix (an array of rows): the ratings of the k raters for each of the n subjects. The forms are
97
+ * ICC1 = (MSB − MSW)/(MSB + (k − 1)MSW) (one-way), ICC2 = (MSB − MSE)/(MSB + (k − 1)MSE + k(MSJ − MSE)/n) (two-way
98
+ * random raters, absolute agreement), ICC3 = (MSB − MSE)/(MSB + (k − 1)MSE) (two-way fixed raters, consistency), and
99
+ * their averages over k raters ICC1k, ICC2k, ICC3k. With `lmer: true` (the default, as psych) the mean squares are
100
+ * rebuilt from the REML estimates of the variance components of the two-way random model, which are not negative;
101
+ * where both ANOVA components are not negative they equal the ANOVA mean squares. psych fits that model with lme4,
102
+ * whose optimiser stops early (results about 1e-5 relative off); here the REML estimates are computed exactly, in
103
+ * closed form.
104
+ *
105
+ * ICC1, ICC3, ICC1k and ICC3k agree with {@link icc} (irr's forms); the interval of ICC2k is psych's (ICC2's bounds
106
+ * transformed by Spearman-Brown), not irr's (McGraw and Wong's average-agreement interval).
107
+ *
108
+ * Where the residual mean square is 0 (ratings that differ between raters by constants), the F statistics of ICC2 and
109
+ * ICC3 are Infinity with p-value 0, and ICC3, ICC3k and their bounds are 1.
110
+ *
111
+ * @param x An n × k matrix of ratings (array of rows), without missing values.
112
+ * @param options See {@link ICCOptions}.
113
+ * @returns See {@link ICCResult}.
114
+ * @throws TypeError if x is not a matrix of numbers; RangeError for missing or infinite ratings (psych's REML path
115
+ * accepts missing ratings; here they are an error), fewer than 2 subjects or raters, ratings that are all equal or
116
+ * identical for every subject, or a level out of range.
117
+ *
118
+ * @example
119
+ * ```ts
120
+ * const r = ICC([[9, 2, 5, 8], [6, 1, 3, 2], [8, 4, 6, 8], [7, 1, 2, 6], [10, 5, 6, 9], [6, 2, 4, 7]]);
121
+ * r.results[1]!.ICC; // 0.28976377952755905 (ICC2)
122
+ * r.results[4]!.lower; // 0.07113681530250335 (ICC2k)
123
+ * ```
124
+ *
125
+ * @category Agreement, reliability and factor analysis
126
+ */
127
+ export function ICC(x, options = {}) {
128
+ checkOptions(options, ICC_KEYS, "ICC"); // generated: option-keys.mjs
129
+ const lmer = options.lmer ?? true;
130
+ if (typeof lmer !== "boolean")
131
+ throw new TypeError("'lmer' must be true or false");
132
+ let alpha;
133
+ let confLevel;
134
+ if (options.alpha !== undefined) {
135
+ alpha = options.alpha;
136
+ if (!(typeof alpha === "number" && alpha > 0 && alpha < 1))
137
+ throw new RangeError("'alpha' must be a single number in (0, 1)");
138
+ confLevel = 1 - alpha;
139
+ }
140
+ else {
141
+ confLevel = options.confLevel ?? 0.95;
142
+ checkConfLevelOpen(confLevel);
143
+ alpha = 1 - confLevel;
144
+ }
145
+ if (!Array.isArray(x) || x.length === 0 || !x.every((r) => Array.isArray(r))) {
146
+ throw new TypeError("'x' must be a matrix (an array of rows)");
147
+ }
148
+ const k = x[0].length;
149
+ if (x.some((r) => r.length !== k))
150
+ throw new TypeError("'x' must be a matrix (rows of equal length)");
151
+ if (x.some((r) => r.some((v) => typeof v !== "number")))
152
+ throw new TypeError("'x' must contain numbers");
153
+ if (x.some((r) => r.some(Number.isNaN)))
154
+ throw new RangeError("'x' contains missing ratings (only complete data are supported)");
155
+ if (x.some((r) => r.some((v) => !Number.isFinite(v))))
156
+ throw new RangeError("'x' contains infinite ratings");
157
+ const n = x.length;
158
+ if (n < 2 || k < 2)
159
+ throw new RangeError("at least 2 subjects and 2 raters are needed");
160
+ // the ratings scaled by one power of 2 (exact), for the checks below
161
+ const { groups: rows } = scaleToUnit(x);
162
+ if (rows.every((r) => sameArray(r, rows[0]))) {
163
+ throw new RangeError(rows[0].every((v) => v === rows[0][0]) ? "all ratings are equal" : "every subject has the same ratings: the coefficients are undefined");
164
+ }
165
+ const cols = Array.from({ length: k }, (_, j) => rows.map((r) => r[j]));
166
+ // SSB and SSE do not change when a constant is added to a column, SSJ and SSE not when one is added to a row: the
167
+ // sums of squares come from the ratings minus the first row (SSB), minus the first column (SSJ) and minus both
168
+ // (SSE), so that a rater or subject offset far beyond the spread of the ratings does not swamp them. Each difference
169
+ // is exact (a double-double); they are formed from the unscaled ratings (divided by 8 where a difference could
170
+ // overflow: the double differences x_ij - x_i1 - x_1j + x_11 reach 4 max|x|) and then scaled by one power of 2 of
171
+ // their own
172
+ let big = 0;
173
+ for (const r of x)
174
+ for (const v of r)
175
+ big = Math.max(big, Math.abs(v));
176
+ const shift = big > 2 ** 1020 ? 3 : 0;
177
+ const raw = shift > 0 ? x.map((r) => r.map((v) => v / 8)) : x;
178
+ const byCol = raw.map((r) => r.map((v, j) => exactDiff(v, raw[0][j])));
179
+ const byRow = raw.map((r) => r.map((v) => exactDiff(v, r[0])));
180
+ const both = byRow.map((r) => r.map((v, j) => ddSub(v, byRow[0][j])));
181
+ // each scaled by its own power of 2, so that the squares of the small ones do not underflow beside a large offset
182
+ const expOf = (m) => {
183
+ let big = 0;
184
+ for (const r of m)
185
+ for (const v of r)
186
+ big = Math.max(big, Math.abs(v[0]));
187
+ return big === 0 ? 0 : Math.floor(Math.log2(big));
188
+ };
189
+ const unit = (m, e) => m.map((r) => r.map((v) => [ldexp(v[0], -e), ldexp(v[1], -e)]));
190
+ const [kB, kJ, kE] = [expOf(byCol), expOf(byRow), expOf(both)];
191
+ const [yB, yJ, yE] = [unit(byCol, kB), unit(byRow, kJ), unit(both, kE)];
192
+ const colsOf = (m) => Array.from({ length: k }, (_, j) => m.map((r) => r[j]));
193
+ const ssB = ssOfMeans(yB.map(meanOfDD), meanOfDD(yB.flat()), k);
194
+ // (identical columns: SSJ is exactly 0, which the double-double means need not give)
195
+ const ssJ = cols.every((c) => sameArray(c, cols[0])) ? [0, 0] : ssOfMeans(colsOf(yJ).map(meanOfDD), meanOfDD(yJ.flat()), n);
196
+ let ssE = [0, 0];
197
+ if (!isAdditive(rows)) {
198
+ // the residuals x - row mean - column mean + grand mean, in double-double (no cancellation of SST - SSB - SSJ)
199
+ const rm = yE.map(meanOfDD);
200
+ const cm = colsOf(yE).map(meanOfDD);
201
+ const grand = meanOfDD(yE.flat());
202
+ yE.forEach((r, i) => r.forEach((v, j) => {
203
+ const e = ddAdd(ddSub(ddSub(v, rm[i]), cm[j]), grand);
204
+ ssE = ddAdd(ssE, ddMul(e, e));
205
+ }));
206
+ }
207
+ // Each sum of squares stays in its own units, 2^(2kB), 2^(2kJ), 2^(2kE) (times 64 where the ratings were divided by 8): a
208
+ // quantity brings only the mean squares it uses to the larger of their scales, so that it underflows only where its
209
+ // true value does (a rater offset far beyond the spread makes SSJ huge, but MSB, MSE, ICC3 and F3 do not change)
210
+ const scaled = (ss, kx) => ({ v: ss, e: 2 * (kx + shift) });
211
+ const SB = scaled(ssB, kB);
212
+ const SJ = scaled(ssJ, kJ);
213
+ const SE = scaled(ssE, kE);
214
+ const dfB = n - 1;
215
+ const dfJ = k - 1;
216
+ const dfE = (n - 1) * (k - 1);
217
+ let MSB = sDiv(SB, dfB);
218
+ let MSJ = sDiv(SJ, dfJ);
219
+ let MSE = sDiv(SE, dfE);
220
+ let MSW = sDiv(sAdd(SJ, SE), dfJ + dfE);
221
+ const warnings = [];
222
+ if (lmer) {
223
+ // REML: the isotonic regression of (MSB, MSJ) >= MSE with weights df (see the header)
224
+ const parts = {
225
+ B: { ss: SB, df: dfB, ms: MSB, pooled: false },
226
+ J: { ss: SJ, df: dfJ, ms: MSJ, pooled: false },
227
+ };
228
+ let pooledSS = SE;
229
+ let pooledDf = dfE;
230
+ for (const t of sLessEq(MSB, MSJ) ? ["B", "J"] : ["J", "B"]) {
231
+ const part = parts[t];
232
+ if (sLess(part.ms, sDiv(pooledSS, pooledDf))) {
233
+ pooledSS = sAdd(pooledSS, part.ss);
234
+ pooledDf += part.df;
235
+ part.pooled = true;
236
+ }
237
+ }
238
+ const lambdaE = sDiv(pooledSS, pooledDf);
239
+ if (parts.B.pooled)
240
+ MSB = lambdaE;
241
+ if (parts.J.pooled)
242
+ MSJ = lambdaE;
243
+ MSE = lambdaE;
244
+ // sigma2_e + sigma2_rater = MSE + (MSJ - MSE)/n: the ANOVA MSW unless the subjects' mean square was pooled
245
+ // (pooling the raters' gives (SSJ + SSE)/(dfJ + dfE) = MSW itself)
246
+ if (parts.B.pooled) {
247
+ const [e, j] = inCommon(MSE, MSJ);
248
+ MSW = { v: [e.at + (j.at - e.at) / n, 0], e: e.E };
249
+ }
250
+ }
251
+ else if (ssE[0] === 0)
252
+ warnings.push("essentially perfect fit for ‘1’: summary may be unreliable");
253
+ // the upper alpha/2 quantile of F (rule 10: from the upper tail itself below 1e-8, as 1 - alpha/2 loses its digits)
254
+ const q = (d1, d2) => alpha / 2 < 1e-8 ? qf1(alpha / 2, d1, d2, false, false) : qf1(1 - alpha / 2, d1, d2, true, false);
255
+ const upperP = (F, d1, d2) => pf1(F, d1, d2, false, false);
256
+ // (F - 1)/(F + k - 1) and 1 - 1/F, with their limit 1 at F = Infinity
257
+ const single = (f) => (f === Infinity ? 1 : (f - 1) / (f + k - 1));
258
+ const average = (f) => 1 - 1 / f;
259
+ const dfW = n * (k - 1);
260
+ const F1 = sRatio(MSB, MSW);
261
+ const F3 = sRatio(MSB, MSE);
262
+ const [F1L, F1U] = [F1 / q(dfB, dfW), F1 * q(dfW, dfB)];
263
+ const [F3L, F3U] = [F3 / q(dfB, dfE), F3 * q(dfE, dfB)];
264
+ // ICC1 and ICC1k need MSB and MSW, ICC3 and ICC3k MSB and MSE, ICC2, ICC2k and ICC2's interval all three: each in
265
+ // the units of the largest of those it uses
266
+ const [b1, w1] = inCommon(MSB, MSW).map((t) => t.at);
267
+ const [b3, e3] = inCommon(MSB, MSE).map((t) => t.at);
268
+ const [b2, j2, e2] = inCommon(MSB, MSJ, MSE).map((t) => t.at);
269
+ const icc1 = (b1 - w1) / (b1 + (k - 1) * w1);
270
+ const icc2 = (b2 - e2) / (b2 + (k - 1) * e2 + (k * (j2 - e2)) / n);
271
+ const icc3 = (b3 - e3) / (b3 + (k - 1) * e3);
272
+ // ICC2's interval (Shrout and Fleiss 1979, eq. for case 2): Satterthwaite's v of the combination k ICC2 MSJ + (n(1 +
273
+ // (k - 1) ICC2) - k ICC2) MSE, written with MSE multiplied through (Fj = MSJ/MSE in the paper), so that MSE = 0 gives
274
+ // its limit k - 1 (and MSJ = MSE = 0, where any v gives the bounds 1, k - 1 too)
275
+ // v does not change when a and c are scaled together: both are divided by the power of 2 of the larger, so that
276
+ // their squares neither overflow nor underflow (MSJ far beyond MSB and MSE made (n - 1) a^2 + c^2 underflow to 0)
277
+ const a0 = k * icc2 * j2;
278
+ const c0 = (n * (1 + (k - 1) * icc2) - k * icc2) * e2;
279
+ const top = Math.max(Math.abs(a0), Math.abs(c0));
280
+ const ka = top > 0 && Number.isFinite(top) ? Math.floor(Math.log2(top)) : 0;
281
+ const a = ldexp(a0, -ka);
282
+ const c = ldexp(c0, -ka);
283
+ const vDen = (n - 1) * a * a + c * c;
284
+ const v = vDen === 0 ? k - 1 : ((k - 1) * (n - 1) * (a + c) ** 2) / vDen;
285
+ const G1 = q(dfB, v);
286
+ const G2 = q(v, dfB);
287
+ // the bounds with numerator and denominator divided by G1 (and by G2 where it is above 1), so that a quantile that
288
+ // overflows (a tiny v, where ICC2 < 0 makes a and c nearly cancel) gives the limit G -> Infinity, not -Inf/Inf.
289
+ // Above 1/2 a bound is formed as 1 minus its complement, (n MSE + kJE)/(kJE + n MSB/G), which keeps it <= 1
290
+ const kJE = k * j2 + (k * n - k - n) * e2;
291
+ const bound = (b, den) => (b > 0.5 ? 1 - (n * e2 + kJE) / den : b);
292
+ const l2 = bound((n * (b2 / G1 - e2)) / (kJE + (n * b2) / G1), kJE + (n * b2) / G1);
293
+ const u2 = G2 > 1
294
+ ? bound((n * (b2 - e2 / G2)) / (kJE / G2 + n * b2), kJE + n * G2 * b2)
295
+ : bound((n * (G2 * b2 - e2)) / (kJE + n * G2 * b2), kJE + n * G2 * b2);
296
+ const sb = (r) => (r * k) / (1 + r * (k - 1));
297
+ const p1 = upperP(F1, dfB, dfW);
298
+ const p3 = upperP(F3, dfB, dfE);
299
+ const row = (type, ICCv, F, df2, p, lower, upper) => ({
300
+ type,
301
+ name: NAMES[type],
302
+ ICC: ICCv,
303
+ F,
304
+ df1: dfB,
305
+ df2,
306
+ pValue: p,
307
+ lower,
308
+ upper,
309
+ });
310
+ const results = [
311
+ row("ICC1", icc1, F1, dfW, p1, single(F1L), single(F1U)),
312
+ row("ICC2", icc2, F3, dfE, p3, l2, u2),
313
+ row("ICC3", icc3, F3, dfE, p3, single(F3L), single(F3U)),
314
+ row("ICC1k", (b1 - w1) / b1, F1, dfW, p1, average(F1L), average(F1U)),
315
+ row("ICC2k", (b2 - e2) / (b2 + (j2 - e2) / n), F3, dfE, p3, sb(l2), sb(u2)),
316
+ row("ICC3k", (b3 - e3) / b3, F3, dfE, p3, average(F3L), average(F3U)),
317
+ ];
318
+ // each mean square scaled back on its own
319
+ const back = (ms) => ldexpWide(ms.v[0], ms.e);
320
+ return reported("ICC", {
321
+ results,
322
+ MSB: back(MSB),
323
+ MSJ: back(MSJ),
324
+ MSE: back(MSE),
325
+ MSW: back(MSW),
326
+ n,
327
+ k,
328
+ confLevel,
329
+ lmer,
330
+ warnings,
331
+ });
332
+ }
@@ -14,7 +14,7 @@ export interface KsTestOptions {
14
14
  /**
15
15
  * Exact p-value. Default: exact for one sample of fewer than 100 values without ties, and for two samples with
16
16
  * m n < 10000. The exact two-sided one-sample p-value for D < 1/2 raises a matrix of size 2 floor(n D) + 1 to the
17
- * n-th power; where that needs more than 2^33 multiply-adds (m 781 at n 1023, about 4 s) it is a RangeError (R
17
+ * n-th power; where that needs more than 2^33 multiply-adds (m 783 at n 1023, about 4 s) it is a RangeError (R
18
18
  * computes it however long it takes).
19
19
  */
20
20
  exact?: boolean;
@@ -0,0 +1,209 @@
1
+ import type { Sample } from "./types.js";
2
+ /**
3
+ * Regression methods of {@link mcreg}.
4
+ *
5
+ * @category Agreement, reliability and factor analysis
6
+ */
7
+ export type McregMethod = "PaBa" | "Deming" | "WDeming";
8
+ /**
9
+ * Interval methods of {@link mcreg}.
10
+ *
11
+ * @category Agreement, reliability and factor analysis
12
+ */
13
+ export type McregCiMethod = "analytical" | "jackknife" | "bootstrap" | "nestedbootstrap";
14
+ /**
15
+ * Bootstrap intervals of {@link mcreg}.
16
+ *
17
+ * @category Agreement, reliability and factor analysis
18
+ */
19
+ export type McregBootstrapCiMethod = "quantile" | "Student" | "BCa" | "tBoot";
20
+ /**
21
+ * Options for {@link mcreg}.
22
+ *
23
+ * @category Agreement, reliability and factor analysis
24
+ */
25
+ export interface McregOptions {
26
+ /**
27
+ * `"PaBa"` (Passing-Bablok, the default, as mcr), `"Deming"` or `"WDeming"` (weighted Deming, constant coefficient
28
+ * of variation). Unambiguous abbreviations are accepted.
29
+ */
30
+ methodReg?: McregMethod | (string & {});
31
+ /**
32
+ * `"analytical"` (the default for Deming and Passing-Bablok; not available for weighted Deming), `"jackknife"` (the
33
+ * default for weighted Deming), `"bootstrap"` or `"nestedbootstrap"`. mcr's default is `"bootstrap"`.
34
+ */
35
+ methodCi?: McregCiMethod | (string & {});
36
+ /**
37
+ * The bootstrap interval: `"quantile"` (the default), `"Student"`, `"BCa"` or `"tBoot"` (bootstrap-t: with Deming
38
+ * or with nested resamples).
39
+ */
40
+ methodBootstrapCi?: McregBootstrapCiMethod | (string & {});
41
+ /**
42
+ * The ratio of the error variances σ²(x)/σ²(y), x the reference method (mcr's `error.ratio`; Deming and weighted
43
+ * Deming), positive and finite. Default `1`.
44
+ */
45
+ errorRatio?: number;
46
+ /** Level of the intervals, in (0, 1) (mcr's `1 - alpha`). Default `0.95`. */
47
+ confLevel?: number;
48
+ /** Passing-Bablok: the mean of two middle slopes as `"radian"` (tan of the mean angle, the default) or `"tangent"`. */
49
+ slopeMeasure?: "radian" | "tangent" | (string & {});
50
+ /** Number of bootstrap resamples, a positive integer. Default `999`. */
51
+ nsamples?: number;
52
+ /** Number of inner resamples of each resample for `"nestedbootstrap"`, a positive integer. Default `25`. */
53
+ nnested?: number;
54
+ /**
55
+ * Seed of the resamples: the stream of R's `set.seed(rngSeed, kind = "Mersenne-Twister")`, as mcr's `rng.seed`; the
56
+ * state of the generator is restored afterwards if it had one (in a session that never drew a random number, the
57
+ * stream of the seed continues, as in R). Without it the resamples are drawn from the current stream.
58
+ */
59
+ rngSeed?: number;
60
+ /** Weighted Deming: the largest number of iterations, a positive integer. Default `30`. */
61
+ iterMax?: number;
62
+ /** Weighted Deming: the iteration stops when both coefficients change by less than this (absolute). Default `1e-6`. */
63
+ threshold?: number;
64
+ /** Drop the pairs with `NaN` (otherwise they are an error). Default `false`. */
65
+ naRm?: boolean;
66
+ }
67
+ /**
68
+ * A coefficient of {@link McregResult}.
69
+ *
70
+ * @category Agreement, reliability and factor analysis
71
+ */
72
+ export interface McregCoefficient {
73
+ /** The estimate from all the data. */
74
+ estimate: number;
75
+ /** Its standard error (`NaN` where the method has none: Passing-Bablok analytical, bootstrap quantile and BCa). */
76
+ se: number;
77
+ /** The interval at `confLevel`. */
78
+ confInt: [number, number];
79
+ }
80
+ /**
81
+ * Result of {@link mcreg}.
82
+ *
83
+ * @category Agreement, reliability and factor analysis
84
+ */
85
+ export interface McregResult {
86
+ /** The regression method, in full. */
87
+ methodReg: McregMethod;
88
+ /** The interval method, in full. */
89
+ methodCi: McregCiMethod;
90
+ /** The bootstrap interval, in full (bootstrap methods only). */
91
+ methodBootstrapCi?: McregBootstrapCiMethod;
92
+ /** The level of the intervals. */
93
+ confLevel: number;
94
+ /** The ratio of the error variances used (1 for Passing-Bablok). */
95
+ errorRatio: number;
96
+ /** Number of pairs used. */
97
+ n: number;
98
+ /** The intercept (mcr's row `Intercept` of `@para`). */
99
+ intercept: McregCoefficient;
100
+ /** The slope (mcr's row `Slope` of `@para`). */
101
+ slope: McregCoefficient;
102
+ /** The mean of x (Deming), the weighted mean of the last iteration (weighted Deming), `NaN` (Passing-Bablok). */
103
+ xmean: number;
104
+ /** Weighted Deming: the weights of the last iteration (mcr's `@weight`); Infinity where beyond the double range. */
105
+ weights?: number[];
106
+ /** Jackknife: the leave-one-out coefficients (mcr's `@B0jack`, `@B1jack`; also for the BCa interval). */
107
+ jackknife?: {
108
+ /** The intercepts with each point left out (mcr's `@B0jack`). */
109
+ intercept: number[];
110
+ /** The slopes with each point left out (mcr's `@B1jack`). */
111
+ slope: number[];
112
+ };
113
+ /**
114
+ * Bootstrap: the coefficients of the resamples kept, in the order drawn (mcr's `@B0`, `@B1`), their standard errors
115
+ * (`@sigmaB0`, `@sigmaB1`: the standard deviation of the nested estimates, the analytical standard error for Deming,
116
+ * the jackknife one for weighted Deming with BCa, else `NaN`), the global standard errors (`@glob.sigma`) and the
117
+ * number of resamples kept.
118
+ */
119
+ bootstrap?: {
120
+ /** The intercepts of the resamples kept, in the order drawn (mcr's `@B0`). */
121
+ intercept: number[];
122
+ /** The slopes of the resamples kept (mcr's `@B1`). */
123
+ slope: number[];
124
+ /** The standard errors of the intercepts (mcr's `@sigmaB0`). */
125
+ sigmaIntercept: number[];
126
+ /** The standard errors of the slopes (mcr's `@sigmaB1`). */
127
+ sigmaSlope: number[];
128
+ /** The global standard errors of the intercept and the slope (mcr's `@glob.sigma`). */
129
+ globalSigma: [number, number];
130
+ /** The number of resamples kept. */
131
+ nsamples: number;
132
+ };
133
+ /**
134
+ * Passing-Bablok: the linearity statistic (mcr's `calcCUSUM`): the numbers of points above and below the line and
135
+ * the largest absolute cumulative sum of their scores ordered along the line.
136
+ */
137
+ cusum?: {
138
+ /** The number of points above the line. */
139
+ nPos: number;
140
+ /** The number of points below the line. */
141
+ nNeg: number;
142
+ /** The largest absolute cumulative sum of the scores ordered along the line. */
143
+ maxCusum: number;
144
+ };
145
+ /** Warnings (the weighted Deming iteration not converging, degenerate resamples, an undefined interval). */
146
+ warnings: string[];
147
+ }
148
+ /**
149
+ * Method comparison regression of y (test method) on x (reference method): Deming, weighted Deming or Passing-Bablok
150
+ * regression with analytical, jackknife or bootstrap intervals. Equivalent to `mcr::mcreg()` in R.
151
+ *
152
+ * - **Deming** (`"Deming"`): the slope minimises the squared distances in the metric of the error variances, λ =
153
+ * `errorRatio` = σ²(x)/σ²(y) (mcr's convention; λ → 0 gives the least-squares slope of y on x). The analytical
154
+ * standard errors are Strike's (1991), with t intervals on n - 2 degrees of freedom.
155
+ * - **Weighted Deming** (`"WDeming"`): Linnet's (1990) iteration for errors proportional to the level (constant
156
+ * coefficient of variation), stopped as mcr when both coefficients change by less than `threshold` (absolute), with
157
+ * a warning when `iterMax` iterations are reached. No analytical interval (jackknife by default). Values must be
158
+ * positive. Since the threshold is absolute, data of very large magnitude (around 1e150) may not converge and
159
+ * data of very small magnitude (around 1e-150) stop after the first iteration; choose `threshold` in the units of
160
+ * the data.
161
+ * - **Passing-Bablok** (`"PaBa"`): the shifted median of the n(n - 1)/2 pairwise slopes and the rank interval of
162
+ * Passing and Bablok (1983); the intercept is the median of y - b x and its limits those of the slope's limits.
163
+ * Differences below a relative 1e-12 count as ties (mcr's rule; a pair tied in x only is vertical), so data with a
164
+ * large offset (1e12 + O(1)) have most differences set to 0; the mean of two middle slopes is tan of the mean angle
165
+ * (`slopeMeasure: "radian"`, mcr's default; it changes when y is rescaled, as angles do not scale) or the mean slope
166
+ * (`"tangent"`). Where the interval is not defined (too few points, always for n <= 4) its limits and the
167
+ * intercept's are -Infinity and Infinity, with a warning. Values must not be negative. The result has the CUSUM
168
+ * statistic of linearity (`cusum`; no test decision).
169
+ * - **jackknife**: the leave-one-out estimates, the standard error sd(pseudo-values)/sqrt(n) and the interval estimate
170
+ * ± t se on n - 2 degrees of freedom (Linnet 1993); the estimates are those of all the data.
171
+ * - **bootstrap**: `nsamples` resamples of the pairs with replacement; `"quantile"` the percentile interval,
172
+ * `"Student"` estimate ± t sd(B), `"BCa"` the bias-corrected and accelerated interval (jackknife acceleration),
173
+ * `"tBoot"` the bootstrap-t interval with the analytical standard errors (Deming) or, with `"nestedbootstrap"`, the
174
+ * standard deviation of `nnested` inner resamples of each resample. Resamples with constant x or y are dropped
175
+ * with mcr's warning (an error when more than 5% are). The resamples are drawn as R's `sample(1:n, n, replace =
176
+ * TRUE)` from the current random stream, or from `set.seed(rngSeed)` as mcr's `rng.seed` (the generator's state is
177
+ * then restored if it had one), so the values are mcr's for the same seed. With very few points (n = 5) the
178
+ * bootstrap-t limits can be infinite or huge, because resamples of 2 or 3 distinct points have standard errors 0.
179
+ *
180
+ * Unlike mcr, the default interval is `"analytical"` (`"jackknife"` for weighted Deming) rather than a random
181
+ * bootstrap; `confLevel` replaces mcr's `alpha` (= 1 - confLevel); 2 or fewer points, constant x or y, infinite
182
+ * values and data whose Deming covariance is 0 are errors. Passing-Bablok's odd-position slopes are dy/dx (mcr: tan of
183
+ * its angle, a few ulps off). PaBaLarge, LinReg, WLinReg, PBequi and TS are not offered.
184
+ *
185
+ * @param x Measurements by the reference method.
186
+ * @param y Measurements by the test method, paired with `x`.
187
+ * @param options See {@link McregOptions}.
188
+ * @returns See {@link McregResult}.
189
+ * @throws TypeError if `x` and `y` differ in length; RangeError for missing values without `naRm`, infinite values,
190
+ * fewer than 3 pairs, constant x or y, negative values (Passing-Bablok), values that are not positive (weighted
191
+ * Deming), more than 5793 points (Passing-Bablok), an analytical interval for weighted Deming, a bootstrap-t
192
+ * interval without nested resamples for Passing-Bablok or weighted Deming, too many degenerate resamples, a zero
193
+ * covariance (Deming), or an invalid option.
194
+ *
195
+ * @example
196
+ * ```ts
197
+ * const x = [1, 2, 3, 4, 5, 6, 7];
198
+ * const y = [1.2, 1.9, 3.2, 3.8, 5.1, 6.4, 6.6];
199
+ * const d = mcreg(x, y, { methodReg: "Deming" });
200
+ * d.slope.estimate; // 0.97547950725034482
201
+ * d.slope.confInt; // [0.83267195599246846, 1.1182870585082212]
202
+ * const pb = mcreg(x, y); // Passing-Bablok
203
+ * pb.slope.estimate; // 0.95
204
+ * pb.intercept.confInt; // [-0.8524794459077718, 0.80365513709218339]
205
+ * ```
206
+ *
207
+ * @category Agreement, reliability and factor analysis
208
+ */
209
+ export declare function mcreg(x: Sample, y: Sample, options?: McregOptions): McregResult;