@numero-uno-jpn/rstats 0.8.0 → 0.10.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 +88 -0
- package/README.ja.md +89 -13
- package/README.md +90 -13
- package/THIRD_PARTY_NOTICES.md +12 -2
- package/dist/chunks/{chunk-OHPHNE3O.js → chunk-2XKG3DX4.js} +1 -1
- package/dist/chunks/{chunk-3I6EKGB6.js → chunk-4NM37MGA.js} +2 -2
- package/dist/chunks/chunk-7HPVUVZB.js +2 -0
- package/dist/chunks/{chunk-I3LAZE6C.js → chunk-AECGWZHD.js} +2 -2
- package/dist/chunks/chunk-ENL43FNO.js +2 -0
- package/dist/chunks/chunk-EWC6I75B.js +2 -0
- package/dist/chunks/chunk-IT354SHV.js +3 -0
- package/dist/chunks/{chunk-VIPSPG3Y.js → chunk-LIMZKONM.js} +2 -2
- package/dist/chunks/chunk-O6PT7IVU.js +2 -0
- package/dist/chunks/{chunk-YGWPU67I.js → chunk-QFULZNHL.js} +1 -1
- package/dist/chunks/{chunk-XU4BGFZ6.js → chunk-QJJWGNJP.js} +2 -2
- package/dist/chunks/{chunk-32PRRONF.js → chunk-QULPY6YM.js} +1 -1
- package/dist/chunks/chunk-XWTZ4RTR.js +2 -0
- package/dist/chunks/chunk-ZRIM4R4A.js +2 -0
- package/dist/descriptive/factanal.d.ts +56 -0
- package/dist/descriptive/factanal.js +186 -0
- package/dist/descriptive/omega.d.ts +56 -0
- package/dist/descriptive/omega.js +323 -0
- package/dist/descriptive.js +2 -2
- package/dist/distributions/bvnorm.d.ts +15 -0
- package/dist/distributions/bvnorm.js +131 -0
- package/dist/distributions/nbeta.js +34 -1
- package/dist/distributions/nchisq.d.ts +10 -0
- package/dist/distributions/nchisq.js +46 -0
- package/dist/distributions.js +2 -2
- package/dist/entries/distributions.d.ts +1 -0
- package/dist/entries/distributions.js +1 -0
- package/dist/entries/linalg.d.ts +2 -0
- package/dist/entries/linalg.js +2 -0
- package/dist/entries/numerics.d.ts +2 -0
- package/dist/entries/numerics.js +1 -0
- package/dist/entries/tests.d.ts +25 -1
- package/dist/entries/tests.js +22 -1
- package/dist/htest/agreement.d.ts +141 -0
- package/dist/htest/agreement.js +274 -0
- package/dist/htest/aov.d.ts +19 -0
- package/dist/htest/aov.js +22 -15
- package/dist/htest/core/simulate.d.ts +2 -0
- package/dist/htest/core/simulate.js +1 -1
- package/dist/htest/dunnett.d.ts +5 -0
- package/dist/htest/dunnett.js +89 -0
- package/dist/htest/effectSize.d.ts +112 -0
- package/dist/htest/effectSize.js +385 -0
- package/dist/htest/leveneTest.d.ts +30 -0
- package/dist/htest/leveneTest.js +41 -0
- package/dist/htest/multipleComparisons.d.ts +147 -0
- package/dist/htest/multipleComparisons.js +369 -0
- package/dist/htest/normalityTests.d.ts +44 -0
- package/dist/htest/normalityTests.js +164 -0
- package/dist/htest/polycor.d.ts +117 -0
- package/dist/htest/polycor.js +468 -0
- package/dist/htest/power.d.ts +132 -0
- package/dist/htest/power.js +227 -0
- package/dist/htest/pwr.d.ts +263 -0
- package/dist/htest/pwr.js +440 -0
- package/dist/htest/rankTests.d.ts +7 -0
- package/dist/htest/rankTests.js +11 -1
- package/dist/htest/trendTests.d.ts +57 -0
- package/dist/htest/trendTests.js +167 -0
- package/dist/linalg/eigen.d.ts +8 -0
- package/dist/linalg/eigen.js +5 -4
- package/dist/linalg/expm.d.ts +48 -0
- package/dist/linalg/expm.js +472 -0
- package/dist/linalg/schur.d.ts +48 -0
- package/dist/linalg/schur.js +225 -0
- package/dist/linalg.js +2 -2
- package/dist/models/anovaSequential.d.ts +58 -0
- package/dist/models/anovaSequential.js +138 -0
- package/dist/models/aovEz.d.ts +64 -0
- package/dist/models/aovEz.js +332 -0
- package/dist/models/aovStrata.d.ts +32 -0
- package/dist/models/aovStrata.js +104 -0
- package/dist/models/carAnova.d.ts +30 -0
- package/dist/models/carAnova.js +121 -0
- package/dist/models/coxph.d.ts +101 -0
- package/dist/models/coxph.js +502 -0
- package/dist/models/ddLeastSquares.d.ts +30 -0
- package/dist/models/ddLeastSquares.js +90 -0
- package/dist/models/ddMatrix.d.ts +10 -0
- package/dist/models/ddMatrix.js +91 -0
- package/dist/models/formula.d.ts +83 -0
- package/dist/models/formula.js +333 -0
- package/dist/models/glm.d.ts +226 -0
- package/dist/models/glm.js +546 -0
- package/dist/models/glmAnova.d.ts +31 -0
- package/dist/models/glmAnova.js +146 -0
- package/dist/models/glmConfint.d.ts +25 -0
- package/dist/models/glmConfint.js +139 -0
- package/dist/models/glmFamily.d.ts +66 -0
- package/dist/models/glmFamily.js +359 -0
- package/dist/models/lm.d.ts +84 -3
- package/dist/models/lm.js +141 -44
- package/dist/models/mauchly.d.ts +48 -0
- package/dist/models/mauchly.js +123 -0
- package/dist/models/modelFrame.d.ts +40 -0
- package/dist/models/modelFrame.js +131 -0
- package/dist/models/modelMatrix.d.ts +88 -0
- package/dist/models/modelMatrix.js +170 -0
- package/dist/models/survival.d.ts +87 -0
- package/dist/models/survival.js +238 -0
- package/dist/numerics.js +2 -2
- package/dist/optim/lbfgsb.d.ts +20 -0
- package/dist/optim/lbfgsb.js +1240 -0
- package/dist/optim/optim.d.ts +85 -0
- package/dist/optim/optim.js +610 -0
- package/dist/rstats.js +19 -3
- package/dist/special.js +2 -2
- package/dist/tests.js +18 -3
- package/llms.txt +102 -0
- package/package.json +3 -2
- package/dist/chunks/chunk-EJRCDJ76.js +0 -2
- package/dist/chunks/chunk-JERGQKZM.js +0 -2
- package/dist/chunks/chunk-JVYV4633.js +0 -2
- package/dist/chunks/chunk-LXMMKO26.js +0 -2
- package/dist/chunks/chunk-MJQLKEO5.js +0 -2
- package/dist/chunks/chunk-RZ7SBJEG.js +0 -2
- package/dist/chunks/chunk-SPQC445Q.js +0 -2
- package/dist/chunks/chunk-U633VFH3.js +0 -2
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
// McDonald's omega, psych's omega() with its defaults (minres factoring, varimax then oblimin, a Schmid-Leiman
|
|
2
|
+
// transformation, items with a negative general loading flipped). Written for rStats.js from the specification
|
|
3
|
+
// oracle/omega-behaviour.md (no R, psych or GPArotation code was read or used): the minres uniquenesses minimise
|
|
4
|
+
// the off-diagonal residuals by L-BFGS-B (this library's optim), the oblique rotation is GPArotation's quartimin
|
|
5
|
+
// with its Barzilai-Borwein step and non-monotone line search, and the general factor comes from a one-factor
|
|
6
|
+
// minres analysis of the factor correlations.
|
|
7
|
+
import { eigen } from "../linalg/eigen.js";
|
|
8
|
+
import { solve } from "../linalg/solve.js";
|
|
9
|
+
import { svd } from "../linalg/svd.js";
|
|
10
|
+
import { optim } from "../optim/optim.js";
|
|
11
|
+
import { cor } from "./cov.js";
|
|
12
|
+
import { sumOnce, varimax } from "./factanal.js";
|
|
13
|
+
const EPS = 2 ** -52;
|
|
14
|
+
const TWO_FACTOR_MESSAGE = "\nThree factors are required for identification -- general factor loadings set to be equal. \nProceed with caution. \nThink about redoing the analysis with alternative values of the 'option' setting.\n\n";
|
|
15
|
+
const matMul = (A, B) => A.map((row) => B[0].map((_, j) => {
|
|
16
|
+
let s = 0;
|
|
17
|
+
for (let k = 0; k < row.length; k++)
|
|
18
|
+
s += row[k] * B[k][j];
|
|
19
|
+
return s;
|
|
20
|
+
}));
|
|
21
|
+
const transpose = (A) => A[0].map((_, j) => A.map((r) => r[j]));
|
|
22
|
+
const colSums = (m, f = (v) => v) => m[0].map((_, j) => sumOnce(m.map((r) => f(r[j]))));
|
|
23
|
+
const rowSums = (m, f = (v) => v) => m.map((r) => sumOnce(r.map(f)));
|
|
24
|
+
/** Sum of all entries (column by column, as R) */
|
|
25
|
+
const sumAll = (m, f = (v) => v) => sumOnce(m[0].flatMap((_, j) => m.map((r) => f(r[j]))));
|
|
26
|
+
const signOf = (v) => (v < 0 ? -1 : 1);
|
|
27
|
+
/** r_ij / sqrt(r_ii r_jj) with unit diagonal */
|
|
28
|
+
function toCorrelation(S) {
|
|
29
|
+
const sd = S.map((r, i) => Math.sqrt(r[i]));
|
|
30
|
+
return S.map((r, i) => r.map((v, j) => (i === j ? 1 : v / (sd[i] * sd[j]))));
|
|
31
|
+
}
|
|
32
|
+
/** Squared multiple correlations from the pseudo-inverse, clipped to [0, 1] (messages as psych's smc) */
|
|
33
|
+
function smc(S, messages) {
|
|
34
|
+
const R = toCorrelation(S);
|
|
35
|
+
const { d, u, v } = svd(R);
|
|
36
|
+
const kept = d.map((_, k) => k).filter((k) => d[k] > Math.sqrt(EPS) * d[0]);
|
|
37
|
+
const out = R.map((_, i) => {
|
|
38
|
+
let s = 0;
|
|
39
|
+
for (const k of kept)
|
|
40
|
+
s += v[i][k] * (1 / d[k]) * u[i][k];
|
|
41
|
+
return 1 - 1 / s;
|
|
42
|
+
});
|
|
43
|
+
if (out.some((x) => x > 1))
|
|
44
|
+
addMessage(messages, "In smc, smcs > 1 were set to 1.0");
|
|
45
|
+
if (out.some((x) => x < 0))
|
|
46
|
+
addMessage(messages, "In smc, smcs < 0 were set to .0");
|
|
47
|
+
return out.map((x) => (x > 1 ? 1 : x < 0 ? 0 : x));
|
|
48
|
+
}
|
|
49
|
+
const addMessage = (list, m) => {
|
|
50
|
+
if (!list.includes(m))
|
|
51
|
+
list.push(m);
|
|
52
|
+
};
|
|
53
|
+
/** The first q eigenvectors of S with diagonal `diag`, times the square roots of their eigenvalues (clipped by `clip`) */
|
|
54
|
+
function principalLoadings(S, diag, q, clip) {
|
|
55
|
+
const M = S.map((r, i) => r.map((v, j) => (i === j ? diag[i] : v)));
|
|
56
|
+
const E = eigen(M, { symmetric: true });
|
|
57
|
+
const w = E.values.slice(0, q).map((e) => Math.sqrt(clip(e)));
|
|
58
|
+
return E.vectors.map((row) => row.slice(0, q).map((v, k) => v * w[k]));
|
|
59
|
+
}
|
|
60
|
+
const outer = (L) => matMul(L, transpose(L));
|
|
61
|
+
/** Minres factor analysis of a correlation matrix with q factors (varimax for q > 1) */
|
|
62
|
+
function minres(S0, q, warnings, messages) {
|
|
63
|
+
const S = toCorrelation(S0);
|
|
64
|
+
const p = S.length;
|
|
65
|
+
const s = smc(S, messages);
|
|
66
|
+
const objective = (psi) => {
|
|
67
|
+
const L = principalLoadings(S, psi.map((v) => 1 - v), q, (e) => (e < EPS ? 100 * EPS : e));
|
|
68
|
+
const model = outer(L);
|
|
69
|
+
const terms = [];
|
|
70
|
+
for (let j = 0; j < p; j++)
|
|
71
|
+
for (let i = j + 1; i < p; i++)
|
|
72
|
+
terms.push((S[i][j] - model[i][j]) ** 2);
|
|
73
|
+
return sumOnce(terms);
|
|
74
|
+
};
|
|
75
|
+
const gradient = (psi) => {
|
|
76
|
+
const L = principalLoadings(S, psi.map((v, i) => S[i][i] - v), q, (e) => Math.max(e, 0));
|
|
77
|
+
return psi.map((v, i) => {
|
|
78
|
+
let h = 0;
|
|
79
|
+
for (let k = 0; k < q; k++)
|
|
80
|
+
h += L[i][k] * L[i][k];
|
|
81
|
+
return h + v - S[i][i];
|
|
82
|
+
});
|
|
83
|
+
};
|
|
84
|
+
const fit = optim(s.map((v) => 1 - v), objective, {
|
|
85
|
+
gr: gradient,
|
|
86
|
+
method: "L-BFGS-B",
|
|
87
|
+
lower: 0.005,
|
|
88
|
+
upper: Math.max(Math.max(...s), 1),
|
|
89
|
+
control: { fnscale: 1, parscale: new Array(p).fill(0.01) },
|
|
90
|
+
});
|
|
91
|
+
const psi = fit.par;
|
|
92
|
+
let L = principalLoadings(S, psi.map((v, i) => S[i][i] - v), q, (e) => Math.max(e, 0));
|
|
93
|
+
L = signColumns(L, q);
|
|
94
|
+
L = L.map((r) => r.map((v) => (v === 0 ? 1e-15 : v)));
|
|
95
|
+
if (rowSums(L, (v) => v * v).some((h) => h > 1)) {
|
|
96
|
+
addMessage(warnings, "An ultra-Heywood case was detected. Examine the results carefully");
|
|
97
|
+
}
|
|
98
|
+
if (q > 1) {
|
|
99
|
+
L = signColumns(varimax(L).loadings, q);
|
|
100
|
+
const ssq = colSums(L, (v) => v * v);
|
|
101
|
+
const order = ssq.map((_, j) => j).sort((a, b) => ssq[b] - ssq[a] || a - b);
|
|
102
|
+
L = L.map((r) => order.map((j) => r[j]));
|
|
103
|
+
}
|
|
104
|
+
else {
|
|
105
|
+
L = signColumns(L, q);
|
|
106
|
+
}
|
|
107
|
+
return L;
|
|
108
|
+
}
|
|
109
|
+
/** q > 1: each column times the sign of its sum; q = 1: negated if its sum is negative */
|
|
110
|
+
function signColumns(L, q) {
|
|
111
|
+
const sign = colSums(L).map(signOf);
|
|
112
|
+
if (q === 1)
|
|
113
|
+
return sign[0] < 0 ? L.map((r) => r.map((v) => -v)) : L;
|
|
114
|
+
return L.map((r) => r.map((v, j) => sign[j] * v));
|
|
115
|
+
}
|
|
116
|
+
/** Quartimin criterion and gradient at loadings L */
|
|
117
|
+
function quartimin(L) {
|
|
118
|
+
const q = L[0].length;
|
|
119
|
+
const L2 = L.map((r) => r.map((v) => v * v));
|
|
120
|
+
const X = L2.map((r) => r.map((_, j) => {
|
|
121
|
+
let s = 0;
|
|
122
|
+
for (let m = 0; m < q; m++)
|
|
123
|
+
if (m !== j)
|
|
124
|
+
s += r[m];
|
|
125
|
+
return s;
|
|
126
|
+
}));
|
|
127
|
+
return { f: sumAll(L2.map((r, i) => r.map((v, j) => v * X[i][j]))) / 4, Gq: L.map((r, i) => r.map((v, j) => v * X[i][j])) };
|
|
128
|
+
}
|
|
129
|
+
/** Oblique quartimin (oblimin) rotation of A by gradient projection: the pattern and the factor correlations */
|
|
130
|
+
function oblimin(A) {
|
|
131
|
+
const q = A[0].length;
|
|
132
|
+
const at = (T) => {
|
|
133
|
+
const Ti = solve(T);
|
|
134
|
+
const L = matMul(A, transpose(Ti));
|
|
135
|
+
const { f, Gq } = quartimin(L);
|
|
136
|
+
const G = transpose(matMul(matMul(transpose(L), Gq), Ti)).map((r) => r.map((v) => -v));
|
|
137
|
+
return { L, f, G };
|
|
138
|
+
};
|
|
139
|
+
let T = Array.from({ length: q }, (_, i) => Array.from({ length: q }, (_, j) => (i === j ? 1 : 0)));
|
|
140
|
+
let alpha = 1;
|
|
141
|
+
let cur = at(T);
|
|
142
|
+
let previous;
|
|
143
|
+
const values = [];
|
|
144
|
+
let converged = false;
|
|
145
|
+
for (let iter = 0; iter <= 2000; iter++) {
|
|
146
|
+
const d = colSums(T.map((r, i) => r.map((v, j) => v * cur.G[i][j])));
|
|
147
|
+
const Gp = cur.G.map((r, i) => r.map((v, j) => v - T[i][j] * d[j]));
|
|
148
|
+
const s = Math.sqrt(sumAll(Gp, (v) => v * v));
|
|
149
|
+
values.push(cur.f);
|
|
150
|
+
if (s < 1e-5) {
|
|
151
|
+
converged = true;
|
|
152
|
+
break;
|
|
153
|
+
}
|
|
154
|
+
if (previous !== undefined) {
|
|
155
|
+
const P = previous;
|
|
156
|
+
const dT = T.map((r, i) => r.map((v, j) => v - P.T[i][j]));
|
|
157
|
+
const dG = Gp.map((r, i) => r.map((v, j) => v - P.Gp[i][j]));
|
|
158
|
+
if (sumAll(dG, (v) => v * v) > 0) {
|
|
159
|
+
alpha = sumAll(dT, (v) => v * v) / Math.abs(sumAll(dT.map((r, i) => r.map((v, j) => v * dG[i][j]))));
|
|
160
|
+
alpha = Math.max(1e-10, Math.min(alpha, 20));
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
else {
|
|
164
|
+
alpha = 2 * alpha;
|
|
165
|
+
}
|
|
166
|
+
const target = Math.max(...values.slice(-10));
|
|
167
|
+
let trial = cur;
|
|
168
|
+
let Tt = T;
|
|
169
|
+
for (let i = 0; i <= 10; i++) {
|
|
170
|
+
const X = T.map((r, a) => r.map((v, b) => v - alpha * Gp[a][b]));
|
|
171
|
+
const len = colSums(X, (v) => v * v).map((v) => 1 / Math.sqrt(v));
|
|
172
|
+
Tt = X.map((r) => r.map((v, j) => v * len[j]));
|
|
173
|
+
trial = at(Tt);
|
|
174
|
+
if (target - trial.f > 0.5 * s * s * alpha)
|
|
175
|
+
break;
|
|
176
|
+
alpha = alpha / 2;
|
|
177
|
+
}
|
|
178
|
+
previous = { T, Gp };
|
|
179
|
+
T = Tt;
|
|
180
|
+
cur = trial;
|
|
181
|
+
}
|
|
182
|
+
return { loadings: cur.L, phi: matMul(transpose(T), T), converged };
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* McDonald's omega (hierarchical, asymptotic and total) from a Schmid-Leiman transformation of an oblique minres
|
|
186
|
+
* factor solution. Equivalent to R's `psych::omega(x, nfactors)` with its defaults (`fm = "minres"`, `rotate =
|
|
187
|
+
* "oblimin"`, `option = "equal"`, `flip = TRUE`).
|
|
188
|
+
*
|
|
189
|
+
* @param x The data matrix (array of rows, NaN for missing values: correlations of pairwise complete observations),
|
|
190
|
+
* or `null` with `options.covmat`.
|
|
191
|
+
* @param options See {@link OmegaOptions}.
|
|
192
|
+
*
|
|
193
|
+
* @example
|
|
194
|
+
* ```ts
|
|
195
|
+
* const om = omega(x); // x: an n x 12 data matrix
|
|
196
|
+
* om.omegaH; om.omegaTot; om.sl;
|
|
197
|
+
* ```
|
|
198
|
+
*/
|
|
199
|
+
export function omega(x, options = {}) {
|
|
200
|
+
const q = options.nfactors ?? 3;
|
|
201
|
+
if (!Number.isInteger(q) || q < 1)
|
|
202
|
+
throw new RangeError("'nfactors' must be a positive integer");
|
|
203
|
+
let R;
|
|
204
|
+
if (options.covmat !== undefined) {
|
|
205
|
+
R = toCorrelation(options.covmat);
|
|
206
|
+
}
|
|
207
|
+
else {
|
|
208
|
+
if (x === null)
|
|
209
|
+
throw new TypeError("neither 'x' nor 'covmat' supplied");
|
|
210
|
+
R = cor(x, undefined, { use: "pairwise.complete.obs" });
|
|
211
|
+
}
|
|
212
|
+
const p = R.length;
|
|
213
|
+
const warnings = [];
|
|
214
|
+
const messages = [];
|
|
215
|
+
const orthog = minres(R, q, warnings, messages);
|
|
216
|
+
let oblique;
|
|
217
|
+
let phi;
|
|
218
|
+
let gloading;
|
|
219
|
+
if (q === 1) {
|
|
220
|
+
oblique = orthog.map((r) => r.slice());
|
|
221
|
+
gloading = [1];
|
|
222
|
+
addMessage(messages, "Omega_h for 1 factor is not meaningful, just omega_t\n");
|
|
223
|
+
addMessage(warnings, "Omega_h and Omega_asymptotic are not meaningful with one factor");
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
const rot = oblimin(orthog);
|
|
227
|
+
if (!rot.converged)
|
|
228
|
+
addMessage(warnings, "oblimin did not converge in 2000 iterations");
|
|
229
|
+
oblique = rot.loadings;
|
|
230
|
+
phi = rot.phi;
|
|
231
|
+
if (q === 2) {
|
|
232
|
+
const r12 = phi[0][1];
|
|
233
|
+
const a = Math.sqrt(Math.abs(r12));
|
|
234
|
+
gloading = [a, signOf(r12) * a];
|
|
235
|
+
addMessage(messages, TWO_FACTOR_MESSAGE);
|
|
236
|
+
}
|
|
237
|
+
else {
|
|
238
|
+
gloading = minres(phi, 1, warnings, messages).map((r) => r[0]);
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
// Schmid-Leiman
|
|
242
|
+
const g = oblique.map((r) => {
|
|
243
|
+
let s = 0;
|
|
244
|
+
for (let k = 0; k < q; k++)
|
|
245
|
+
s += r[k] * gloading[k];
|
|
246
|
+
return s;
|
|
247
|
+
});
|
|
248
|
+
const h2 = rowSums(orthog, (v) => v * v);
|
|
249
|
+
const u2 = h2.map((h, i) => R[i][i] - h);
|
|
250
|
+
const groupLoadings = oblique.map((r, i) => r.map((v, k) => {
|
|
251
|
+
// one factor (gloading 1): v is 0 exactly, the formula would leave only a rounding residue
|
|
252
|
+
if (q === 1)
|
|
253
|
+
return 0;
|
|
254
|
+
const Rii = R[i][i];
|
|
255
|
+
let w = Rii - (Rii - v * v) - (v * gloading[k]) ** 2;
|
|
256
|
+
if (w < 0)
|
|
257
|
+
w = 0;
|
|
258
|
+
return signOf(v) * Math.sqrt(w);
|
|
259
|
+
}));
|
|
260
|
+
const p2 = g.map((v, i) => (v * v) / h2[i]);
|
|
261
|
+
const com = g.map((v, i) => {
|
|
262
|
+
const F = [v, ...groupLoadings[i]];
|
|
263
|
+
return sumOnce(F.map((f) => f * f)) ** 2 / sumOnce(F.map((f) => f ** 4));
|
|
264
|
+
});
|
|
265
|
+
// flip
|
|
266
|
+
const key = g.map(signOf);
|
|
267
|
+
if (key.some((k) => k < 0))
|
|
268
|
+
R = R.map((r, i) => r.map((v, j) => key[i] * v * key[j]));
|
|
269
|
+
const gs = g.map((v, i) => key[i] * v);
|
|
270
|
+
const Fs = groupLoadings.map((r, i) => r.map((v) => key[i] * v));
|
|
271
|
+
const sl = gs.map((v, i) => [v, ...Fs[i], h2[i], u2[i], p2[i], com[i]]);
|
|
272
|
+
// statistics
|
|
273
|
+
const Vt = sumAll(R);
|
|
274
|
+
const Vitem = sumOnce(R.map((r, i) => r[i]));
|
|
275
|
+
const gsq = sumOnce(gs) ** 2;
|
|
276
|
+
const U = sumOnce(u2);
|
|
277
|
+
const omegaH = gsq / Vt;
|
|
278
|
+
const omegaTot = (Vt - U) / Vt;
|
|
279
|
+
const omegaLim = gsq / (Vt - U);
|
|
280
|
+
const alpha = (((Vt - Vitem) / Vt) * p) / (p - 1);
|
|
281
|
+
const G6 = (Vt + sumOnce(smc(R, messages)) - Vitem) / Vt;
|
|
282
|
+
const ev = colSums(sl.map((r) => r.slice(0, q + 1)), (v) => v * v);
|
|
283
|
+
const ECV = ev[0] / sumOnce(ev);
|
|
284
|
+
// omega of each group
|
|
285
|
+
const group = Fs.map((r) => {
|
|
286
|
+
let best = 0;
|
|
287
|
+
for (let k = 1; k < q; k++)
|
|
288
|
+
if (Math.abs(r[k]) > Math.abs(r[best]))
|
|
289
|
+
best = k;
|
|
290
|
+
return best;
|
|
291
|
+
});
|
|
292
|
+
const groupRows = [];
|
|
293
|
+
const aSquares = [];
|
|
294
|
+
for (let k = 0; k < q; k++) {
|
|
295
|
+
const items = group.map((_, i) => i).filter((i) => group[i] === k);
|
|
296
|
+
const V = sumOnce(items.flatMap((j) => items.map((i) => R[i][j])));
|
|
297
|
+
const a = sumOnce(items.map((i) => Fs[i][k]));
|
|
298
|
+
const b = sumOnce(items.map((i) => gs[i]));
|
|
299
|
+
aSquares.push(a * a);
|
|
300
|
+
groupRows.push([(a * a + b * b) / V, (b * b) / V, (a * a) / V]);
|
|
301
|
+
}
|
|
302
|
+
const omegaGroup = [[omegaTot, sumOnce(gs) ** 2 / Vt, sumOnce(aSquares) / Vt], ...groupRows];
|
|
303
|
+
const out = {
|
|
304
|
+
omegaH,
|
|
305
|
+
omegaLim,
|
|
306
|
+
alpha,
|
|
307
|
+
omegaTot,
|
|
308
|
+
G6,
|
|
309
|
+
ECV,
|
|
310
|
+
sl,
|
|
311
|
+
slNames: ["g", ...Array.from({ length: q }, (_, k) => `F${k + 1}*`), "h2", "u2", "p2", "com"],
|
|
312
|
+
orthog,
|
|
313
|
+
oblique,
|
|
314
|
+
gloading,
|
|
315
|
+
key,
|
|
316
|
+
omegaGroup,
|
|
317
|
+
warnings,
|
|
318
|
+
messages,
|
|
319
|
+
};
|
|
320
|
+
if (phi !== undefined)
|
|
321
|
+
out.phi = phi;
|
|
322
|
+
return out;
|
|
323
|
+
}
|
package/dist/descriptive.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
/*! rStats.js 0.
|
|
2
|
-
import{
|
|
1
|
+
/*! rStats.js 0.10.0 | MIT License | includes code ported from SciPy, Boost.Math, statsmodels, LAPACK and others: see THIRD_PARTY_NOTICES.md at https://github.com/numero-uno-jpn/rStats.js */
|
|
2
|
+
import{f as C,g as Q,h as j}from"./chunks/chunk-XWTZ4RTR.js";import"./chunks/chunk-ZRIM4R4A.js";import{a as U,b as z,c as D,d as T,e as V,f as X,g as L,h as k,i as R,j as Z,k as G,l as H,m as J,n as K,o as W,p as Y,q as $,r as v,s as tt,t as et,u as nt}from"./chunks/chunk-AECGWZHD.js";import{a as _,b as rt,c as ot,d as st,e as it,f as at}from"./chunks/chunk-QFULZNHL.js";import"./chunks/chunk-7HPVUVZB.js";import"./chunks/chunk-LIMZKONM.js";import"./chunks/chunk-4NM37MGA.js";import"./chunks/chunk-2XKG3DX4.js";var q=4*Number.EPSILON,ct={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function lt(i,e,s){let r=i.length,c=n=>i[Math.min(Math.max(n,1),r)-1];if(s===7){let n=1+(r-1)*e,h=Math.floor(n),f=c(h),w=c(Math.ceil(n));if(n>h&&w!==f){let M=n-h;return(1-M)*f+M*w}return f}let a,t;if(s<=3){let n=s===3?r*e-.5:r*e;a=Math.floor(n*(1+q)),s===1?t=n>a?1:0:s===2?t=n>a?1:.5:t=n!==a||Math.abs(a%2)===1?1:0}else{let[n,h]=ct[s],f=n+e*(r+1-n-h);a=Math.floor(f*(1+q)),t=f-a,Math.abs(t)<q&&(t=0)}let o=c(a),l=c(a+1);return t===1?l:t>0&&t<1&&o!==l?(1-t)*o+t*l:o}function F(i,e=[0,.25,.5,.75,1],s={}){let r=s.type??7;if(!(Number.isInteger(r)&&r>=1&&r<=9))throw new RangeError("'type' must be an integer in 1..9");let c=U(i,s.naRm);if(c===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let a=c.sort((n,h)=>n-h),t=typeof e=="number"?[e]:Array.from(e),o=100*Number.EPSILON;if(t.some(n=>n<-o||n>1+o))throw new RangeError("'probs' outside [0,1]");let l=t.map(n=>Number.isNaN(n)||a.length===0?NaN:lt(a,Math.min(Math.max(n,0),1),r));return typeof e=="number"?l[0]:l}function O(i,e={}){let[s,r]=F(i,[.25,.75],e);return r-s}function ft(i){let e=Array.from(i).filter(a=>!Number.isNaN(a)).sort((a,t)=>a-t),s=e.length;if(s===0)return[NaN,NaN,NaN,NaN,NaN];let r=Math.floor((s+3)/2)/2;return[1,r,(s+1)/2,s+1-r,s].map(a=>.5*(e[Math.floor(a)-1]+e[Math.ceil(a)-1]))}function ut(i,e={}){let s=U(i,e.naRm);if(s===void 0)return NaN;let r=e.center??k(s),c=e.constant??1.4826,a=e.low??!1,t=e.high??!1,o=s.map(n=>Math.abs(n-r)),l=o.length;if((a||t)&&l%2===0){if(a&&t)throw new RangeError("'low' and 'high' cannot be both TRUE");let n=l/2+(t?1:0),h=o.sort((f,w)=>f-w);return c*h[n-1]}return c*k(o)}function P(i,e={}){let s=Array.from(i).filter(Number.isFinite);if(s.length===0)return[];let r=e.n??5,c=e.minN??Math.floor(r/3),a=e.shrinkSml??.75,t=e.highUBias??1.5,o=e.u5Bias??.5+1.5*t,l=1/0,n=-1/0;for(let N of s)N<l&&(l=N),N>n&&(n=N);let h=n-l,f,w;if(h===0&&n===0)f=1,w=!0;else{f=Math.max(Math.abs(l),Math.abs(n));let p=(1+(o>=1.5*t+.5?1/(1+t):1.5/(1+o)))*Math.max(1,r)*Number.EPSILON;w=h<f*p*3}w?(f>10&&(f=9+f/10),f*=a,c>1&&(f/=c)):(f=r>1?h/r:h,h===1/0&&r>=2&&(f=n/r-l/r));let M=2**-20*mt;f<M?f=M:f>Number.MAX_VALUE/1.25&&(f=Number.MAX_VALUE/1.25);let x=10**Math.floor(Math.log10(f)),S=[[2*x,t],[5*x,o],[10*x,t]],g=x;for(let[N,p]of S)if(N-f<p*(f-g))g=N;else break;let m=1e-10,u=Math.floor(l/g+m);for(;u*g>l+m*g;)u--;for(;!Number.isFinite(u*g);)u++;let b=Math.ceil(n/g-m);for(;b*g<n-m*g;)b++;for(;!Number.isFinite(b*g);)b--;let d=Math.trunc(.5+b-u);if(d<c){let N=c-d,p=Math.floor(N/2),I=N%2;l===0&&u===0&&n!==0?b+=N:n===0&&b===0&&l!==0?u-=N:u>=0?(b+=p,u-=p+I):(u-=p,b+=p+I),d=c}let y=u*g<l?u*g:l,E=b*g>n?b*g:n;if(d<=0)return[y];let A;if(Number.isFinite(E-y))A=_(y,E,d+1);else{let N=E/d-y/d;A=Array.from({length:d+1},(p,I)=>y+I*N),A[d]=E}let B=E/d-y/d;return A.map(N=>Math.abs(N)<1e-14*B?0:N)}var mt=22250738585072014e-324;function ht(i){return i===0||!Number.isFinite(i)?i:Number(i.toPrecision(5))}function Nt(i,e){let s=i.length,[r,c]=R(i),a=c-r;switch(e.toLowerCase()){case"sturges":return Math.ceil(Math.log2(s)+1);case"scott":{let t=3.5*L(i)*s**-.3333333333333333;return t>0?Math.max(1,Math.ceil(a/t)):1}case"fd":case"freedman-diaconis":{let t=i.map(ht),o=2*O(t);for(let l=1/8;o===0&&l>=1/512;l/=2){let[n,h]=F(t,[l,1-l]);o=(h-n)/(1-2*l)}return o===0&&(o=3.5*L(i)),o>0?Math.ceil(a/o*s**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function gt(i,e){let s=i.slice(1).map((r,c)=>r-i[c]);return i.length>5?k(s):i.length<=3?e:Math.min(...s.filter(r=>r>0))}function dt(i,e={}){let s=Array.from(i).filter(Number.isFinite),r=s.length,c=e.right??!0,a=e.includeLowest??!0,t=e.breaks??"Sturges",o;if(typeof t!="string"&&typeof t!="number"&&t.length>1)o=[...t].sort((m,u)=>m-u);else{a=!0;let m=typeof t=="string"?Nt(s,t):typeof t=="number"?t:t[0];if(!Number.isFinite(m)||m<1)throw new RangeError("invalid number of 'breaks'");m=Math.min(m,1e6);let[u,b]=R(s);o=P([u,b],{n:m,minN:1});for(let d=1;d<o.length;d++)if(!(o[d]-o[d-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let l=o.length,[n,h]=r>0?R(s):[0,0],f=1e-7*gt(o,h-n),w=o.map((m,u)=>c?u===0&&a?m-f:m+f:u<l-1?m-f:a?m+f:m-f),M=new Array(Math.max(0,l-1)).fill(0),x=0;for(let m of s){let u=bt(m,w,c,a);u>=0&&(M[u]++,x++)}if(x<r)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let S=M.map((m,u)=>m/(r*(o[u+1]-o[u]))),g=M.map((m,u)=>.5*(o[u+1]+o[u]));return{breaks:o,counts:M,density:S,mids:g}}function bt(i,e,s,r){let c=e.length-1;if(c<1)return-1;if(s){if(i===e[0]&&r)return 0;if(!(i>e[0]&&i<=e[c]))return-1;let o=1,l=c;for(;o<l;){let n=o+l>>1;i<=e[n]?l=n:o=n+1}return o-1}if(i===e[c]&&r)return c-1;if(!(i>=e[0]&&i<e[c]))return-1;let a=0,t=c-1;for(;a<t;){let o=a+t+1>>1;e[o]<=i?a=o:t=o-1}return a}function wt(i){let e=Array.from(i).filter(r=>!Number.isNaN(r)).sort((r,c)=>r-c),s=e.length;if(s<1)throw new RangeError("'x' must have 1 or more non-missing values");return r=>{if(Number.isNaN(r))return NaN;let c=0,a=s;for(;c<a;){let t=c+a>>1;e[t]<=r?c=t+1:a=t}return c/s}}export{O as IQR,j as cor,Q as cov,H as cummax,J as cummin,G as cumprod,Z as cumsum,it as cut,et as cv,K as diff,wt as ecdf,at as findInterval,ft as fivenum,$ as geometricMean,dt as hist,Y as kurtosis,ut as mad,T as mean,tt as meanAD,k as median,v as modes,P as pretty,D as prod,F as quantile,R as range,C as rank,nt as scale,L as sd,W as skewness,z as sum,ot as table,rt as tabulate,st as unique,X as variance,V as weightedMean};
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Probability that a standard bivariate normal pair (X, Y) with correlation `rho` lies in the rectangle
|
|
3
|
+
* `lower ≤ (X, Y) ≤ upper`. Equivalent to mvtnorm's `pmvnorm(lower, upper, corr = matrix(c(1, rho, rho, 1), 2))`.
|
|
4
|
+
* Bounds may be infinite. Accurate to about 1e-15 absolute.
|
|
5
|
+
*
|
|
6
|
+
* @param lower - Lower bounds `[a1, a2]`.
|
|
7
|
+
* @param upper - Upper bounds `[b1, b2]`.
|
|
8
|
+
* @param rho - Correlation, in [−1, 1].
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* ```ts
|
|
12
|
+
* pbvnorm([-Infinity, -Infinity], [0, 0], 0.5); // 0.3333333333333333
|
|
13
|
+
* ```
|
|
14
|
+
*/
|
|
15
|
+
export declare function pbvnorm(lower: readonly [number, number] | readonly number[], upper: readonly [number, number] | readonly number[], rho: number): number;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Rectangle probabilities of the standard bivariate normal distribution (what mvtnorm's pmvnorm gives in two
|
|
2
|
+
// dimensions).
|
|
3
|
+
//
|
|
4
|
+
// Written for rStats.js from oracle/polycor-behaviour.md and the method published by A. Genz, "Numerical computation
|
|
5
|
+
// of rectangular bivariate and trivariate normal and t probabilities", Statistics and Computing 14 (2004) 251-260
|
|
6
|
+
// (after Drezner and Wesolowsky); no code was ported. The upper orthant probability P(X > h, Y > k) is Sheppard's
|
|
7
|
+
// integral over θ in [0, asin ρ], by Gauss-Legendre quadrature with 6, 12 or 20 nodes, for |ρ| < 0.925; closer to
|
|
8
|
+
// |ρ| = 1 it is Φ(−max(h, k)) minus an integral in t = sqrt(1 − ρ²)-scale whose singular part is taken out by a
|
|
9
|
+
// Taylor expansion and integrated in closed form. A rectangle is the alternating sum of four orthants, after
|
|
10
|
+
// reflecting (X, Y) → (−X, −Y) when that puts the rectangle in the upper tail (smaller orthants, less cancellation);
|
|
11
|
+
// it is clipped at 0.
|
|
12
|
+
import { pnorm } from "./normal.js";
|
|
13
|
+
/** Nodes in (0, 1) and weights of the n-point Gauss-Legendre rule on [−1, 1] (the symmetric half), by Newton's method */
|
|
14
|
+
function gaussLegendre(n) {
|
|
15
|
+
const x = [];
|
|
16
|
+
const w = [];
|
|
17
|
+
for (let i = 1; i <= n / 2; i++) {
|
|
18
|
+
let z = Math.cos((Math.PI * (i - 0.25)) / (n + 0.5));
|
|
19
|
+
let dp = 0;
|
|
20
|
+
for (let it = 0; it < 100; it++) {
|
|
21
|
+
// Legendre P_n(z) and its derivative by the three-term recurrence
|
|
22
|
+
let p0 = 1;
|
|
23
|
+
let p1 = z;
|
|
24
|
+
for (let k = 2; k <= n; k++)
|
|
25
|
+
[p0, p1] = [p1, ((2 * k - 1) * z * p1 - (k - 1) * p0) / k];
|
|
26
|
+
dp = (n * (z * p1 - p0)) / (z * z - 1);
|
|
27
|
+
const dz = p1 / dp;
|
|
28
|
+
z -= dz;
|
|
29
|
+
if (Math.abs(dz) <= 1e-17)
|
|
30
|
+
break;
|
|
31
|
+
}
|
|
32
|
+
x.push(z);
|
|
33
|
+
w.push(2 / ((1 - z * z) * dp * dp));
|
|
34
|
+
}
|
|
35
|
+
return { x, w };
|
|
36
|
+
}
|
|
37
|
+
const RULES = [gaussLegendre(6), gaussLegendre(12), gaussLegendre(20)];
|
|
38
|
+
const TWO_PI = 2 * Math.PI;
|
|
39
|
+
const upperPhi = (x) => pnorm(x, { lowerTail: false });
|
|
40
|
+
/** P(X > h, Y > k) for the standard bivariate normal with correlation r (h, k finite) */
|
|
41
|
+
function upperOrthant(h, k, r) {
|
|
42
|
+
if (r === 1)
|
|
43
|
+
return upperPhi(Math.max(h, k));
|
|
44
|
+
if (r === -1)
|
|
45
|
+
return Math.max(0, upperPhi(h) - pnorm(-k));
|
|
46
|
+
const { x, w } = RULES[Math.abs(r) < 0.3 ? 0 : Math.abs(r) < 0.75 ? 1 : 2];
|
|
47
|
+
const hk = h * k;
|
|
48
|
+
if (Math.abs(r) < 0.925) {
|
|
49
|
+
// Sheppard: Φ(−h)Φ(−k) + (1/2π) ∫_0^{asin r} exp(−(h² − 2hk sin θ + k²)/(2 cos² θ)) dθ
|
|
50
|
+
const hs = (h * h + k * k) / 2;
|
|
51
|
+
const asr = Math.asin(r);
|
|
52
|
+
let s = 0;
|
|
53
|
+
for (let i = 0; i < x.length; i++) {
|
|
54
|
+
for (const node of [1 - x[i], 1 + x[i]]) {
|
|
55
|
+
const sn = Math.sin((asr * node) / 2);
|
|
56
|
+
s += w[i] * Math.exp((sn * hk - hs) / (1 - sn * sn));
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return (s * asr) / (2 * TWO_PI) + upperPhi(h) * upperPhi(k);
|
|
60
|
+
}
|
|
61
|
+
// |r| near 1: for r < 0 use P(X > h, Y > k; r) = Φ(−h) − P(X > h, −Y > −k; −r)
|
|
62
|
+
const kk = r < 0 ? -k : k;
|
|
63
|
+
const hkk = r < 0 ? -hk : hk;
|
|
64
|
+
const as = (1 - r) * (1 + r);
|
|
65
|
+
const a = Math.sqrt(as);
|
|
66
|
+
const bs = (h - kk) ** 2;
|
|
67
|
+
const c = (4 - hkk) / 8;
|
|
68
|
+
const d = (12 - hkk) / 16;
|
|
69
|
+
// P(X > h, Y > k; |r|) − Φ(−max(h, k)) = −(1/2π) (closed-form part + quadrature of the remainder) over t in (0, a)
|
|
70
|
+
let s = a * Math.exp(-(bs / as + hkk) / 2) * (1 - (c * (bs - as) * (1 - (d * bs) / 5)) / 3 + (c * d * as * as) / 5);
|
|
71
|
+
if (hkk > -160) {
|
|
72
|
+
const b = Math.sqrt(bs);
|
|
73
|
+
s -= Math.exp(-hkk / 2) * Math.sqrt(TWO_PI) * pnorm(-b / a) * b * (1 - (c * bs * (1 - (d * bs) / 5)) / 3);
|
|
74
|
+
}
|
|
75
|
+
const half = a / 2;
|
|
76
|
+
for (let i = 0; i < x.length; i++) {
|
|
77
|
+
for (const node of [1 - x[i], 1 + x[i]]) {
|
|
78
|
+
const xs = (half * node) ** 2;
|
|
79
|
+
const rs = Math.sqrt(1 - xs);
|
|
80
|
+
s +=
|
|
81
|
+
half *
|
|
82
|
+
w[i] *
|
|
83
|
+
(Math.exp(-bs / (2 * xs) - hkk / (1 + rs)) / rs - Math.exp(-(bs / xs + hkk) / 2) * (1 + c * xs * (1 + d * xs)));
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
const tail = -s / TWO_PI;
|
|
87
|
+
if (r > 0)
|
|
88
|
+
return tail + upperPhi(Math.max(h, kk));
|
|
89
|
+
return -tail + (kk > h ? pnorm(kk) - pnorm(h) : 0);
|
|
90
|
+
}
|
|
91
|
+
/** P(X > h, Y > k) with infinite bounds allowed */
|
|
92
|
+
function orthant(h, k, r) {
|
|
93
|
+
if (h === Infinity || k === Infinity)
|
|
94
|
+
return 0;
|
|
95
|
+
if (h === -Infinity)
|
|
96
|
+
return k === -Infinity ? 1 : upperPhi(k);
|
|
97
|
+
if (k === -Infinity)
|
|
98
|
+
return upperPhi(h);
|
|
99
|
+
return upperOrthant(h, k, r);
|
|
100
|
+
}
|
|
101
|
+
/**
|
|
102
|
+
* Probability that a standard bivariate normal pair (X, Y) with correlation `rho` lies in the rectangle
|
|
103
|
+
* `lower ≤ (X, Y) ≤ upper`. Equivalent to mvtnorm's `pmvnorm(lower, upper, corr = matrix(c(1, rho, rho, 1), 2))`.
|
|
104
|
+
* Bounds may be infinite. Accurate to about 1e-15 absolute.
|
|
105
|
+
*
|
|
106
|
+
* @param lower - Lower bounds `[a1, a2]`.
|
|
107
|
+
* @param upper - Upper bounds `[b1, b2]`.
|
|
108
|
+
* @param rho - Correlation, in [−1, 1].
|
|
109
|
+
*
|
|
110
|
+
* @example
|
|
111
|
+
* ```ts
|
|
112
|
+
* pbvnorm([-Infinity, -Infinity], [0, 0], 0.5); // 0.3333333333333333
|
|
113
|
+
* ```
|
|
114
|
+
*/
|
|
115
|
+
export function pbvnorm(lower, upper, rho) {
|
|
116
|
+
if (lower.length !== 2 || upper.length !== 2)
|
|
117
|
+
throw new TypeError("'lower' and 'upper' must have length 2");
|
|
118
|
+
if (!(rho >= -1 && rho <= 1))
|
|
119
|
+
throw new RangeError("'rho' must be in [-1, 1]");
|
|
120
|
+
let [a1, a2] = lower;
|
|
121
|
+
let [b1, b2] = upper;
|
|
122
|
+
if ([a1, a2, b1, b2].some(Number.isNaN))
|
|
123
|
+
return NaN;
|
|
124
|
+
if (!(a1 < b1 && a2 < b2))
|
|
125
|
+
return 0;
|
|
126
|
+
// reflect a rectangle in the lower half into the upper half
|
|
127
|
+
if (a1 + b1 + a2 + b2 < 0)
|
|
128
|
+
[a1, a2, b1, b2] = [-b1, -b2, -a1, -a2];
|
|
129
|
+
const p = orthant(a1, a2, rho) - orthant(a1, b2, rho) - orthant(b1, a2, rho) + orthant(b1, b2, rho);
|
|
130
|
+
return Math.max(0, p);
|
|
131
|
+
}
|
|
@@ -22,7 +22,7 @@ import { betaIncDD } from "../special/incbet.js";
|
|
|
22
22
|
import { dbinomExponent, dbinomRawDD } from "../special/loader.js";
|
|
23
23
|
import { dbeta1, pbeta1, qbeta1 } from "./beta.js";
|
|
24
24
|
import { dfDensity1, pf1, qf1 } from "./f.js";
|
|
25
|
-
import { dnchisq1, pnchisq1, qnchisq1 } from "./nchisq.js";
|
|
25
|
+
import { dnchisq1, negligibleTail, pnchisq1, qnchisq1 } from "./nchisq.js";
|
|
26
26
|
function betaKernel(a, b, xd, xcd) {
|
|
27
27
|
const ab = twoSum(a, b);
|
|
28
28
|
// For very small x the ratio underflows, so keep it scaled by 2^500
|
|
@@ -284,8 +284,41 @@ export function pnf1(q, m, n, ncp, lowerTail, logP) {
|
|
|
284
284
|
return pnfTiny(q, m, n, ncp, lowerTail, logP);
|
|
285
285
|
if (ncp === 0)
|
|
286
286
|
return pf1(q, m, n, lowerTail, logP);
|
|
287
|
+
const neg = negligibleTail(fTailBound(q, m, n, ncp), lowerTail, logP);
|
|
288
|
+
if (neg !== undefined)
|
|
289
|
+
return neg;
|
|
287
290
|
return pnfRaw(q, m, n, ncp, lowerTail, logP);
|
|
288
291
|
}
|
|
292
|
+
/** Below this log a probability rounds to 0 in double precision (as in src/distributions/nchisq.ts) */
|
|
293
|
+
const LOG_NEGLIGIBLE = -746;
|
|
294
|
+
/**
|
|
295
|
+
* Chernoff bounds of the noncentral F = (X/m)/(V/n), X ~ χ²(m, λ), V ~ χ²(n) independent. With c = q m/n,
|
|
296
|
+
* F <= q is X - cV <= 0, and E[e^(-s(X - cV))] = (1 + 2s)^(-m/2) e^(-λs/(1 + 2s)) (1 - 2cs)^(-n/2) for 0 < s < 1/(2c)
|
|
297
|
+
* bounds P[F <= q]; E[e^(s(X - cV))] = (1 - 2s)^(-m/2) e^(λs/(1 - 2s)) (1 + 2cs)^(-n/2) for 0 < s < 1/2 bounds
|
|
298
|
+
* P[F >= q]. Every s in range gives a valid bound; the smallest over a grid of s is taken. Returns the tail whose
|
|
299
|
+
* bound is below the double range.
|
|
300
|
+
*/
|
|
301
|
+
function fTailBound(q, m, n, ncp) {
|
|
302
|
+
const c = (q * m) / n;
|
|
303
|
+
if (!(c > 0 && Number.isFinite(c)))
|
|
304
|
+
return undefined;
|
|
305
|
+
const lower = (s) => -(m / 2) * Math.log1p(2 * s) - (ncp * s) / (1 + 2 * s) - (n / 2) * Math.log1p(-2 * c * s);
|
|
306
|
+
const upper = (s) => -(m / 2) * Math.log1p(-2 * s) + (ncp * s) / (1 - 2 * s) - (n / 2) * Math.log1p(2 * c * s);
|
|
307
|
+
const best = (f, sMax) => {
|
|
308
|
+
let b = Infinity;
|
|
309
|
+
for (let i = 1; i <= 60; i++) {
|
|
310
|
+
const v = Math.min(f(sMax * 2 ** -i), f(sMax * (1 - 2 ** -i)));
|
|
311
|
+
if (v < b)
|
|
312
|
+
b = v;
|
|
313
|
+
}
|
|
314
|
+
return b;
|
|
315
|
+
};
|
|
316
|
+
if (best(lower, 1 / (2 * c)) < LOG_NEGLIGIBLE)
|
|
317
|
+
return "lower";
|
|
318
|
+
if (best(upper, 0.5) < LOG_NEGLIGIBLE)
|
|
319
|
+
return "upper";
|
|
320
|
+
return undefined;
|
|
321
|
+
}
|
|
289
322
|
export function qnf1(p, m, n, ncp, lowerTail, logP) {
|
|
290
323
|
if (Number.isNaN(p) || Number.isNaN(m) || Number.isNaN(n) || Number.isNaN(ncp))
|
|
291
324
|
return NaN;
|
|
@@ -1,3 +1,13 @@
|
|
|
1
1
|
export declare function dnchisq1(x: number, df: number, ncp: number, log: boolean): number;
|
|
2
2
|
export declare function pnchisq1(q: number, df: number, ncp: number, lowerTail: boolean, logP: boolean): number;
|
|
3
|
+
/**
|
|
4
|
+
* A tail that a rigorous bound places below the smallest positive double: `far` is "lower" when P[X <= q] is
|
|
5
|
+
* negligible, "upper" when P[X > q] is, undefined when neither bound decides it
|
|
6
|
+
*/
|
|
7
|
+
export type FarTail = "lower" | "upper" | undefined;
|
|
8
|
+
/**
|
|
9
|
+
* The value of the requested tail when the far tail is negligible: the far tail is exactly 0, the near tail exactly 1
|
|
10
|
+
* (log 0). The log of the far tail is left to the full computation (undefined).
|
|
11
|
+
*/
|
|
12
|
+
export declare function negligibleTail(far: FarTail, lowerTail: boolean, logP: boolean): number | undefined;
|
|
3
13
|
export declare function qnchisq1(p: number, df: number, ncp: number, lowerTail: boolean, logP: boolean): number;
|