@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.
- package/CHANGELOG.md +128 -0
- package/README.ja.md +28 -11
- package/README.md +27 -10
- package/dist/chunks/{chunk-RRO4LMCB.js → chunk-27VFB3SA.js} +2 -2
- package/dist/chunks/{chunk-BKV3FINA.js → chunk-56GFP4UU.js} +2 -2
- package/dist/chunks/{chunk-JWBSEL3V.js → chunk-5SW3L6J3.js} +2 -2
- package/dist/chunks/{chunk-NSU6U3ET.js → chunk-6FZAJQ4H.js} +2 -2
- package/dist/chunks/{chunk-VERBXW6E.js → chunk-BQJFFGYP.js} +2 -2
- package/dist/chunks/{chunk-ORE5ZRCY.js → chunk-F6Z3GLWA.js} +2 -2
- package/dist/chunks/{chunk-2NNBUYHJ.js → chunk-GBSMRVUY.js} +2 -2
- package/dist/chunks/{chunk-7WG7X2UI.js → chunk-GEF2YRBV.js} +2 -2
- package/dist/chunks/{chunk-L23RSC2N.js → chunk-GIER5WMB.js} +2 -2
- package/dist/chunks/{chunk-IAWXF73N.js → chunk-GLGOV3A5.js} +2 -2
- package/dist/chunks/{chunk-F3EQLL4F.js → chunk-H72MW7YP.js} +2 -2
- package/dist/chunks/{chunk-T5DRIITM.js → chunk-HWB7XRX2.js} +2 -2
- package/dist/chunks/chunk-J72MLFUG.js +2 -0
- package/dist/chunks/{chunk-TNETWBF5.js → chunk-PZ66PUWC.js} +2 -2
- package/dist/chunks/{chunk-IMPRIQE5.js → chunk-RUZATICF.js} +1 -1
- package/dist/chunks/{chunk-BI7NYJWP.js → chunk-RY7CCWVU.js} +1 -1
- package/dist/chunks/{chunk-7INBXTVV.js → chunk-S2YCFUCA.js} +2 -2
- package/dist/chunks/chunk-SVS54D6Z.js +2 -0
- package/dist/chunks/{chunk-HBHMEPGY.js → chunk-TEHMTQNB.js} +3 -3
- package/dist/chunks/chunk-UMMCVF53.js +2 -0
- package/dist/chunks/{chunk-5SGTWSCB.js → chunk-UNP4HBPP.js} +2 -2
- package/dist/chunks/{chunk-A66M3ZEA.js → chunk-V2KVTAVV.js} +2 -2
- package/dist/chunks/{chunk-EEU7D4RU.js → chunk-WWJGCBWH.js} +1 -1
- package/dist/chunks/chunk-X7K6EF7S.js +2 -0
- package/dist/chunks/{chunk-73LNRWU3.js → chunk-YBOSCQF2.js} +1 -1
- package/dist/chunks/{chunk-6FZHTD5G.js → chunk-ZQSOMEIM.js} +2 -2
- package/dist/chunks/{chunk-4AOTAT3O.js → chunk-ZRFZ5UIB.js} +2 -2
- package/dist/descriptive.js +2 -2
- package/dist/distributions.js +2 -2
- package/dist/entries/tests.d.ts +13 -0
- package/dist/entries/tests.js +13 -0
- package/dist/htest/agreement.d.ts +2 -2
- package/dist/htest/blandAltman.d.ts +100 -0
- package/dist/htest/blandAltman.js +159 -0
- package/dist/htest/diagnosticTests.d.ts +91 -0
- package/dist/htest/diagnosticTests.js +116 -0
- package/dist/htest/iccPsych.d.ts +106 -0
- package/dist/htest/iccPsych.js +332 -0
- package/dist/htest/ksTest.d.ts +1 -1
- package/dist/htest/mcreg.d.ts +209 -0
- package/dist/htest/mcreg.js +735 -0
- package/dist/htest/roc.d.ts +287 -0
- package/dist/htest/roc.js +635 -0
- package/dist/htest/rocTest.d.ts +139 -0
- package/dist/htest/rocTest.js +444 -0
- package/dist/htest/tTOST.d.ts +202 -0
- package/dist/htest/tTOST.js +558 -0
- package/dist/htest/trendTests.d.ts +1 -1
- package/dist/htest/trendTests.js +1 -1
- package/dist/internal/summary.js +5 -0
- package/dist/linalg/qr.d.ts +3 -0
- package/dist/linalg/qr.js +3 -0
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +2 -2
- package/dist/models/coeftest.d.ts +139 -0
- package/dist/models/coeftest.js +237 -0
- package/dist/models/competingRisks.d.ts +188 -0
- package/dist/models/competingRisks.js +673 -0
- package/dist/models/coxZph.d.ts +67 -0
- package/dist/models/coxZph.js +479 -0
- package/dist/models/coxph.d.ts +107 -16
- package/dist/models/coxph.js +641 -72
- package/dist/models/glm.d.ts +11 -1
- package/dist/models/glm.js +19 -2
- package/dist/models/inputRows.d.ts +10 -0
- package/dist/models/inputRows.js +23 -0
- package/dist/models/lm.d.ts +8 -0
- package/dist/models/lm.js +14 -2
- package/dist/models/rmst2.d.ts +126 -0
- package/dist/models/rmst2.js +365 -0
- package/dist/models/sandwich.d.ts +177 -0
- package/dist/models/sandwich.js +923 -0
- package/dist/models/survival.d.ts +65 -24
- package/dist/models/survival.js +407 -72
- package/dist/models/survreg.d.ts +160 -0
- package/dist/models/survreg.js +809 -0
- package/dist/numerics.js +2 -2
- package/dist/random/rng.d.ts +8 -1
- package/dist/random/rng.js +14 -1
- package/dist/rstats.js +16 -16
- package/dist/special.js +2 -2
- package/dist/tests.js +13 -13
- package/llms.txt +25 -0
- package/package.json +1 -1
- package/dist/chunks/chunk-47IIPUFN.js +0 -2
- package/dist/chunks/chunk-CQB4BJBR.js +0 -2
|
@@ -0,0 +1,735 @@
|
|
|
1
|
+
// Method comparison regression, as mcr's mcreg: Deming regression, weighted Deming regression (constant coefficient
|
|
2
|
+
// of variation) and Passing-Bablok regression, with analytical, jackknife and bootstrap intervals of the intercept
|
|
3
|
+
// and slope (quantile, Student, BCa and bootstrap-t, the last with nested resamples), and the CUSUM statistic of
|
|
4
|
+
// linearity of Passing and Bablok.
|
|
5
|
+
//
|
|
6
|
+
// Written for rStats.js from oracle/methodcomparison-behaviour.md (section 2) and the published methods (no R or
|
|
7
|
+
// package code was read):
|
|
8
|
+
// - Deming: Cornbleet PJ, Gochman N (1979), Incorrect least-squares regression coefficients in method-comparison
|
|
9
|
+
// analysis, Clin Chem 25:432-438, and Linnet K (1990), Estimation of the linear relationship between the
|
|
10
|
+
// measurements of two methods with proportional errors, Stat Med 9:1463-1473 (λ = error variance of x over that of
|
|
11
|
+
// y, as mcr's error.ratio): the slope is the positive-discriminant root of λ p b² - (λq - u) b - p = 0 with u, q, p
|
|
12
|
+
// the centred sums of squares and products. Its analytical standard error is Strike PW (1991), Statistical Methods
|
|
13
|
+
// in Laboratory Medicine.
|
|
14
|
+
// - Weighted Deming: Linnet (1990), the iteration of the Deming fit with the weights 1/((x̂ + λŷ)/(1 + λ))² of the
|
|
15
|
+
// points projected on the current line; mcr's stopping rule (an absolute threshold on both coefficients).
|
|
16
|
+
// - Passing H, Bablok W (1983), A new biometrical procedure for testing the equality of measurements from two
|
|
17
|
+
// different analytical methods, J Clin Chem Clin Biochem 21:709-720: the shifted median of the pairwise slopes
|
|
18
|
+
// (slopes of -1 left out, the median shifted by the number K of slopes below -1), the rank interval with
|
|
19
|
+
// C = z sqrt(N(N - 1)(2N + 5)/18), the intercept as the median of y - b x, and the cumulative sum of the signs of the
|
|
20
|
+
// residuals ordered by their projection on the line (linearity). mcr stores each slope as an angle and averages
|
|
21
|
+
// two middle angles (or two slopes, "tangent").
|
|
22
|
+
// - Linnet K (1993), Evaluation of regression procedures for methods comparison studies, Clin Chem 39:424-432: the
|
|
23
|
+
// jackknife standard errors and intervals.
|
|
24
|
+
// - Efron B, Tibshirani RJ (1993), An Introduction to the Bootstrap: the bootstrap percentile, BCa (bias correction
|
|
25
|
+
// z0 and the jackknife acceleration) and bootstrap-t intervals.
|
|
26
|
+
//
|
|
27
|
+
// The data are divided by one power of 2 first (src/internal/summary.ts), so that the sums of squares and the 1e-12
|
|
28
|
+
// tie rule of Passing-Bablok can neither overflow nor underflow; the slope has no units, the intercept and its
|
|
29
|
+
// interval are scaled back at the end (exact).
|
|
30
|
+
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
31
|
+
import { qt1 } from "../distributions/t.js";
|
|
32
|
+
import { quantile } from "../descriptive/quantile.js";
|
|
33
|
+
import { RNGkind, getRandomSeed, isRandomSeeded, setRandomSeed, setSeed, unifIndex } from "../random/rng.js";
|
|
34
|
+
import { ldexp, ldexpWide, meanDD, scaleToUnit, standardDeviation } from "../internal/summary.js";
|
|
35
|
+
import { reported } from "../internal/warnings.js";
|
|
36
|
+
import { ddAdd, ddDivNum, ddMul, ddSub } from "../special/dd.js";
|
|
37
|
+
import { matchChoice } from "./power.js";
|
|
38
|
+
// Generated by `node scripts/option-keys.mjs --write` from the option types; do not edit (begin)
|
|
39
|
+
import { checkOptions } from "../internal/checkOptions.js";
|
|
40
|
+
const MCREG_KEYS = /* @__PURE__ */ new Set([
|
|
41
|
+
"methodReg", "methodCi", "methodBootstrapCi", "errorRatio", "confLevel", "slopeMeasure", "nsamples", "nnested",
|
|
42
|
+
"rngSeed", "iterMax", "threshold", "naRm",
|
|
43
|
+
]);
|
|
44
|
+
const METHODS = ["PaBa", "Deming", "WDeming"];
|
|
45
|
+
const CI_METHODS = ["analytical", "jackknife", "bootstrap", "nestedbootstrap"];
|
|
46
|
+
const BOOT_METHODS = ["quantile", "Student", "BCa", "tBoot"];
|
|
47
|
+
/** The largest number of points for Passing-Bablok: n(n - 1)/2 slopes in one array of at most 2^24 values */
|
|
48
|
+
const PABA_MAX_N = 5793;
|
|
49
|
+
/** The largest number of pairwise slopes of all the Passing-Bablok fits of a call (resamples and jackknife included) */
|
|
50
|
+
const PABA_MAX_SLOPES = 2 ** 27;
|
|
51
|
+
/**
|
|
52
|
+
* a - b, set to 0 when |a - b| < 1e-12 (|a| + |b|)/2: mcr's rule for ties of Passing-Bablok (and of 1 - r² in Deming's
|
|
53
|
+
* standard error). Applied to data scaled to [1, 2), so the sum cannot overflow
|
|
54
|
+
*/
|
|
55
|
+
function tieDiff(a, b) {
|
|
56
|
+
const d = a - b;
|
|
57
|
+
return Math.abs(d) < (1e-12 * (Math.abs(a) + Math.abs(b))) / 2 ? 0 : d;
|
|
58
|
+
}
|
|
59
|
+
/** Centred sums of squares and products (double-double) and the means of x and y */
|
|
60
|
+
function moments(x, y) {
|
|
61
|
+
const mx = meanDD(x);
|
|
62
|
+
const my = meanDD(y);
|
|
63
|
+
let u = [0, 0];
|
|
64
|
+
let q = [0, 0];
|
|
65
|
+
let p = [0, 0];
|
|
66
|
+
for (let i = 0; i < x.length; i++) {
|
|
67
|
+
const dx = ddSub([x[i], 0], mx);
|
|
68
|
+
const dy = ddSub([y[i], 0], my);
|
|
69
|
+
u = ddAdd(u, ddMul(dx, dx));
|
|
70
|
+
q = ddAdd(q, ddMul(dy, dy));
|
|
71
|
+
p = ddAdd(p, ddMul(dx, dy));
|
|
72
|
+
}
|
|
73
|
+
return { u, q, p, mx, my };
|
|
74
|
+
}
|
|
75
|
+
/**
|
|
76
|
+
* The Deming slope from the sums u (x), q (y), p (cross products) and λ: the root of λ p b² - (λq - u) b - p = 0 of
|
|
77
|
+
* the sign of p, (a + R)/(2λp) with a = λq - u and R = sqrt(a² + 4λp²), or 2p/(R - a) where a < 0 (the same root
|
|
78
|
+
* without cancellation: mcr's form gives slope 0 for λ = 1e-300). For λ > 1 the equation is divided by λ first, so
|
|
79
|
+
* that λq and λp² cannot overflow (λ = 1e300). NaN for p = 0 (no linear relation: the root is 0, infinite or
|
|
80
|
+
* undefined), as mcr
|
|
81
|
+
*/
|
|
82
|
+
function demingSlope(u, q, p, lambda) {
|
|
83
|
+
if (p === 0)
|
|
84
|
+
return NaN;
|
|
85
|
+
if (lambda <= 1) {
|
|
86
|
+
const a = lambda * q - u;
|
|
87
|
+
const r = Math.sqrt(a * a + 4 * lambda * p * p);
|
|
88
|
+
return a >= 0 ? (a + r) / (2 * lambda * p) : (2 * p) / (r - a);
|
|
89
|
+
}
|
|
90
|
+
// p b² - (q - u/λ) b - p/λ = 0
|
|
91
|
+
const a = q - u / lambda;
|
|
92
|
+
const r = Math.sqrt(a * a + (4 * p * p) / lambda);
|
|
93
|
+
return a >= 0 ? (a + r) / (2 * p) : (2 * p) / lambda / (r - a);
|
|
94
|
+
}
|
|
95
|
+
/** Deming regression with Strike's analytical standard errors, on scaled data */
|
|
96
|
+
function demingFit(x, y, lambda) {
|
|
97
|
+
const n = x.length;
|
|
98
|
+
const { u, q, p, mx, my } = moments(x, y);
|
|
99
|
+
const b1 = demingSlope(u[0], q[0], p[0], lambda);
|
|
100
|
+
const b0 = ddSub(my, ddMul([b1, 0], mx))[0];
|
|
101
|
+
// 1 - r² = (uq - p²)/(uq), formed in double-double (mcr's 1 - p²/(uq) loses digits for r near 1), set to 0 by the
|
|
102
|
+
// tie rule as mcr does (an exact line has standard errors 0)
|
|
103
|
+
const uq = ddMul(u, q);
|
|
104
|
+
const r2 = (p[0] * p[0]) / (u[0] * q[0]);
|
|
105
|
+
let omr2 = ddSub(uq, ddMul(p, p))[0] / (uq[0] + uq[1]);
|
|
106
|
+
if (Math.abs(omr2) < (1e-12 * (1 + r2)) / 2)
|
|
107
|
+
omr2 = 0;
|
|
108
|
+
const se1 = Math.sqrt((b1 * b1 * omr2) / r2 / (n - 2));
|
|
109
|
+
let sx2 = [0, 0];
|
|
110
|
+
for (const v of x)
|
|
111
|
+
sx2 = ddAdd(sx2, ddMul([v, 0], [v, 0]));
|
|
112
|
+
const se0 = Math.sqrt(se1 * se1 * ddDivNum(sx2, n)[0]);
|
|
113
|
+
return { b0, b1, se0, se1, xmean: mx[0] };
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Weighted Deming regression (Linnet 1990) with mcr's stopping rule, on x scaled by 2^-kx and y by 2^-ky, with the
|
|
117
|
+
* error ratio of the scaled data (lambda) and mix = errorRatio 2^(ky - kx): the level m = (x̂ + errorRatio ŷ)/(1 +
|
|
118
|
+
* errorRatio) of a point is, up to one constant factor, x̂ + mix ŷ in the scaled units. The weights 1/m² enter only
|
|
119
|
+
* through the weighted means (with the weights divided by the largest, so that they cannot overflow) and the sums
|
|
120
|
+
* of (dx/m)², (dy/m)² and dx dy/m², which do not depend on that factor (the slope is homogeneous in them); mcr's
|
|
121
|
+
* weights 1/m², which overflow for data spanning more than about 1e154, are formed only for output
|
|
122
|
+
*/
|
|
123
|
+
function wdemingFit(x, y, lambda, mix, errorRatio, iterMax, threshold, kx, ky) {
|
|
124
|
+
const n = x.length;
|
|
125
|
+
const start = demingFit(x, y, lambda);
|
|
126
|
+
let b0 = start.b0;
|
|
127
|
+
let b1 = start.b1;
|
|
128
|
+
let xmean = NaN;
|
|
129
|
+
// m up to the factor (mix > 1 ? mix : 1)/(1 + errorRatio) 2^kx: x̂ + mix ŷ, or x̂/mix + ŷ for mix > 1
|
|
130
|
+
const m = new Array(n);
|
|
131
|
+
let count = iterMax;
|
|
132
|
+
for (let i = 0; i < iterMax; i++) {
|
|
133
|
+
const f = 1 + lambda * b1 * b1;
|
|
134
|
+
let mMin = Infinity;
|
|
135
|
+
for (let j = 0; j < n; j++) {
|
|
136
|
+
const d = y[j] - (b0 + b1 * x[j]);
|
|
137
|
+
const xh = x[j] + (lambda * b1 * d) / f;
|
|
138
|
+
const yh = y[j] - d / f;
|
|
139
|
+
m[j] = mix > 1 ? xh / mix + yh : xh + mix * yh;
|
|
140
|
+
mMin = Math.min(mMin, Math.abs(m[j]));
|
|
141
|
+
}
|
|
142
|
+
let sw = [0, 0];
|
|
143
|
+
let swx = [0, 0];
|
|
144
|
+
let swy = [0, 0];
|
|
145
|
+
for (let j = 0; j < n; j++) {
|
|
146
|
+
// the weight relative to the largest, (mMin/m)^2 <= 1
|
|
147
|
+
const r = mMin / m[j];
|
|
148
|
+
const wj = [r * r, 0];
|
|
149
|
+
sw = ddAdd(sw, wj);
|
|
150
|
+
swx = ddAdd(swx, ddMul(wj, [x[j], 0]));
|
|
151
|
+
swy = ddAdd(swy, ddMul(wj, [y[j], 0]));
|
|
152
|
+
}
|
|
153
|
+
const xw = ddDivNum(swx, sw[0] + sw[1]);
|
|
154
|
+
const yw = ddDivNum(swy, sw[0] + sw[1]);
|
|
155
|
+
let u = [0, 0];
|
|
156
|
+
let q = [0, 0];
|
|
157
|
+
let p = [0, 0];
|
|
158
|
+
for (let j = 0; j < n; j++) {
|
|
159
|
+
const dx = ddDivNum(ddSub([x[j], 0], xw), m[j]);
|
|
160
|
+
const dy = ddDivNum(ddSub([y[j], 0], yw), m[j]);
|
|
161
|
+
u = ddAdd(u, ddMul(dx, dx));
|
|
162
|
+
q = ddAdd(q, ddMul(dy, dy));
|
|
163
|
+
p = ddAdd(p, ddMul(dx, dy));
|
|
164
|
+
}
|
|
165
|
+
const B1 = demingSlope(u[0], q[0], p[0], lambda);
|
|
166
|
+
const B0 = ddSub(yw, ddMul([B1, 0], xw))[0];
|
|
167
|
+
xmean = xw[0];
|
|
168
|
+
// the threshold is absolute, on the slope and the intercept in the units of the data
|
|
169
|
+
const done = ldexp(Math.abs(b1 - B1), ky - kx) < threshold && ldexp(Math.abs(b0 - B0), ky) < threshold;
|
|
170
|
+
b0 = B0;
|
|
171
|
+
b1 = B1;
|
|
172
|
+
if (done) {
|
|
173
|
+
count = i + 1;
|
|
174
|
+
break;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
// mcr's weights 1/m² in the units of the data (Infinity or 0 where they leave the double range). The true level is
|
|
178
|
+
// m (errorRatio/(1 + errorRatio)) 2^ky for mix > 1 and m/(1 + errorRatio) 2^kx otherwise; the powers of 2 of
|
|
179
|
+
// errorRatio, 1 + errorRatio and the units are carried apart from the products, which would overflow or underflow
|
|
180
|
+
// where x and y have very different units although the weight itself is representable
|
|
181
|
+
const [sR, tR] = split(errorRatio);
|
|
182
|
+
const [s1, t1] = split(1 + errorRatio);
|
|
183
|
+
// m itself is split as well: its values may span more than 2^512 (a point near 0 among large ones), where squaring
|
|
184
|
+
// 1/m before applying the exponent overflowed although the weight is representable
|
|
185
|
+
const weights = m.map((v) => {
|
|
186
|
+
if (v === 0)
|
|
187
|
+
return Infinity;
|
|
188
|
+
const [sv, tv] = split(Math.abs(v));
|
|
189
|
+
return mix > 1
|
|
190
|
+
? ldexpWide((s1 / (sR * sv)) ** 2, 2 * (t1 - tR - tv - ky))
|
|
191
|
+
: ldexpWide((s1 / sv) ** 2, 2 * (t1 - tv - kx));
|
|
192
|
+
});
|
|
193
|
+
// as mcr: the warning also when the last allowed iteration converged
|
|
194
|
+
return { b0, b1, xmean, weights, converged: count < iterMax };
|
|
195
|
+
}
|
|
196
|
+
/** A positive finite v as [s, t] with v = s 2^t exactly, s in [1/2, 4) */
|
|
197
|
+
function split(v) {
|
|
198
|
+
const t = Math.floor(Math.log2(v));
|
|
199
|
+
return [ldexpWide(v, -t), t];
|
|
200
|
+
}
|
|
201
|
+
/** The angle of a slope (±π/2 for a vertical pair) */
|
|
202
|
+
const angle = (s) => Math.atan(s);
|
|
203
|
+
/** The slope of an entry of the sorted list: dy/dx itself, tan(±π/2) for a vertical pair (as mcr's tan of the angle) */
|
|
204
|
+
const slopeOf = (s) => (Number.isFinite(s) ? s : Math.tan(angle(s)));
|
|
205
|
+
/**
|
|
206
|
+
* The pairwise slopes of Passing-Bablok, sorted. Differences below a relative 1e-12 are 0 (mcr's rule); a vertical pair
|
|
207
|
+
* is +Infinity for a positive (or zero) Kendall correlation and -Infinity otherwise, a pair with both differences 0
|
|
208
|
+
* is left out. The counts compare the angles atan(dy/dx) with ∓π/4, as mcr
|
|
209
|
+
*/
|
|
210
|
+
function pabaSlopes(x, y) {
|
|
211
|
+
const n = x.length;
|
|
212
|
+
// Kendall's S: its sign is that of tau_b
|
|
213
|
+
let s = 0;
|
|
214
|
+
for (let j = 0; j < n; j++) {
|
|
215
|
+
for (let k = j + 1; k < n; k++)
|
|
216
|
+
s += Math.sign(x[k] - x[j]) * Math.sign(y[k] - y[j]);
|
|
217
|
+
}
|
|
218
|
+
const posCor = s >= 0;
|
|
219
|
+
const slopes = new Float64Array((n * (n - 1)) / 2);
|
|
220
|
+
let m = 0;
|
|
221
|
+
let e = 0;
|
|
222
|
+
let kk = 0;
|
|
223
|
+
const quarter = Math.PI / 4;
|
|
224
|
+
for (let j = 0; j < n; j++) {
|
|
225
|
+
for (let k = j + 1; k < n; k++) {
|
|
226
|
+
const dx = tieDiff(x[k], x[j]);
|
|
227
|
+
const dy = tieDiff(y[k], y[j]);
|
|
228
|
+
let v;
|
|
229
|
+
if (dx !== 0)
|
|
230
|
+
v = dy / dx;
|
|
231
|
+
else if (dy !== 0)
|
|
232
|
+
v = posCor ? Infinity : -Infinity;
|
|
233
|
+
else
|
|
234
|
+
continue;
|
|
235
|
+
slopes[m++] = v;
|
|
236
|
+
const t = angle(v);
|
|
237
|
+
if (posCor) {
|
|
238
|
+
if (t === -quarter)
|
|
239
|
+
e++;
|
|
240
|
+
else if (t < -quarter)
|
|
241
|
+
kk++;
|
|
242
|
+
}
|
|
243
|
+
else if (t === quarter)
|
|
244
|
+
e++;
|
|
245
|
+
else if (t > quarter)
|
|
246
|
+
kk++;
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const sorted = slopes.subarray(0, m).sort();
|
|
250
|
+
return { sorted, offset: posCor ? 2 * kk + e : -(2 * kk + e), e };
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* The slope at the shifted median position m (1-based, of the sorted list): the entry (m + 1)/2 for odd m, the mean of
|
|
254
|
+
* the entries m/2 and m/2 + 1 for even m (tan of the mean angle, or the mean slope). NaN if a position is outside
|
|
255
|
+
*/
|
|
256
|
+
function pabaAt(sorted, m, tangent) {
|
|
257
|
+
const len = sorted.length;
|
|
258
|
+
if (m % 2 !== 0) {
|
|
259
|
+
const j = (m + 1) / 2;
|
|
260
|
+
return j >= 1 && j <= len ? slopeOf(sorted[j - 1]) : NaN;
|
|
261
|
+
}
|
|
262
|
+
const j = m / 2;
|
|
263
|
+
if (j < 1 || j + 1 > len)
|
|
264
|
+
return NaN;
|
|
265
|
+
const l = sorted[j - 1];
|
|
266
|
+
const r = sorted[j];
|
|
267
|
+
return tangent ? (slopeOf(l) + slopeOf(r)) / 2 : Math.tan((angle(l) + angle(r)) / 2);
|
|
268
|
+
}
|
|
269
|
+
/** The median (R's: the mean of the two middle values for an even count) */
|
|
270
|
+
function median(v) {
|
|
271
|
+
const s = Float64Array.from(v).sort();
|
|
272
|
+
const h = s.length >> 1;
|
|
273
|
+
return s.length % 2 === 1 ? s[h] : (s[h - 1] + s[h]) / 2;
|
|
274
|
+
}
|
|
275
|
+
/** median(y - b x) with the tie rule (Passing-Bablok's intercept); ∓Infinity for a slope of ±Infinity */
|
|
276
|
+
function pabaIntercept(x, y, b) {
|
|
277
|
+
if (!Number.isFinite(b))
|
|
278
|
+
return -b;
|
|
279
|
+
return median(x.map((v, i) => tieDiff(y[i], b * v)));
|
|
280
|
+
}
|
|
281
|
+
/** Passing-Bablok's estimates, on scaled data */
|
|
282
|
+
function pabaFit(x, y, tangent) {
|
|
283
|
+
const slopes = pabaSlopes(x, y);
|
|
284
|
+
const b1 = pabaAt(slopes.sorted, slopes.sorted.length + slopes.offset, tangent);
|
|
285
|
+
return { b0: Number.isNaN(b1) ? NaN : pabaIntercept(x, y, b1), b1, slopes };
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Passing-Bablok's rank interval of the slope at the normal quantile z, and the intercept's: [-Inf, Inf] for both
|
|
289
|
+
* where either end is not defined (too few points), with defined false
|
|
290
|
+
*/
|
|
291
|
+
function pabaInterval(x, y, slopes, z, tangent) {
|
|
292
|
+
const n = x.length;
|
|
293
|
+
const { sorted, offset, e } = slopes;
|
|
294
|
+
const len = sorted.length;
|
|
295
|
+
// (Math.round rounds halves up, which for positive values is C's round, away from zero)
|
|
296
|
+
const c = Math.round(z * Math.sqrt((n * (n - 1) * (2 * n + 5)) / 18));
|
|
297
|
+
const end = (m, lower) => {
|
|
298
|
+
// C's integer division: truncation toward 0
|
|
299
|
+
const j = Math.trunc((m + 1) / 2);
|
|
300
|
+
if (lower ? j < 2 * e + 1 : j > len)
|
|
301
|
+
return NaN;
|
|
302
|
+
if (m % 2 === 0) {
|
|
303
|
+
if (j + 1 > len)
|
|
304
|
+
return NaN;
|
|
305
|
+
const l = sorted[j - 1];
|
|
306
|
+
const r = sorted[j];
|
|
307
|
+
return tangent ? (slopeOf(l) + slopeOf(r)) / 2 : Math.tan((angle(l) + angle(r)) / 2);
|
|
308
|
+
}
|
|
309
|
+
return slopeOf(sorted[j - 1]);
|
|
310
|
+
};
|
|
311
|
+
const lo = end(len - c + offset, true);
|
|
312
|
+
const hi = end(len + c + offset, false);
|
|
313
|
+
if (Number.isNaN(lo) || Number.isNaN(hi))
|
|
314
|
+
return { slope: [-Infinity, Infinity], intercept: [-Infinity, Infinity], defined: false };
|
|
315
|
+
return { slope: [lo, hi], intercept: [pabaIntercept(x, y, hi), pabaIntercept(x, y, lo)], defined: true };
|
|
316
|
+
}
|
|
317
|
+
/**
|
|
318
|
+
* Passing and Bablok's linearity statistic for the fit (b0, b1): the scores +sqrt(L/l) of the l points above the line
|
|
319
|
+
* and -sqrt(l/L) of the L below (0 on it), cumulated in the order of the projections (y + x/b1 - b0)/sqrt(1 + 1/b1²)
|
|
320
|
+
* (ties in the data order)
|
|
321
|
+
*/
|
|
322
|
+
function cusumOf(x, y, b0, b1) {
|
|
323
|
+
const n = x.length;
|
|
324
|
+
const r = x.map((v, i) => y[i] - b0 - b1 * v);
|
|
325
|
+
const l = r.filter((v) => v > 0).length;
|
|
326
|
+
const L = r.filter((v) => v < 0).length;
|
|
327
|
+
const up = Math.sqrt(L / l);
|
|
328
|
+
const down = -Math.sqrt(l / L);
|
|
329
|
+
const d = x.map((v, i) => (y[i] + v / b1 - b0) / Math.sqrt(1 + 1 / (b1 * b1)));
|
|
330
|
+
const order = Array.from({ length: n }, (_, i) => i).sort((a, b) => d[a] - d[b] || a - b);
|
|
331
|
+
let s = 0;
|
|
332
|
+
let max = 0;
|
|
333
|
+
for (const i of order) {
|
|
334
|
+
const v = r[i];
|
|
335
|
+
s += v > 0 ? up : v < 0 ? down : 0;
|
|
336
|
+
max = Math.max(max, Math.abs(s));
|
|
337
|
+
}
|
|
338
|
+
return { nPos: l, nNeg: L, maxCusum: max };
|
|
339
|
+
}
|
|
340
|
+
/** Whether all values are equal */
|
|
341
|
+
const constant = (v) => v.every((u) => u === v[0]);
|
|
342
|
+
/** A positive integer option */
|
|
343
|
+
function positiveInteger(v, name) {
|
|
344
|
+
if (!(typeof v === "number" && Number.isInteger(v) && v >= 1))
|
|
345
|
+
throw new RangeError(`'${name}' must be a positive integer`);
|
|
346
|
+
return v;
|
|
347
|
+
}
|
|
348
|
+
/** Type 7 quantile of the values at p in [0, 1] */
|
|
349
|
+
const q7 = (v, p) => quantile(v, p);
|
|
350
|
+
/** Standard deviation without the NaN values (R's sd(na.rm = TRUE)) */
|
|
351
|
+
const sdNaRm = (v) => standardDeviation(v.filter((u) => !Number.isNaN(u)));
|
|
352
|
+
/**
|
|
353
|
+
* Method comparison regression of y (test method) on x (reference method): Deming, weighted Deming or Passing-Bablok
|
|
354
|
+
* regression with analytical, jackknife or bootstrap intervals. Equivalent to `mcr::mcreg()` in R.
|
|
355
|
+
*
|
|
356
|
+
* - **Deming** (`"Deming"`): the slope minimises the squared distances in the metric of the error variances, λ =
|
|
357
|
+
* `errorRatio` = σ²(x)/σ²(y) (mcr's convention; λ → 0 gives the least-squares slope of y on x). The analytical
|
|
358
|
+
* standard errors are Strike's (1991), with t intervals on n - 2 degrees of freedom.
|
|
359
|
+
* - **Weighted Deming** (`"WDeming"`): Linnet's (1990) iteration for errors proportional to the level (constant
|
|
360
|
+
* coefficient of variation), stopped as mcr when both coefficients change by less than `threshold` (absolute), with
|
|
361
|
+
* a warning when `iterMax` iterations are reached. No analytical interval (jackknife by default). Values must be
|
|
362
|
+
* positive. Since the threshold is absolute, data of very large magnitude (around 1e150) may not converge and
|
|
363
|
+
* data of very small magnitude (around 1e-150) stop after the first iteration; choose `threshold` in the units of
|
|
364
|
+
* the data.
|
|
365
|
+
* - **Passing-Bablok** (`"PaBa"`): the shifted median of the n(n - 1)/2 pairwise slopes and the rank interval of
|
|
366
|
+
* Passing and Bablok (1983); the intercept is the median of y - b x and its limits those of the slope's limits.
|
|
367
|
+
* Differences below a relative 1e-12 count as ties (mcr's rule; a pair tied in x only is vertical), so data with a
|
|
368
|
+
* large offset (1e12 + O(1)) have most differences set to 0; the mean of two middle slopes is tan of the mean angle
|
|
369
|
+
* (`slopeMeasure: "radian"`, mcr's default; it changes when y is rescaled, as angles do not scale) or the mean slope
|
|
370
|
+
* (`"tangent"`). Where the interval is not defined (too few points, always for n <= 4) its limits and the
|
|
371
|
+
* intercept's are -Infinity and Infinity, with a warning. Values must not be negative. The result has the CUSUM
|
|
372
|
+
* statistic of linearity (`cusum`; no test decision).
|
|
373
|
+
* - **jackknife**: the leave-one-out estimates, the standard error sd(pseudo-values)/sqrt(n) and the interval estimate
|
|
374
|
+
* ± t se on n - 2 degrees of freedom (Linnet 1993); the estimates are those of all the data.
|
|
375
|
+
* - **bootstrap**: `nsamples` resamples of the pairs with replacement; `"quantile"` the percentile interval,
|
|
376
|
+
* `"Student"` estimate ± t sd(B), `"BCa"` the bias-corrected and accelerated interval (jackknife acceleration),
|
|
377
|
+
* `"tBoot"` the bootstrap-t interval with the analytical standard errors (Deming) or, with `"nestedbootstrap"`, the
|
|
378
|
+
* standard deviation of `nnested` inner resamples of each resample. Resamples with constant x or y are dropped
|
|
379
|
+
* with mcr's warning (an error when more than 5% are). The resamples are drawn as R's `sample(1:n, n, replace =
|
|
380
|
+
* TRUE)` from the current random stream, or from `set.seed(rngSeed)` as mcr's `rng.seed` (the generator's state is
|
|
381
|
+
* then restored if it had one), so the values are mcr's for the same seed. With very few points (n = 5) the
|
|
382
|
+
* bootstrap-t limits can be infinite or huge, because resamples of 2 or 3 distinct points have standard errors 0.
|
|
383
|
+
*
|
|
384
|
+
* Unlike mcr, the default interval is `"analytical"` (`"jackknife"` for weighted Deming) rather than a random
|
|
385
|
+
* bootstrap; `confLevel` replaces mcr's `alpha` (= 1 - confLevel); 2 or fewer points, constant x or y, infinite
|
|
386
|
+
* values and data whose Deming covariance is 0 are errors. Passing-Bablok's odd-position slopes are dy/dx (mcr: tan of
|
|
387
|
+
* its angle, a few ulps off). PaBaLarge, LinReg, WLinReg, PBequi and TS are not offered.
|
|
388
|
+
*
|
|
389
|
+
* @param x Measurements by the reference method.
|
|
390
|
+
* @param y Measurements by the test method, paired with `x`.
|
|
391
|
+
* @param options See {@link McregOptions}.
|
|
392
|
+
* @returns See {@link McregResult}.
|
|
393
|
+
* @throws TypeError if `x` and `y` differ in length; RangeError for missing values without `naRm`, infinite values,
|
|
394
|
+
* fewer than 3 pairs, constant x or y, negative values (Passing-Bablok), values that are not positive (weighted
|
|
395
|
+
* Deming), more than 5793 points (Passing-Bablok), an analytical interval for weighted Deming, a bootstrap-t
|
|
396
|
+
* interval without nested resamples for Passing-Bablok or weighted Deming, too many degenerate resamples, a zero
|
|
397
|
+
* covariance (Deming), or an invalid option.
|
|
398
|
+
*
|
|
399
|
+
* @example
|
|
400
|
+
* ```ts
|
|
401
|
+
* const x = [1, 2, 3, 4, 5, 6, 7];
|
|
402
|
+
* const y = [1.2, 1.9, 3.2, 3.8, 5.1, 6.4, 6.6];
|
|
403
|
+
* const d = mcreg(x, y, { methodReg: "Deming" });
|
|
404
|
+
* d.slope.estimate; // 0.97547950725034482
|
|
405
|
+
* d.slope.confInt; // [0.83267195599246846, 1.1182870585082212]
|
|
406
|
+
* const pb = mcreg(x, y); // Passing-Bablok
|
|
407
|
+
* pb.slope.estimate; // 0.95
|
|
408
|
+
* pb.intercept.confInt; // [-0.8524794459077718, 0.80365513709218339]
|
|
409
|
+
* ```
|
|
410
|
+
*
|
|
411
|
+
* @category Agreement, reliability and factor analysis
|
|
412
|
+
*/
|
|
413
|
+
export function mcreg(x, y, options = {}) {
|
|
414
|
+
checkOptions(options, MCREG_KEYS, "mcreg"); // generated: option-keys.mjs
|
|
415
|
+
const methodReg = matchChoice(options.methodReg, METHODS);
|
|
416
|
+
const methodCi = matchChoice(options.methodCi ?? (methodReg === "WDeming" ? "jackknife" : "analytical"), CI_METHODS);
|
|
417
|
+
const bootstrap = methodCi === "bootstrap" || methodCi === "nestedbootstrap";
|
|
418
|
+
const methodBootstrapCi = matchChoice(options.methodBootstrapCi, BOOT_METHODS);
|
|
419
|
+
const confLevel = options.confLevel ?? 0.95;
|
|
420
|
+
if (!(typeof confLevel === "number" && confLevel > 0 && confLevel < 1))
|
|
421
|
+
throw new RangeError("'confLevel' must be a single number in (0, 1)");
|
|
422
|
+
const slopeMeasure = matchChoice(options.slopeMeasure, ["radian", "tangent"]);
|
|
423
|
+
const tangent = slopeMeasure === "tangent";
|
|
424
|
+
const deming = methodReg !== "PaBa";
|
|
425
|
+
const errorRatio = deming ? (options.errorRatio ?? 1) : 1;
|
|
426
|
+
if (deming && !(typeof errorRatio === "number" && errorRatio > 0 && errorRatio < Infinity)) {
|
|
427
|
+
throw new RangeError("'errorRatio' must be a positive finite number");
|
|
428
|
+
}
|
|
429
|
+
const nsamples = positiveInteger(options.nsamples ?? 999, "nsamples");
|
|
430
|
+
const nnested = positiveInteger(options.nnested ?? 25, "nnested");
|
|
431
|
+
const iterMax = positiveInteger(options.iterMax ?? 30, "iterMax");
|
|
432
|
+
const threshold = options.threshold ?? 1e-6;
|
|
433
|
+
if (!(typeof threshold === "number" && threshold >= 0 && threshold < Infinity))
|
|
434
|
+
throw new RangeError("'threshold' must be a nonnegative number");
|
|
435
|
+
if (methodReg === "WDeming" && methodCi === "analytical") {
|
|
436
|
+
throw new RangeError("there is no analytical interval for weighted Deming regression (use methodCi \"jackknife\" or a bootstrap)");
|
|
437
|
+
}
|
|
438
|
+
if (methodCi === "bootstrap" && methodBootstrapCi === "tBoot" && methodReg !== "Deming") {
|
|
439
|
+
throw new RangeError(`the bootstrap-t interval of ${methodReg} needs methodCi "nestedbootstrap" (there is no analytical standard error)`);
|
|
440
|
+
}
|
|
441
|
+
// the data
|
|
442
|
+
if (x.length !== y.length)
|
|
443
|
+
throw new TypeError("'x' and 'y' must have the same length");
|
|
444
|
+
const xa = [];
|
|
445
|
+
const ya = [];
|
|
446
|
+
for (let i = 0; i < x.length; i++) {
|
|
447
|
+
const u = x[i];
|
|
448
|
+
const v = y[i];
|
|
449
|
+
if (typeof u !== "number" || typeof v !== "number")
|
|
450
|
+
throw new TypeError("'x' and 'y' must be numeric");
|
|
451
|
+
if (Number.isNaN(u) || Number.isNaN(v)) {
|
|
452
|
+
if (options.naRm === true)
|
|
453
|
+
continue;
|
|
454
|
+
throw new RangeError("'x' or 'y' has missing values (use naRm: true to drop the incomplete pairs)");
|
|
455
|
+
}
|
|
456
|
+
if (!Number.isFinite(u) || !Number.isFinite(v))
|
|
457
|
+
throw new RangeError("'x' and 'y' must not contain infinite values");
|
|
458
|
+
xa.push(u);
|
|
459
|
+
ya.push(v);
|
|
460
|
+
}
|
|
461
|
+
const n = xa.length;
|
|
462
|
+
if (n <= 2)
|
|
463
|
+
throw new RangeError("mcreg needs at least 3 complete pairs");
|
|
464
|
+
if (constant(xa) || constant(ya))
|
|
465
|
+
throw new RangeError("'x' and 'y' must not be constant");
|
|
466
|
+
if (methodReg === "PaBa") {
|
|
467
|
+
if (xa.some((v) => v < 0) || ya.some((v) => v < 0))
|
|
468
|
+
throw new RangeError("Passing-Bablok regression needs nonnegative values");
|
|
469
|
+
if (n > PABA_MAX_N)
|
|
470
|
+
throw new RangeError(`Passing-Bablok regression is limited to ${PABA_MAX_N} points (2^24 pairwise slopes)`);
|
|
471
|
+
// rule 4: about 0.1 µs per slope, so 2^27 slopes over all the fits take about 10 s
|
|
472
|
+
const fits = 1 +
|
|
473
|
+
(methodCi === "jackknife" || (bootstrap && methodBootstrapCi === "BCa") ? n : 0) +
|
|
474
|
+
(bootstrap ? nsamples * (1 + (methodCi === "nestedbootstrap" ? nnested : 0)) : 0);
|
|
475
|
+
if (fits * ((n * (n - 1)) / 2) > PABA_MAX_SLOPES) {
|
|
476
|
+
throw new RangeError("the Passing-Bablok fits would take more than 2^27 pairwise slopes in all (reduce nsamples or nnested)");
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
if (methodReg === "WDeming" && (xa.some((v) => v <= 0) || ya.some((v) => v <= 0))) {
|
|
480
|
+
throw new RangeError("weighted Deming regression needs positive values");
|
|
481
|
+
}
|
|
482
|
+
// the data scaled by powers of 2 (exact): Deming and weighted Deming scale x and y separately (x by 2^-kx, y by
|
|
483
|
+
// 2^-ky, the error ratio by 2^(2(ky - kx))), so that data in very different units keep their sums of squares in
|
|
484
|
+
// range; Passing-Bablok scales both by one power (its tie rule and angles compare dy with dx). The slope is
|
|
485
|
+
// scaled back by 2^(ky - kx), the intercept by 2^ky
|
|
486
|
+
const common = scaleToUnit([xa, ya]);
|
|
487
|
+
const [kx, ky] = deming ? [scaleToUnit([xa]).k, scaleToUnit([ya]).k] : [common.k, common.k];
|
|
488
|
+
const xs = deming ? xa.map((v) => ldexp(v, -kx)) : common.groups[0];
|
|
489
|
+
const ys = deming ? ya.map((v) => ldexp(v, -ky)) : common.groups[1];
|
|
490
|
+
// the scaled error ratio, kept from 0 and Infinity (a ratio beyond 2^±1000 of the scaled data is the limit itself to
|
|
491
|
+
// far below the rounding of the sums)
|
|
492
|
+
const lambda = Math.min(Math.max(ldexpWide(errorRatio, 2 * (ky - kx)), Number.MIN_VALUE), 2 ** 1000);
|
|
493
|
+
const mix = ldexpWide(errorRatio, ky - kx);
|
|
494
|
+
const warnings = new Set();
|
|
495
|
+
const noConvergence = `no konvergence after ${iterMax} iterations`;
|
|
496
|
+
/** The estimates for the points idx (in the scaled units), and the analytical standard errors for Deming */
|
|
497
|
+
const fitOf = (xv, yv) => {
|
|
498
|
+
if (methodReg === "Deming")
|
|
499
|
+
return demingFit(xv, yv, lambda);
|
|
500
|
+
if (methodReg === "WDeming") {
|
|
501
|
+
const f = wdemingFit(xv, yv, lambda, mix, errorRatio, iterMax, threshold, kx, ky);
|
|
502
|
+
if (!f.converged)
|
|
503
|
+
warnings.add(noConvergence);
|
|
504
|
+
return f;
|
|
505
|
+
}
|
|
506
|
+
return pabaFit(xv, yv, tangent);
|
|
507
|
+
};
|
|
508
|
+
// the estimates of all the data
|
|
509
|
+
let global;
|
|
510
|
+
let xmean = NaN;
|
|
511
|
+
let weights;
|
|
512
|
+
let analytic;
|
|
513
|
+
let pabaSlopesAll;
|
|
514
|
+
if (methodReg === "Deming") {
|
|
515
|
+
const f = demingFit(xs, ys, lambda);
|
|
516
|
+
global = f;
|
|
517
|
+
xmean = ldexp(f.xmean, kx);
|
|
518
|
+
analytic = [f.se0, f.se1];
|
|
519
|
+
}
|
|
520
|
+
else if (methodReg === "WDeming") {
|
|
521
|
+
const f = wdemingFit(xs, ys, lambda, mix, errorRatio, iterMax, threshold, kx, ky);
|
|
522
|
+
if (!f.converged)
|
|
523
|
+
warnings.add(noConvergence);
|
|
524
|
+
global = f;
|
|
525
|
+
xmean = ldexp(f.xmean, kx);
|
|
526
|
+
weights = f.weights;
|
|
527
|
+
}
|
|
528
|
+
else {
|
|
529
|
+
const f = pabaFit(xs, ys, tangent);
|
|
530
|
+
global = f;
|
|
531
|
+
pabaSlopesAll = f.slopes;
|
|
532
|
+
}
|
|
533
|
+
if (!Number.isFinite(global.b1)) {
|
|
534
|
+
throw new RangeError(methodReg === "PaBa" ? "the Passing-Bablok slope is not defined for these data" : "the covariance of x and y is 0: the Deming slope is not defined");
|
|
535
|
+
}
|
|
536
|
+
const alpha = 1 - confLevel;
|
|
537
|
+
// t and normal quantiles of 1 - alpha/2, from the upper tail (rule 10)
|
|
538
|
+
const tq = qt1(alpha / 2, n - 2, false, false);
|
|
539
|
+
const zq = qnorm(alpha / 2, { lowerTail: false });
|
|
540
|
+
const est = [global.b0, global.b1];
|
|
541
|
+
const se = [NaN, NaN];
|
|
542
|
+
const ci = [
|
|
543
|
+
[NaN, NaN],
|
|
544
|
+
[NaN, NaN],
|
|
545
|
+
];
|
|
546
|
+
let jack;
|
|
547
|
+
let jackSe;
|
|
548
|
+
let boot;
|
|
549
|
+
const jackknife = () => {
|
|
550
|
+
const j0 = [];
|
|
551
|
+
const j1 = [];
|
|
552
|
+
for (let i = 0; i < n; i++) {
|
|
553
|
+
const f = fitOf(xs.filter((_, j) => j !== i), ys.filter((_, j) => j !== i));
|
|
554
|
+
j0.push(f.b0);
|
|
555
|
+
j1.push(f.b1);
|
|
556
|
+
}
|
|
557
|
+
jack = [j0, j1];
|
|
558
|
+
// sd of the pseudo-values n θ - (n - 1) θ_(i) is (n - 1) sd(θ_(i)), without the cancellation of the pseudo-values
|
|
559
|
+
jackSe = [((n - 1) * standardDeviation(j0)) / Math.sqrt(n), ((n - 1) * standardDeviation(j1)) / Math.sqrt(n)];
|
|
560
|
+
};
|
|
561
|
+
if (methodCi === "analytical") {
|
|
562
|
+
if (methodReg === "Deming") {
|
|
563
|
+
for (const c of [0, 1]) {
|
|
564
|
+
se[c] = analytic[c];
|
|
565
|
+
ci[c] = [est[c] - tq * se[c], est[c] + tq * se[c]];
|
|
566
|
+
}
|
|
567
|
+
}
|
|
568
|
+
else {
|
|
569
|
+
const iv = pabaInterval(xs, ys, pabaSlopesAll, zq, tangent);
|
|
570
|
+
if (!iv.defined)
|
|
571
|
+
warnings.add("the Passing-Bablok interval is not defined for so few points: its limits are -Inf and Inf");
|
|
572
|
+
ci[0] = iv.intercept;
|
|
573
|
+
ci[1] = iv.slope;
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
else if (methodCi === "jackknife") {
|
|
577
|
+
jackknife();
|
|
578
|
+
for (const c of [0, 1]) {
|
|
579
|
+
se[c] = jackSe[c];
|
|
580
|
+
ci[c] = [est[c] - tq * se[c], est[c] + tq * se[c]];
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
else {
|
|
584
|
+
if (methodBootstrapCi === "BCa") {
|
|
585
|
+
jackknife();
|
|
586
|
+
if (jack.some((v) => v.some(Number.isNaN)))
|
|
587
|
+
throw new RangeError("Too many identical data points!");
|
|
588
|
+
}
|
|
589
|
+
// the standard errors of all the data: Deming's analytical ones, the jackknife's for weighted Deming with BCa
|
|
590
|
+
const globSigma = methodReg === "Deming" ? analytic : methodReg === "WDeming" && jackSe !== undefined ? jackSe : [NaN, NaN];
|
|
591
|
+
const nested = methodCi === "nestedbootstrap";
|
|
592
|
+
const b0 = [];
|
|
593
|
+
const b1 = [];
|
|
594
|
+
const s0 = [];
|
|
595
|
+
const s1 = [];
|
|
596
|
+
let dropped = 0;
|
|
597
|
+
const draw = () => Array.from({ length: n }, () => unifIndex(n));
|
|
598
|
+
const resample = (idx) => {
|
|
599
|
+
const xv = idx.map((i) => xs[i]);
|
|
600
|
+
const yv = idx.map((i) => ys[i]);
|
|
601
|
+
if (constant(xv) || constant(yv)) {
|
|
602
|
+
if (methodReg === "PaBa") {
|
|
603
|
+
warnings.add("Resampling PaBa regression: x or y coordinates of all data points in subsample identical - regression coefficients undetermined!");
|
|
604
|
+
return { b0: NaN, b1: NaN };
|
|
605
|
+
}
|
|
606
|
+
// mcr warns and fits on; the slope is then NaN (a covariance of 0)
|
|
607
|
+
warnings.add("Resampling Deming regression: all x coordinates in subsample identical - regression coefficients undetermined!");
|
|
608
|
+
}
|
|
609
|
+
return fitOf(xv, yv);
|
|
610
|
+
};
|
|
611
|
+
const run = () => {
|
|
612
|
+
for (let b = 0; b < nsamples; b++) {
|
|
613
|
+
const idx = draw();
|
|
614
|
+
const f = resample(idx);
|
|
615
|
+
let sig;
|
|
616
|
+
if (nested) {
|
|
617
|
+
const i0 = [];
|
|
618
|
+
const i1 = [];
|
|
619
|
+
for (let r = 0; r < nnested; r++) {
|
|
620
|
+
const inner = resample(draw().map((i) => idx[i]));
|
|
621
|
+
i0.push(inner.b0);
|
|
622
|
+
i1.push(inner.b1);
|
|
623
|
+
}
|
|
624
|
+
sig = [sdNaRm(i0), sdNaRm(i1)];
|
|
625
|
+
}
|
|
626
|
+
else if (methodReg === "Deming")
|
|
627
|
+
sig = [f.se0, f.se1];
|
|
628
|
+
else
|
|
629
|
+
sig = globSigma;
|
|
630
|
+
if (Number.isNaN(f.b0) || Number.isNaN(f.b1)) {
|
|
631
|
+
dropped++;
|
|
632
|
+
continue;
|
|
633
|
+
}
|
|
634
|
+
b0.push(f.b0);
|
|
635
|
+
b1.push(f.b1);
|
|
636
|
+
s0.push(sig[0]);
|
|
637
|
+
s1.push(sig[1]);
|
|
638
|
+
}
|
|
639
|
+
};
|
|
640
|
+
if (options.rngSeed !== undefined) {
|
|
641
|
+
// R's set.seed(rngSeed, kind = "Mersenne-Twister"), and the previous state restored afterwards if there was one,
|
|
642
|
+
// as mcr (which restores .Random.seed only where it existed: in a session that never drew a random number nor
|
|
643
|
+
// set a kind with RNGkind, the stream of set.seed(rngSeed) continues after the call)
|
|
644
|
+
const saved = isRandomSeeded() ? getRandomSeed() : undefined;
|
|
645
|
+
try {
|
|
646
|
+
RNGkind({ kind: "Mersenne-Twister" });
|
|
647
|
+
setSeed(options.rngSeed);
|
|
648
|
+
run();
|
|
649
|
+
}
|
|
650
|
+
finally {
|
|
651
|
+
if (saved !== undefined)
|
|
652
|
+
setRandomSeed(saved);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
else
|
|
656
|
+
run();
|
|
657
|
+
if (dropped > 0.05 * nsamples)
|
|
658
|
+
throw new RangeError("There were too many resamples with undetermined regression coefficients!");
|
|
659
|
+
const kept = b0.length;
|
|
660
|
+
const boots = [b0, b1];
|
|
661
|
+
const sigmas = [s0, s1];
|
|
662
|
+
for (const c of [0, 1]) {
|
|
663
|
+
const B = boots[c];
|
|
664
|
+
const th = est[c];
|
|
665
|
+
if (methodBootstrapCi === "quantile") {
|
|
666
|
+
ci[c] = [q7(B, alpha / 2), q7(B, 1 - alpha / 2)];
|
|
667
|
+
}
|
|
668
|
+
else if (methodBootstrapCi === "Student") {
|
|
669
|
+
se[c] = standardDeviation(B);
|
|
670
|
+
ci[c] = [th - tq * se[c], th + tq * se[c]];
|
|
671
|
+
}
|
|
672
|
+
else if (methodBootstrapCi === "BCa") {
|
|
673
|
+
let p = B.filter((v) => v < th).length;
|
|
674
|
+
if (B.every((v) => v === th))
|
|
675
|
+
p = kept / 2;
|
|
676
|
+
else if (p === 0)
|
|
677
|
+
p = 0.5;
|
|
678
|
+
else if (p === kept)
|
|
679
|
+
p = kept - 0.5;
|
|
680
|
+
const z0 = qnorm(p / kept);
|
|
681
|
+
const jk = jack[c];
|
|
682
|
+
const jm = jk.reduce((a, v) => a + v, 0) / jk.length;
|
|
683
|
+
let s2 = 0;
|
|
684
|
+
let s3 = 0;
|
|
685
|
+
for (const v of jk) {
|
|
686
|
+
const dv = jm - v;
|
|
687
|
+
s2 += dv * dv;
|
|
688
|
+
s3 += dv * dv * dv;
|
|
689
|
+
}
|
|
690
|
+
const acc = s2 === 0 ? 0 : s3 / (6 * s2 ** 1.5);
|
|
691
|
+
const zL = -zq;
|
|
692
|
+
const zU = zq;
|
|
693
|
+
const iu = pnorm(z0 - (zL - z0) / (1 + acc * (zL - z0)));
|
|
694
|
+
const il = pnorm(z0 - (zU - z0) / (1 + acc * (zU - z0)));
|
|
695
|
+
ci[c] = [q7(B, il), q7(B, iu)];
|
|
696
|
+
}
|
|
697
|
+
else {
|
|
698
|
+
// bootstrap-t
|
|
699
|
+
const t = B.map((v, i) => (v - th) / sigmas[c][i]);
|
|
700
|
+
const sHat = Number.isNaN(globSigma[c]) ? standardDeviation(B) : globSigma[c];
|
|
701
|
+
se[c] = sHat;
|
|
702
|
+
ci[c] = [th - q7(t, 1 - alpha / 2) * sHat, th - q7(t, alpha / 2) * sHat];
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
boot = {
|
|
706
|
+
intercept: b0.map((v) => ldexp(v, ky)),
|
|
707
|
+
slope: b1.map((v) => ldexp(v, ky - kx)),
|
|
708
|
+
sigmaIntercept: s0.map((v) => ldexp(v, ky)),
|
|
709
|
+
sigmaSlope: s1.map((v) => ldexp(v, ky - kx)),
|
|
710
|
+
globalSigma: [ldexp(globSigma[0], ky), ldexp(globSigma[1], ky - kx)],
|
|
711
|
+
nsamples: kept,
|
|
712
|
+
};
|
|
713
|
+
}
|
|
714
|
+
const coef = (c) => {
|
|
715
|
+
const back = (v) => ldexp(v, c === 0 ? ky : ky - kx);
|
|
716
|
+
return { estimate: back(est[c]), se: back(se[c]), confInt: [back(ci[c][0]), back(ci[c][1])] };
|
|
717
|
+
};
|
|
718
|
+
const result = {
|
|
719
|
+
methodReg,
|
|
720
|
+
methodCi,
|
|
721
|
+
...(bootstrap ? { methodBootstrapCi } : {}),
|
|
722
|
+
confLevel,
|
|
723
|
+
errorRatio,
|
|
724
|
+
n,
|
|
725
|
+
intercept: coef(0),
|
|
726
|
+
slope: coef(1),
|
|
727
|
+
xmean,
|
|
728
|
+
...(weights === undefined ? {} : { weights }),
|
|
729
|
+
...(jack === undefined ? {} : { jackknife: { intercept: jack[0].map((v) => ldexp(v, ky)), slope: jack[1].map((v) => ldexp(v, ky - kx)) } }),
|
|
730
|
+
...(boot === undefined ? {} : { bootstrap: boot }),
|
|
731
|
+
...(methodReg === "PaBa" ? { cusum: cusumOf(xs, ys, global.b0, global.b1) } : {}),
|
|
732
|
+
warnings: [...warnings],
|
|
733
|
+
};
|
|
734
|
+
return reported("mcreg", result);
|
|
735
|
+
}
|