@numero-uno-jpn/rstats 1.1.0 → 1.3.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 (97) hide show
  1. package/CHANGELOG.md +142 -0
  2. package/README.ja.md +33 -15
  3. package/README.md +32 -14
  4. package/dist/chunks/{chunk-4KCSBTR5.js → chunk-2VZW4XPK.js} +2 -2
  5. package/dist/chunks/chunk-4OOTEXZU.js +2 -0
  6. package/dist/chunks/{chunk-Z2HGLFZN.js → chunk-6TZVS6WC.js} +2 -2
  7. package/dist/chunks/{chunk-U7BRXOUS.js → chunk-6X2ZMPF5.js} +2 -2
  8. package/dist/chunks/{chunk-GJEKNJP7.js → chunk-AJZV2SVY.js} +2 -2
  9. package/dist/chunks/{chunk-GRUQRNX7.js → chunk-BNTBZ5W3.js} +3 -3
  10. package/dist/chunks/{chunk-DR4GQ7PW.js → chunk-EBRTF7RM.js} +1 -1
  11. package/dist/chunks/{chunk-OG7UORIX.js → chunk-FFNHG5SB.js} +1 -1
  12. package/dist/chunks/{chunk-N5BDSMXS.js → chunk-GUM57VVM.js} +1 -1
  13. package/dist/chunks/{chunk-GGJA3JRO.js → chunk-HBRSUHSU.js} +2 -2
  14. package/dist/chunks/{chunk-HRA7PCQT.js → chunk-I5NWGQOQ.js} +2 -2
  15. package/dist/chunks/chunk-IJV43Y7Q.js +2 -0
  16. package/dist/chunks/{chunk-YN5MLKDL.js → chunk-IOGQEMDE.js} +2 -2
  17. package/dist/chunks/{chunk-GYGQUYEP.js → chunk-JJRZ2TTF.js} +2 -2
  18. package/dist/chunks/{chunk-X4J6UJHN.js → chunk-LA4H6ZSC.js} +2 -2
  19. package/dist/chunks/{chunk-DTJG2IL2.js → chunk-LMNU4NHZ.js} +2 -2
  20. package/dist/chunks/{chunk-4VRMAYPY.js → chunk-LNUNKFIH.js} +3 -3
  21. package/dist/chunks/chunk-MJXETGT2.js +2 -0
  22. package/dist/chunks/chunk-P7ZHH2SF.js +2 -0
  23. package/dist/chunks/{chunk-HUWOSLKE.js → chunk-PDHBRDTF.js} +2 -2
  24. package/dist/chunks/{chunk-7KJ24LYK.js → chunk-RCGW2DCK.js} +2 -2
  25. package/dist/chunks/{chunk-QUTJEYDX.js → chunk-TZTVDVP4.js} +2 -2
  26. package/dist/chunks/{chunk-HZLSNJQM.js → chunk-UJYRU37Z.js} +2 -2
  27. package/dist/chunks/{chunk-EJYCDE4Z.js → chunk-UMDXXT3M.js} +1 -1
  28. package/dist/chunks/{chunk-7IJCUSA5.js → chunk-UOAFEB64.js} +2 -2
  29. package/dist/chunks/{chunk-JNWWLNE3.js → chunk-Z74ZOTUN.js} +2 -2
  30. package/dist/descriptive.js +2 -2
  31. package/dist/distributions.js +2 -2
  32. package/dist/entries/tests.d.ts +14 -0
  33. package/dist/entries/tests.js +14 -0
  34. package/dist/htest/agreement.d.ts +2 -2
  35. package/dist/htest/binomCI.d.ts +116 -0
  36. package/dist/htest/binomCI.js +252 -0
  37. package/dist/htest/blandAltman.d.ts +100 -0
  38. package/dist/htest/blandAltman.js +159 -0
  39. package/dist/htest/boschlooTest.d.ts +65 -0
  40. package/dist/htest/boschlooTest.js +394 -0
  41. package/dist/htest/chisqTest.d.ts +19 -0
  42. package/dist/htest/chisqTest.js +30 -2
  43. package/dist/htest/core/twoProportions.d.ts +48 -0
  44. package/dist/htest/core/twoProportions.js +476 -0
  45. package/dist/htest/diagnosticTests.d.ts +91 -0
  46. package/dist/htest/diagnosticTests.js +116 -0
  47. package/dist/htest/equivalence.d.ts +172 -0
  48. package/dist/htest/equivalence.js +189 -0
  49. package/dist/htest/fisherTest.d.ts +49 -0
  50. package/dist/htest/fisherTest.js +136 -13
  51. package/dist/htest/iccPsych.d.ts +106 -0
  52. package/dist/htest/iccPsych.js +332 -0
  53. package/dist/htest/ksTest.d.ts +1 -1
  54. package/dist/htest/mcreg.d.ts +209 -0
  55. package/dist/htest/mcreg.js +735 -0
  56. package/dist/htest/roc.d.ts +287 -0
  57. package/dist/htest/roc.js +635 -0
  58. package/dist/htest/rocTest.d.ts +139 -0
  59. package/dist/htest/rocTest.js +444 -0
  60. package/dist/htest/tTOST.d.ts +202 -0
  61. package/dist/htest/tTOST.js +558 -0
  62. package/dist/htest/tableTests.d.ts +216 -0
  63. package/dist/htest/tableTests.js +650 -0
  64. package/dist/htest/trendTests.d.ts +1 -1
  65. package/dist/htest/trendTests.js +1 -1
  66. package/dist/htest/twoByTwo.d.ts +203 -0
  67. package/dist/htest/twoByTwo.js +385 -0
  68. package/dist/internal/summary.js +5 -0
  69. package/dist/linalg/qr.d.ts +3 -0
  70. package/dist/linalg/qr.js +3 -0
  71. package/dist/linalg.js +2 -2
  72. package/dist/mixed.js +2 -2
  73. package/dist/models/coeftest.d.ts +139 -0
  74. package/dist/models/coeftest.js +237 -0
  75. package/dist/models/coxph.d.ts +60 -9
  76. package/dist/models/coxph.js +367 -38
  77. package/dist/models/glm.d.ts +11 -1
  78. package/dist/models/glm.js +19 -2
  79. package/dist/models/inputRows.d.ts +10 -0
  80. package/dist/models/inputRows.js +23 -0
  81. package/dist/models/lm.d.ts +8 -0
  82. package/dist/models/lm.js +14 -2
  83. package/dist/models/sandwich.d.ts +177 -0
  84. package/dist/models/sandwich.js +923 -0
  85. package/dist/numerics.js +2 -2
  86. package/dist/random/rng.d.ts +8 -1
  87. package/dist/random/rng.js +14 -1
  88. package/dist/rstats.js +16 -16
  89. package/dist/special/igam.js +140 -23
  90. package/dist/special/loader.js +8 -0
  91. package/dist/special.js +2 -2
  92. package/dist/tests.js +13 -13
  93. package/llms.txt +25 -0
  94. package/package.json +1 -1
  95. package/dist/chunks/chunk-NDTJ23A6.js +0 -2
  96. package/dist/chunks/chunk-UMLMY4XS.js +0 -2
  97. package/dist/chunks/chunk-Y4YWLSWU.js +0 -2
@@ -0,0 +1,558 @@
1
+ // Equivalence and minimal-effect t tests with standardised effect sizes (TOSTER's t_TOST and tsum_TOST), from data or
2
+ // from summary statistics.
3
+ //
4
+ // Written for rStats.js from oracle/methodcomparison-behaviour.md, section 4 (no R or package code), and the papers:
5
+ // - Schuirmann DJ (1987) J Pharmacokin Biopharm 15:657-680 (two one-sided tests); Lakens D (2017) Soc Psychol
6
+ // Personal Sci 8:355-362 (TOST and minimal-effect tests, bounds in raw or standardised units).
7
+ // - Hedges LV (1981) J Educ Stat 6:107-128: the bias correction J(df) = Γ(df/2)/(sqrt(df/2) Γ((df − 1)/2)).
8
+ // - Steiger JH, Fouladi RT (1997), in Harlow, Mulaik and Steiger (eds), What if there were no significance tests?:
9
+ // the interval of the noncentrality of t by inverting the noncentral t distribution ("nct"), here as true roots.
10
+ // - Bonett DG (2008) Psychol Methods 13:99-109: the standard error of the standardised difference with the average
11
+ // variance (d_av).
12
+ // - Goulet-Pelletier JC, Cousineau D (2018) Quant Methods Psychol 14:242-265: the "goulet" interval (quantiles of the
13
+ // noncentral t at the observed noncentrality) and its standard error.
14
+ import { qnorm } from "../distributions/normal.js";
15
+ import { pt, pt1, qt, qt1 } from "../distributions/t.js";
16
+ import { completePairs, dropNaN, ldexp, ldexpWide, mean, scaleToUnit, variance } from "../internal/summary.js";
17
+ import { reported, unreported } from "../internal/warnings.js";
18
+ import { unirootCore } from "../numerics/integrate.js";
19
+ import { hedgesJ } from "./effectSize.js";
20
+ import { matchChoice } from "./power.js";
21
+ import { tTest } from "./tTest.js";
22
+ // Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
23
+ import { checkOptions } from "../internal/checkOptions.js";
24
+ const T_TOST_KEYS = /* @__PURE__ */ new Set([
25
+ "eqb", "lowEqbound", "highEqbound", "hypothesis", "paired", "varEqual", "alpha", "mu", "eqboundType",
26
+ "biasCorrection", "rmCorrection", "glass", "smdCi",
27
+ ]);
28
+ const TSUM_TOST_KEYS_0 = ["m1", "sd1", "n1", "m2", "sd2", "n2", "r12"];
29
+ const TSUM_TOST_KEYS_1 = /* @__PURE__ */ new Set([
30
+ "eqb", "lowEqbound", "highEqbound", "hypothesis", "paired", "varEqual", "alpha", "mu", "eqboundType",
31
+ "biasCorrection", "rmCorrection", "glass", "smdCi",
32
+ ]);
33
+ const ZERO_NOTE = "Equivalence interval does not include zero.";
34
+ const SMD_NOTE = "Warning: setting bound type to SMD produces biased results!";
35
+ const MET_NOTE = "MET test may have higher error rates than a nil two-tailed test. Consider wider equivalence bounds.";
36
+ /** The noncentrality with P(T(df, ncp) > t) = p (upperTail) or P(T(df, ncp) <= t) = p, as a root to the last bit */
37
+ function ncpRoot(t, df, p, upperTail) {
38
+ // an infinite t (a standardised difference beyond the doubles, e.g. a mean of 1e300 over a SD of 1e-300) has both
39
+ // roots at that infinity: the limits are infinite as the estimate is
40
+ if (t === Infinity || t === -Infinity)
41
+ return t;
42
+ // (where t ± 1 both round to t, a step of 1 to 2 ulp of t, as cohensD)
43
+ const h = t - 1 < t + 1 ? 1 : Math.abs(t) * Number.EPSILON;
44
+ // P(T > t) increases with ncp, P(T <= t) decreases
45
+ return unirootCore((ncp) => pt(t, df, { ncp, lowerTail: !upperTail }) - p, t - h, t + h, {
46
+ tol: 0,
47
+ maxiter: 5000,
48
+ extendInt: upperTail ? "upX" : "downX",
49
+ }).root;
50
+ }
51
+ /** The standardised difference of section 4.3 of the behaviour file, from |delta|, with the sign restored at the end */
52
+ function standardised(m, o) {
53
+ const { alpha, smdCi } = o;
54
+ const ad = Math.abs(m.delta);
55
+ const g2 = (J, g, df) => (1 - (df - 2) / (df * J * J)) * g * g;
56
+ let label;
57
+ let denom;
58
+ let df; // the df of J (and of the t and z intervals)
59
+ let J;
60
+ let g;
61
+ let seNct; // the standard error of the nct, t and z cases
62
+ let tStat; // nct: |delta| over the standard error of the difference
63
+ let dfNct;
64
+ let hn; // nct: the limits are the noncentralities times sqrt(hn) J
65
+ let c; // goulet: g/lambda
66
+ let dfGoulet;
67
+ let seGoulet;
68
+ const bc = o.biasCorrection;
69
+ if (m.design === "two") {
70
+ const { n1, n2, s1, s2 } = m;
71
+ const v1 = s1 * s1;
72
+ const v2 = s2 * s2;
73
+ const ntilde = (2 * n1 * n2) / (n1 + n2);
74
+ if (o.glass !== undefined) {
75
+ const first = o.glass === "glass1";
76
+ const [sG, nG, sO, nO] = first ? [s1, n1, s2, n2] : [s2, n2, s1, n1];
77
+ denom = sG;
78
+ df = nG - 1;
79
+ label = bc ? "Glass's delta(g)" : "Glass's delta(d)";
80
+ J = bc ? hedgesJ(df) : 1;
81
+ g = (J * ad) / denom;
82
+ // (TOSTER's 1/n2 + s²/(n1 s²): 1/n1 + 1/n2 for either sample)
83
+ hn = 1 / n2 + 1 / n1;
84
+ const r = sO / sG;
85
+ seNct = Math.sqrt((r * r) / (nO - 1) + 1 / (nG - 1) + (g * g) / (2 * (nG - 1)));
86
+ tStat = ad / (sG * Math.sqrt(1 / nG + (r * r) / nO));
87
+ // as TOSTER: the noncentral t of Glass's delta on n1 + n2 - 2 df
88
+ dfNct = n1 + n2 - 2;
89
+ c = Math.sqrt(2 / ntilde);
90
+ }
91
+ else if (o.varEqual) {
92
+ denom = Math.sqrt(((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2));
93
+ df = n1 + n2 - 2;
94
+ label = bc ? "Hedges's g" : "Cohen's d";
95
+ J = bc ? hedgesJ(df) : 1;
96
+ g = (J * ad) / denom;
97
+ hn = 1 / n1 + 1 / n2;
98
+ seNct = Math.sqrt(1 / n1 + 1 / n2 + g2(J, g, df));
99
+ tStat = ad / (denom * Math.sqrt(hn));
100
+ dfNct = df;
101
+ // as TOSTER: lambda = g sqrt(n1 n2 (s1² + s2²)/(2(n2 s1² + n1 s2²))) with the pooled SD
102
+ c = Math.sqrt((2 * (n2 * v1 + n1 * v2)) / (n1 * n2 * (v1 + v2)));
103
+ }
104
+ else {
105
+ denom = Math.sqrt((v1 + v2) / 2);
106
+ // (the df of the average variance: (n1 - 1)(n2 - 1)(s1² + s2²)² / ((n2 - 1)s1⁴ + (n1 - 1)s2⁴))
107
+ df = ((n1 - 1) * (n2 - 1) * (v1 + v2) ** 2) / ((n2 - 1) * v1 * v1 + (n1 - 1) * v2 * v2);
108
+ label = bc ? "Hedges's g(av)" : "Cohen's d(av)";
109
+ J = bc ? hedgesJ(df) : 1;
110
+ g = (J * ad) / denom;
111
+ hn = (2 * (n2 * v1 + n1 * v2)) / (n1 * n2 * (v1 + v2));
112
+ const d4 = denom ** 4;
113
+ seNct = Math.sqrt((g * g * ((v1 * v1) / (n1 - 1) + (v2 * v2) / (n2 - 1))) / (8 * d4) + (v1 / (n1 - 1) + v2 / (n2 - 1)) / (denom * denom));
114
+ tStat = ad / Math.sqrt(v1 / n1 + v2 / n2);
115
+ dfNct = df;
116
+ c = Math.sqrt(2 / ntilde);
117
+ }
118
+ dfGoulet = df;
119
+ seGoulet = (gg, JJ) => Math.sqrt((dfGoulet / (dfGoulet - 2)) * (2 / ntilde) * (1 + (gg * gg * ntilde) / 2) - (gg * gg) / (JJ * JJ));
120
+ }
121
+ else if (m.design === "paired") {
122
+ const { n, s1, s2, sdif, oneMinusR } = m;
123
+ const tag = o.glass !== undefined ? "" : o.rmCorrection ? "(rm)" : "(z)";
124
+ if (o.glass !== undefined)
125
+ denom = o.glass === "glass1" ? s1 : s2;
126
+ else
127
+ denom = o.rmCorrection ? sdif / Math.sqrt(2 * oneMinusR) : sdif;
128
+ label = o.glass !== undefined ? (bc ? "Glass's delta(g)" : "Glass's delta(d)") : bc ? `Hedges's g${tag}` : `Cohen's d${tag}`;
129
+ df = n - 1;
130
+ dfGoulet = 2 * n - 2;
131
+ J = bc ? hedgesJ(smdCi === "goulet" ? dfGoulet : df) : 1;
132
+ g = (J * ad) / denom;
133
+ hn = 1 / n;
134
+ tStat = (ad * Math.sqrt(n)) / denom;
135
+ dfNct = df;
136
+ c = Math.sqrt((2 * oneMinusR) / n);
137
+ seGoulet = (gg, JJ) => {
138
+ const dfG = smdCi === "goulet" ? dfGoulet : df;
139
+ const se = Math.sqrt((dfG / (dfG - 2)) * ((2 * oneMinusR) / n) * (1 + (gg * gg * n) / (2 * oneMinusR)) - (gg * gg) / (JJ * JJ));
140
+ return o.rmCorrection ? se : se * Math.sqrt(2 * oneMinusR);
141
+ };
142
+ if (o.glass !== undefined) {
143
+ const r = sdif / denom;
144
+ seNct = Math.sqrt((r * r) / (n - 1) + (g * g) / (2 * (n - 1)));
145
+ }
146
+ else if (!o.rmCorrection && smdCi === "nct")
147
+ seNct = Math.sqrt(1 / n + g2(J, g, df));
148
+ else
149
+ seNct = seGoulet(g, J);
150
+ }
151
+ else {
152
+ const { n, s } = m;
153
+ denom = s;
154
+ df = n - 1;
155
+ dfGoulet = df;
156
+ label = bc ? "Hedges's g" : "Cohen's d";
157
+ J = bc ? hedgesJ(df) : 1;
158
+ g = (J * ad) / denom;
159
+ hn = 1 / n;
160
+ seNct = Math.sqrt(1 / n + (g * g) / (2 * n));
161
+ tStat = (ad * Math.sqrt(n)) / s;
162
+ dfNct = df;
163
+ c = 1 / Math.sqrt(n);
164
+ seGoulet = (gg, JJ) => Math.sqrt((df / (df - 2)) * (1 / n) * (1 + gg * gg * n) - (gg * gg) / (JJ * JJ));
165
+ }
166
+ let lo;
167
+ let hi;
168
+ let se;
169
+ let dfOut = df;
170
+ if (smdCi === "nct") {
171
+ se = seNct;
172
+ dfOut = dfNct;
173
+ const L = ncpRoot(tStat, dfNct, alpha, true);
174
+ const U = ncpRoot(tStat, dfNct, alpha, false);
175
+ lo = L * Math.sqrt(hn) * J;
176
+ hi = U * Math.sqrt(hn) * J;
177
+ }
178
+ else if (smdCi === "goulet") {
179
+ se = seGoulet(g, J);
180
+ dfOut = dfGoulet;
181
+ // the quantiles of the noncentral t at lambda = g/c, times c (= g/lambda; continuous at g = 0)
182
+ const lambda = g / c;
183
+ lo = qt(alpha, dfGoulet, { ncp: lambda }) * c;
184
+ hi = qt(alpha, dfGoulet, { ncp: lambda, lowerTail: false }) * c;
185
+ }
186
+ else {
187
+ se = seNct;
188
+ // a 1 - 2 alpha interval in every design (TOSTER's one-sample t and z limits are at 1 - alpha; decision 20)
189
+ const q = smdCi === "t" ? qt1(alpha, df, false, false) : qnorm(alpha, { lowerTail: false });
190
+ lo = g - q * se;
191
+ hi = g + q * se;
192
+ }
193
+ const neg = m.delta < 0;
194
+ return { label, denom, estimate: neg ? -g : g, se, confInt: neg ? [-hi, -lo] : [lo, hi], df: dfOut, J };
195
+ }
196
+ /** A sample of tTOST: an array (or typed array) of numbers, NaN allowed (dropped), not infinite */
197
+ function checkSample(v, name) {
198
+ if (!(Array.isArray(v) || ArrayBuffer.isView(v)))
199
+ throw new TypeError(`'${name}' must be an array of numbers`);
200
+ const a = v;
201
+ for (let i = 0; i < a.length; i++) {
202
+ const u = a[i];
203
+ if (typeof u !== "number")
204
+ throw new TypeError(`'${name}' must be numeric`);
205
+ if (u === Infinity || u === -Infinity)
206
+ throw new RangeError(`'${name}' must not contain infinite values`);
207
+ }
208
+ }
209
+ /** The bounds [low, high] from eqb or lowEqbound/highEqbound */
210
+ function boundsOf(options) {
211
+ const { eqb } = options;
212
+ let b;
213
+ if (eqb !== undefined) {
214
+ const v = typeof eqb === "number" ? [eqb] : Array.from(eqb);
215
+ if (!v.every((e) => typeof e === "number"))
216
+ throw new TypeError("'eqb' must be a number or an array of 1 or 2 numbers");
217
+ if (v.length === 1)
218
+ b = [-Math.abs(v[0]), Math.abs(v[0])];
219
+ else if (v.length === 2)
220
+ b = [Math.min(v[0], v[1]), Math.max(v[0], v[1])];
221
+ else
222
+ throw new RangeError("'eqb' must be a number or an array of 1 or 2 numbers");
223
+ }
224
+ else {
225
+ if (options.lowEqbound === undefined || options.highEqbound === undefined) {
226
+ throw new TypeError("the equivalence bounds are required: 'eqb', or 'lowEqbound' and 'highEqbound'");
227
+ }
228
+ b = [options.lowEqbound, options.highEqbound];
229
+ }
230
+ if (!b.every((v) => typeof v === "number" && Number.isFinite(v)))
231
+ throw new RangeError("the equivalence bounds must be finite numbers");
232
+ if (b[0] > b[1])
233
+ throw new RangeError("'lowEqbound' must not be greater than 'highEqbound'");
234
+ return b;
235
+ }
236
+ /** The options shared by tTOST and tsumTOST, checked in TOSTER's order */
237
+ function settingsOf(options) {
238
+ const hypothesis = matchChoice(options.hypothesis, ["EQU", "MET"]);
239
+ const smdBounds = matchChoice(options.eqboundType, ["raw", "SMD"]) === "SMD";
240
+ const smdCi = matchChoice(options.smdCi, ["nct", "goulet", "t", "z"]);
241
+ const glass = options.glass === undefined ? undefined : matchChoice(options.glass, ["glass1", "glass2"]);
242
+ const alpha = options.alpha ?? 0.05;
243
+ if (!(typeof alpha === "number" && alpha > 0 && alpha < 0.5))
244
+ throw new RangeError("'alpha' must be a single number in (0, 0.5)");
245
+ const mu = options.mu ?? 0;
246
+ if (!(typeof mu === "number" && Number.isFinite(mu)))
247
+ throw new RangeError("'mu' must be a finite number");
248
+ const flag = (v, name, def) => {
249
+ if (v !== undefined && typeof v !== "boolean")
250
+ throw new TypeError(`'${name}' must be true or false`);
251
+ return v ?? def;
252
+ };
253
+ return {
254
+ hypothesis,
255
+ smdBounds,
256
+ smdCi,
257
+ glass,
258
+ alpha,
259
+ mu,
260
+ paired: flag(options.paired, "paired", false),
261
+ varEqual: flag(options.varEqual, "varEqual", false),
262
+ biasCorrection: flag(options.biasCorrection, "biasCorrection", true),
263
+ rmCorrection: flag(options.rmCorrection, "rmCorrection", false),
264
+ };
265
+ }
266
+ /**
267
+ * The tests and effect sizes from the effect (the difference minus mu) and its standard error, in the units 2^kE and
268
+ * 2^kSE (so that neither the t statistics nor the interval lose the scaling of the data), and the moments of the
269
+ * standardised difference (in the units 2^kS)
270
+ */
271
+ function tostCore(name, effect, kE, se, kSE, df, method, m, kS, s, given, warnings) {
272
+ const { alpha, hypothesis } = s;
273
+ const smd = standardised(m, s);
274
+ const dDenom = ldexp(smd.denom, kS);
275
+ const raw = s.smdBounds ? [given[0] * dDenom, given[1] * dDenom] : given;
276
+ // each bound as a value of moderate size times 2^kb (the SMD bounds times the denominator, in the SDs' units kS)
277
+ const boundOf = (g) => {
278
+ if (g === 0)
279
+ return [0, kE];
280
+ const tg = Math.floor(Math.log2(Math.abs(g)));
281
+ const sg = ldexpWide(g, -tg);
282
+ return s.smdBounds ? [sg * smd.denom, tg + kS] : [sg, tg];
283
+ };
284
+ const smdB = s.smdBounds ? given : [given[0] / dDenom, given[1] / dDenom];
285
+ if (s.smdBounds)
286
+ warnings.push(SMD_NOTE);
287
+ if (!(raw[0] <= 0 && raw[1] >= 0))
288
+ warnings.push(ZERO_NOTE);
289
+ // the effect is the difference minus mu throughout: the bound tests compare it with [low, high] (TOSTER compares the
290
+ // difference itself), and the raw estimate, its interval and the SMD are those of it
291
+ const tOf = (v) => ldexp(v / se, kE - kSE);
292
+ // effect - bound in the larger of their units, so that neither term leaves the double range where t does not (in
293
+ // tsumTOST the means' units kE and the SDs' kS are independent: a bound converted to the units of tiny means
294
+ // overflowed, t was Infinity)
295
+ const tMinus = (g) => {
296
+ const [b, kb] = boundOf(g);
297
+ const kc = Math.max(kE, kb);
298
+ return ldexpWide((ldexpWide(effect, kE - kc) - ldexpWide(b, kb - kc)) / se, kc - kSE);
299
+ };
300
+ const t0 = tOf(effect);
301
+ const tL = tMinus(given[0]);
302
+ const tU = tMinus(given[1]);
303
+ const seOut = ldexp(se, kSE);
304
+ const equ = hypothesis === "EQU";
305
+ const tTestRow = { t: t0, se: seOut, df, pValue: 2 * pt1(-Math.abs(t0), df, true, false) };
306
+ // EQU: H0 effect <= low (alternative "greater") and diff >= high ("less"); MET the reverse
307
+ const lower = { t: tL, se: seOut, df, pValue: pt1(tL, df, !equ, false) };
308
+ const upper = { t: tU, se: seOut, df, pValue: pt1(tU, df, equ, false) };
309
+ const pValue = equ ? Math.max(lower.pValue, upper.pValue) : Math.min(lower.pValue, upper.pValue);
310
+ if (!equ && raw[0] <= 0 && raw[1] >= 0 && pValue <= tTestRow.pValue)
311
+ warnings.push(MET_NOTE);
312
+ const q = qt1(alpha, df, false, false);
313
+ // the interval in the larger of the two units
314
+ const kc = Math.max(kE, kSE);
315
+ const [eC, sC] = [ldexp(effect, kE - kc), ldexp(se, kSE - kc)];
316
+ return reported(name, {
317
+ tTest: tTestRow,
318
+ lower,
319
+ upper,
320
+ pValue,
321
+ bounds: { raw, smd: smdB },
322
+ raw: { estimate: ldexp(effect, kE), se: seOut, confInt: [ldexp(eC - q * sC, kc), ldexp(eC + q * sC, kc)] },
323
+ smd: { label: smd.label, estimate: smd.estimate, se: smd.se, confInt: smd.confInt, df: smd.df, J: smd.J },
324
+ confLevel: 1 - 2 * alpha,
325
+ method,
326
+ hypothesis,
327
+ warnings,
328
+ });
329
+ }
330
+ /**
331
+ * Two one-sided t tests (TOST) of equivalence, or minimal-effect tests, for one sample, two samples or paired samples,
332
+ * with the standardised mean difference and its interval. Equivalent to `TOSTER::t_TOST()` in R.
333
+ *
334
+ * With `hypothesis: "EQU"` (the default) equivalence, low < difference < high, is shown at level alpha when both the
335
+ * test of the lower bound (alternative "greater") and that of the upper bound (alternative "less") reject; the
336
+ * p-value is the larger of the two. With `"MET"` the alternatives are reversed and the p-value is the smaller. The
337
+ * effect is the difference minus `mu`: mean(x) - mean(y) - mu (two samples, Welch's or pooled), the mean of x - y
338
+ * minus mu (paired) or the mean of x minus mu (one sample). The bounds, the raw estimate and interval and the
339
+ * standardised difference all refer to that effect. The intervals are 1 - 2 alpha intervals (90% for the default alpha
340
+ * 0.05).
341
+ *
342
+ * The standardised difference is Hedges' g (Cohen's d without `biasCorrection`) with the average SD
343
+ * `sqrt((s1² + s2²)/2)` for Welch's test, the pooled SD with `varEqual`, the SD of the differences for paired samples
344
+ * (d_z, or d_rm with `rmCorrection`), the SD of one sample with `glass`, or the SD for one sample. Its interval is from
345
+ * the noncentral t (`"nct"`, as exact roots; TOSTER's optimiser is about 1e-9 accurate), Goulet-Pelletier and
346
+ * Cousineau's (`"goulet"`), or `g -+ q se` with a t or normal quantile (`"t"`, `"z"`).
347
+ *
348
+ * Differences from TOSTER (decisions 20-23 of oracle/methodcomparison-behaviour.md): `mu` is subtracted everywhere
349
+ * (TOSTER tests the bounds on the difference itself, gives the raw interval of the difference, the two-sample SMD of
350
+ * the difference plus mu and the paired SMD without mu); the one-sample `"t"` and `"z"` intervals of the standardised
351
+ * difference are 1 - 2 alpha intervals (TOSTER's 1 - alpha); TOSTER's notes are warnings; alpha must be in (0, 0.5).
352
+ * With `mu` 0 only the last three apply.
353
+ *
354
+ * With 2 observations (df 1) Hedges' correction J(1) is 0: the bias-corrected standardised difference is 0 (and its
355
+ * `"nct"` interval), and some of its standard errors and intervals are NaN or infinite, as TOSTER's formulas give.
356
+ *
357
+ * @param x Sample (NaN values are dropped; for paired samples, the pairs with a NaN).
358
+ * @param y Second sample (omit for one sample).
359
+ * @param options See {@link TTOSTOptions}; the bounds are required.
360
+ * @returns See {@link TTOSTResult}.
361
+ * @throws TypeError without bounds, for options of the wrong type, or for samples that are not arrays of numbers
362
+ * (`null` or strings in them); RangeError for infinite values, alpha outside (0, 0.5), bounds that are not finite or
363
+ * in the wrong order, an unknown choice, or fewer than 2 observations in a sample; Error where the t test has too
364
+ * few observations or the data are essentially constant.
365
+ *
366
+ * @example
367
+ * ```ts
368
+ * const r = tTOST([5.1, 4.9, 5.6, 5.8, 6.0, 5.4, 5.2, 6.1], [5.3, 5.0, 5.5, 5.7, 5.9, 5.2, 4.8, 5.6, 5.0], { eqb: 0.5 });
369
+ * r.pValue; // 0.06280707532313813
370
+ * r.raw.confInt; // [-0.16777332363212605, 0.5261066569654603] (90%)
371
+ * r.smd.label; // "Hedges's g(av)"
372
+ * ```
373
+ *
374
+ * @category Hypothesis tests
375
+ */
376
+ export function tTOST(x, y, options = {}) {
377
+ checkOptions(options, T_TOST_KEYS, "tTOST"); // generated: option-keys.mjs
378
+ const s = settingsOf(options);
379
+ const given = boundsOf(options);
380
+ const { paired, varEqual, mu } = s;
381
+ const oneSample = y === undefined;
382
+ if (paired && oneSample)
383
+ throw new TypeError("'y' is required when paired is true");
384
+ checkSample(x, "x");
385
+ if (!oneSample)
386
+ checkSample(y, "y");
387
+ // the t test: its errors, method and df (R's t.test)
388
+ const tt = unreported(() => (oneSample ? tTest(x, { mu }) : tTest(x, y, { paired, varEqual, mu })));
389
+ const df = tt.parameter;
390
+ // the effect, its standard error (as tTest's) and the moments of the standardised difference, on the data scaled by
391
+ // the same power of 2 as in tTest (exact; the results are scaled back)
392
+ let m;
393
+ let k;
394
+ let effect;
395
+ let se;
396
+ if (oneSample) {
397
+ const sc = scaleToUnit([dropNaN(Array.from(x))]);
398
+ k = sc.k;
399
+ const v = sc.groups[0];
400
+ const vv = variance(v);
401
+ effect = mean(v) - ldexp(mu, -k);
402
+ se = Math.sqrt(vv / v.length);
403
+ m = { design: "one", n: v.length, delta: effect, s: Math.sqrt(vv) };
404
+ }
405
+ else if (paired) {
406
+ const [a0, b0] = completePairs(Array.from(x), Array.from(y));
407
+ const sc = scaleToUnit([a0, b0]);
408
+ k = sc.k;
409
+ const [a, b] = sc.groups;
410
+ const d = a.map((v, i) => v - b[i]);
411
+ const s1 = Math.sqrt(variance(a));
412
+ const s2 = Math.sqrt(variance(b));
413
+ // the SD of the differences directly (s1² + s2² - 2 r s1 s2 cancels for r near 1), and 1 - r from it:
414
+ // 1 - r = (sdif² - (s1 - s2)²) / (2 s1 s2)
415
+ const vd = variance(d);
416
+ const sdif = Math.sqrt(vd);
417
+ const oneMinusR = ((sdif - (s1 - s2)) * (sdif + (s1 - s2))) / (2 * s1 * s2);
418
+ effect = mean(d) - ldexp(mu, -k);
419
+ se = Math.sqrt(vd / d.length);
420
+ m = { design: "paired", n: d.length, delta: mean(a) - mean(b) - ldexp(mu, -k), s1, s2, sdif, oneMinusR };
421
+ }
422
+ else {
423
+ const sc = scaleToUnit([dropNaN(Array.from(x)), dropNaN(Array.from(y))]);
424
+ k = sc.k;
425
+ const [a, b] = sc.groups;
426
+ if (a.length < 2 || b.length < 2)
427
+ throw new RangeError("not enough observations: at least 2 are needed in each sample");
428
+ const [n1, n2, v1, v2] = [a.length, b.length, variance(a), variance(b)];
429
+ effect = mean(a) - mean(b) - ldexp(mu, -k);
430
+ // (tTest's forms)
431
+ se = varEqual
432
+ ? Math.sqrt((((n1 - 1) * v1 + (n2 - 1) * v2) / (n1 + n2 - 2)) * (1 / n1 + 1 / n2))
433
+ : Math.sqrt(Math.sqrt(v1 / n1) ** 2 + Math.sqrt(v2 / n2) ** 2);
434
+ m = { design: "two", n1, n2, delta: effect, s1: Math.sqrt(v1), s2: Math.sqrt(v2) };
435
+ }
436
+ return tostCore("tTOST", effect, k, se, k, df, tt.method, m, k, s, given, []);
437
+ }
438
+ /**
439
+ * {@link tTOST} from summary statistics: means, standard deviations, sample sizes and, for paired samples, the
440
+ * correlation of the pairs. Equivalent to `TOSTER::tsum_TOST()` in R.
441
+ *
442
+ * The tests and effect sizes are those of tTOST for data with these summaries (Welch's or pooled for two samples;
443
+ * paired from the SD of the differences sqrt(sd1² + sd2² - 2 r12 sd1 sd2)). The one-sided p-values are upper tails
444
+ * where TOSTER takes `1 - pt(t, df)`, so small ones keep their digits. For paired samples with n1 != n2 the smaller
445
+ * is used, with TOSTER's warning `Unequal number of pairs; using smallest n`.
446
+ *
447
+ * @param stats See {@link TsumTOSTStatistics}.
448
+ * @param options See {@link TTOSTOptions}; the bounds are required.
449
+ * @returns See {@link TTOSTResult}.
450
+ * @throws RangeError for sizes below 2 (or not integers), standard deviations that are not positive, a correlation
451
+ * outside (-1, 1), missing statistics of the second sample, or the errors of {@link tTOST}'s options.
452
+ *
453
+ * @example
454
+ * ```ts
455
+ * const r = tsumTOST({ m1: 5.5125, sd1: 0.4357, n1: 8, m2: 5.3333, sd2: 0.3536, n2: 9 }, { eqb: 0.5 });
456
+ * r.pValue; // 0.060568376615229305
457
+ * r.smd.confInt; // [-0.35185844793775967, 1.1906849789772087]
458
+ * ```
459
+ *
460
+ * @category Hypothesis tests
461
+ */
462
+ export function tsumTOST(stats, options = {}) {
463
+ checkOptions(stats, TSUM_TOST_KEYS_0, "tsumTOST"); // generated: option-keys.mjs
464
+ checkOptions(options, TSUM_TOST_KEYS_1, "tsumTOST"); // generated: option-keys.mjs
465
+ const s = settingsOf(options);
466
+ const given = boundsOf(options);
467
+ const { m1, sd1, n1, m2, sd2, n2, r12 } = stats;
468
+ const num = (v, name) => {
469
+ if (typeof v !== "number" || !Number.isFinite(v))
470
+ throw new RangeError(`'${name}' must be a finite number`);
471
+ return v;
472
+ };
473
+ const size = (v, name) => {
474
+ const n = num(v, name);
475
+ if (!(Number.isInteger(n) && n >= 2))
476
+ throw new RangeError(`'${name}' must be an integer of at least 2`);
477
+ return n;
478
+ };
479
+ const sdOf = (v, name) => {
480
+ const sd = num(v, name);
481
+ if (!(sd > 0))
482
+ throw new RangeError(`'${name}' must be positive`);
483
+ return sd;
484
+ };
485
+ num(m1, "m1");
486
+ sdOf(sd1, "sd1");
487
+ size(n1, "n1");
488
+ const oneSample = m2 === undefined && sd2 === undefined && n2 === undefined;
489
+ if (s.paired && oneSample)
490
+ throw new TypeError("'m2', 'sd2' and 'n2' are required when paired is true");
491
+ if (!oneSample) {
492
+ num(m2, "m2");
493
+ sdOf(sd2, "sd2");
494
+ size(n2, "n2");
495
+ }
496
+ const warnings = [];
497
+ // the means (with mu) and the SDs each scaled by one power of 2 of their own (exact): the SDs enter only through
498
+ // ratios with the difference and through the df, so a mean far larger than the SDs leaves their squares in range.
499
+ // The difference is in the units 2^kM, the SDs and the standard error in 2^kS; the moments in 2^kS
500
+ const { groups: gm, k: kM } = scaleToUnit([[m1, ...(oneSample ? [] : [m2]), s.mu]]);
501
+ const { groups: gs, k: kS } = scaleToUnit([[sd1, ...(oneSample ? [] : [sd2])]]);
502
+ const [a1, a2 = NaN] = oneSample ? [gm[0][0]] : [gm[0][0], gm[0][1]];
503
+ const muS = gm[0][gm[0].length - 1];
504
+ const [b1, b2 = NaN] = gs[0];
505
+ // the effect in the units of the SDs, for the standardised difference
506
+ const inS = (v) => ldexp(v, kM - kS);
507
+ let effect;
508
+ let se;
509
+ let df;
510
+ let method;
511
+ let m;
512
+ if (oneSample) {
513
+ effect = a1 - muS;
514
+ se = b1 / Math.sqrt(n1);
515
+ df = n1 - 1;
516
+ method = "One Sample t-test";
517
+ m = { design: "one", n: n1, delta: inS(effect), s: b1 };
518
+ }
519
+ else if (s.paired) {
520
+ const r = num(r12, "r12");
521
+ if (!(r > -1 && r < 1))
522
+ throw new RangeError("'r12' must be in (-1, 1)");
523
+ let n = n1;
524
+ if (n1 !== n2) {
525
+ warnings.push("Unequal number of pairs; using smallest n");
526
+ n = Math.min(n1, n2);
527
+ }
528
+ const sdif = Math.sqrt(b1 * b1 + b2 * b2 - 2 * r * b1 * b2);
529
+ if (!(sdif > 0))
530
+ throw new RangeError("the standard deviation of the differences is 0");
531
+ effect = a1 - a2 - muS;
532
+ se = sdif / Math.sqrt(n);
533
+ df = n - 1;
534
+ method = "Paired t-test";
535
+ m = { design: "paired", n, delta: inS(effect), s1: b1, s2: b2, sdif, oneMinusR: 1 - r };
536
+ }
537
+ else {
538
+ const n2v = n2;
539
+ const v1 = b1 * b1;
540
+ const v2 = b2 * b2;
541
+ effect = a1 - a2 - muS;
542
+ if (s.varEqual) {
543
+ const v = ((n1 - 1) * v1 + (n2v - 1) * v2) / (n1 + n2v - 2);
544
+ se = Math.sqrt(v * (1 / n1 + 1 / n2v));
545
+ df = n1 + n2v - 2;
546
+ method = " Two Sample t-test";
547
+ }
548
+ else {
549
+ const w1 = v1 / n1;
550
+ const w2 = v2 / n2v;
551
+ se = Math.sqrt(w1 + w2);
552
+ df = (w1 + w2) ** 2 / ((w1 * w1) / (n1 - 1) + (w2 * w2) / (n2v - 1));
553
+ method = "Welch Two Sample t-test";
554
+ }
555
+ m = { design: "two", n1, n2: n2v, delta: inS(effect), s1: b1, s2: b2 };
556
+ }
557
+ return tostCore("tsumTOST", effect, kM, se, kS, df, method, m, kS, s, given, warnings);
558
+ }