@numero-uno-jpn/rstats 0.9.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.
Files changed (112) hide show
  1. package/CHANGELOG.md +63 -0
  2. package/README.ja.md +60 -11
  3. package/README.md +59 -10
  4. package/THIRD_PARTY_NOTICES.md +7 -2
  5. package/dist/chunks/{chunk-H2AP6TCR.js → chunk-2XKG3DX4.js} +1 -1
  6. package/dist/chunks/{chunk-FC2TLHZC.js → chunk-4NM37MGA.js} +2 -2
  7. package/dist/chunks/chunk-7HPVUVZB.js +2 -0
  8. package/dist/chunks/{chunk-YC4JWUKG.js → chunk-AECGWZHD.js} +2 -2
  9. package/dist/chunks/{chunk-LE7TBHNI.js → chunk-ENL43FNO.js} +2 -2
  10. package/dist/chunks/chunk-EWC6I75B.js +2 -0
  11. package/dist/chunks/chunk-IT354SHV.js +3 -0
  12. package/dist/chunks/{chunk-BGVMSDVJ.js → chunk-LIMZKONM.js} +2 -2
  13. package/dist/chunks/chunk-O6PT7IVU.js +2 -0
  14. package/dist/chunks/{chunk-TOVTN5Y2.js → chunk-QFULZNHL.js} +1 -1
  15. package/dist/chunks/{chunk-5K4PS7IV.js → chunk-QJJWGNJP.js} +2 -2
  16. package/dist/chunks/{chunk-LWUSYIQ4.js → chunk-QULPY6YM.js} +1 -1
  17. package/dist/chunks/chunk-XWTZ4RTR.js +2 -0
  18. package/dist/chunks/chunk-ZRIM4R4A.js +2 -0
  19. package/dist/descriptive/factanal.d.ts +56 -0
  20. package/dist/descriptive/factanal.js +186 -0
  21. package/dist/descriptive/omega.d.ts +56 -0
  22. package/dist/descriptive/omega.js +323 -0
  23. package/dist/descriptive.js +2 -2
  24. package/dist/distributions/bvnorm.d.ts +15 -0
  25. package/dist/distributions/bvnorm.js +131 -0
  26. package/dist/distributions/nbeta.js +34 -1
  27. package/dist/distributions/nchisq.d.ts +10 -0
  28. package/dist/distributions/nchisq.js +46 -0
  29. package/dist/distributions.js +2 -2
  30. package/dist/entries/distributions.d.ts +1 -0
  31. package/dist/entries/distributions.js +1 -0
  32. package/dist/entries/linalg.d.ts +2 -0
  33. package/dist/entries/linalg.js +2 -0
  34. package/dist/entries/numerics.d.ts +2 -0
  35. package/dist/entries/numerics.js +1 -0
  36. package/dist/entries/tests.d.ts +22 -1
  37. package/dist/entries/tests.js +19 -1
  38. package/dist/htest/agreement.d.ts +141 -0
  39. package/dist/htest/agreement.js +274 -0
  40. package/dist/htest/aov.d.ts +19 -0
  41. package/dist/htest/aov.js +22 -15
  42. package/dist/htest/core/simulate.d.ts +2 -0
  43. package/dist/htest/core/simulate.js +1 -1
  44. package/dist/htest/dunnett.d.ts +5 -0
  45. package/dist/htest/dunnett.js +89 -0
  46. package/dist/htest/effectSize.d.ts +112 -0
  47. package/dist/htest/effectSize.js +385 -0
  48. package/dist/htest/leveneTest.d.ts +30 -0
  49. package/dist/htest/leveneTest.js +41 -0
  50. package/dist/htest/multipleComparisons.d.ts +147 -0
  51. package/dist/htest/multipleComparisons.js +369 -0
  52. package/dist/htest/normalityTests.d.ts +44 -0
  53. package/dist/htest/normalityTests.js +164 -0
  54. package/dist/htest/polycor.d.ts +117 -0
  55. package/dist/htest/polycor.js +468 -0
  56. package/dist/htest/power.d.ts +132 -0
  57. package/dist/htest/power.js +227 -0
  58. package/dist/htest/pwr.d.ts +263 -0
  59. package/dist/htest/pwr.js +440 -0
  60. package/dist/htest/rankTests.d.ts +7 -0
  61. package/dist/htest/rankTests.js +11 -1
  62. package/dist/htest/trendTests.d.ts +57 -0
  63. package/dist/htest/trendTests.js +167 -0
  64. package/dist/linalg/eigen.d.ts +8 -0
  65. package/dist/linalg/eigen.js +5 -4
  66. package/dist/linalg/expm.d.ts +48 -0
  67. package/dist/linalg/expm.js +472 -0
  68. package/dist/linalg/schur.d.ts +48 -0
  69. package/dist/linalg/schur.js +225 -0
  70. package/dist/linalg.js +2 -2
  71. package/dist/models/anovaSequential.d.ts +58 -0
  72. package/dist/models/anovaSequential.js +138 -0
  73. package/dist/models/aovEz.d.ts +64 -0
  74. package/dist/models/aovEz.js +332 -0
  75. package/dist/models/aovStrata.d.ts +32 -0
  76. package/dist/models/aovStrata.js +104 -0
  77. package/dist/models/carAnova.d.ts +30 -0
  78. package/dist/models/carAnova.js +121 -0
  79. package/dist/models/coxph.d.ts +101 -0
  80. package/dist/models/coxph.js +502 -0
  81. package/dist/models/ddLeastSquares.d.ts +30 -0
  82. package/dist/models/ddLeastSquares.js +90 -0
  83. package/dist/models/ddMatrix.d.ts +10 -0
  84. package/dist/models/ddMatrix.js +91 -0
  85. package/dist/models/formula.d.ts +83 -0
  86. package/dist/models/formula.js +333 -0
  87. package/dist/models/lm.d.ts +84 -3
  88. package/dist/models/lm.js +141 -44
  89. package/dist/models/mauchly.d.ts +48 -0
  90. package/dist/models/mauchly.js +123 -0
  91. package/dist/models/modelFrame.d.ts +40 -0
  92. package/dist/models/modelFrame.js +131 -0
  93. package/dist/models/modelMatrix.d.ts +88 -0
  94. package/dist/models/modelMatrix.js +170 -0
  95. package/dist/models/survival.d.ts +87 -0
  96. package/dist/models/survival.js +238 -0
  97. package/dist/numerics.js +2 -2
  98. package/dist/optim/lbfgsb.d.ts +20 -0
  99. package/dist/optim/lbfgsb.js +1240 -0
  100. package/dist/optim/optim.d.ts +85 -0
  101. package/dist/optim/optim.js +610 -0
  102. package/dist/rstats.js +19 -4
  103. package/dist/special.js +2 -2
  104. package/dist/tests.js +18 -4
  105. package/llms.txt +102 -0
  106. package/package.json +3 -2
  107. package/dist/chunks/chunk-24U4DKRY.js +0 -2
  108. package/dist/chunks/chunk-IVOBWYLV.js +0 -2
  109. package/dist/chunks/chunk-JLSTEMSN.js +0 -2
  110. package/dist/chunks/chunk-MF4VBCHQ.js +0 -2
  111. package/dist/chunks/chunk-MSAUU6PY.js +0 -2
  112. package/dist/chunks/chunk-ZRO446BP.js +0 -2
@@ -0,0 +1,186 @@
1
+ // Maximum-likelihood factor analysis, R's factanal(), with the varimax and promax rotations. Written for rStats.js
2
+ // from the specification oracle/factanal-behaviour.md (no R code was read or used): the uniquenesses minimise the
3
+ // likelihood criterion by L-BFGS-B (this library's optim), the loadings come from the eigendecomposition of the
4
+ // scaled correlation matrix, and the rotations are Kaiser's varimax (normalised) and Hendrickson and White's promax.
5
+ import { pchisq } from "../distributions/chisq.js";
6
+ import { eigen } from "../linalg/eigen.js";
7
+ import { qr, qrCoef } from "../linalg/qr.js";
8
+ import { solve } from "../linalg/solve.js";
9
+ import { svd } from "../linalg/svd.js";
10
+ import { optim } from "../optim/optim.js";
11
+ import { twoSum } from "../special/dd.js";
12
+ import { cov } from "./cov.js";
13
+ /** Sum rounded once (R's long double accumulation, here double-double); also used by omega */
14
+ export function sumOnce(xs) {
15
+ let hi = 0;
16
+ let lo = 0;
17
+ for (const x of xs) {
18
+ const [s, e] = twoSum(hi, x);
19
+ hi = s;
20
+ lo += e;
21
+ }
22
+ return hi + lo;
23
+ }
24
+ const colSumsOf = (m, f) => m[0].map((_, j) => sumOnce(m.map((r) => f(r[j]))));
25
+ /** The scaled matrix D S D with D = diag(1/sqrt(psi)) */
26
+ function scaled(S, psi) {
27
+ const d = psi.map((v) => 1 / Math.sqrt(v));
28
+ return S.map((row, i) => row.map((v, j) => d[i] * v * d[j]));
29
+ }
30
+ /** Loadings at psi: diag(sqrt(psi)) V diag(sqrt(max(e - 1, 0))) from the first q eigenvectors of D S D */
31
+ function loadingsAt(S, psi, q) {
32
+ const E = eigen(scaled(S, psi), { symmetric: true });
33
+ const w = E.values.slice(0, q).map((e) => Math.sqrt(Math.max(e - 1, 0)));
34
+ return E.vectors.map((row, i) => row.slice(0, q).map((v, k) => Math.sqrt(psi[i]) * (v * w[k])));
35
+ }
36
+ /** Columns sorted by decreasing sum of squares, each made to have a positive sum; `rot` (if any) permuted and signed alike */
37
+ function orderAndSignColumns(L, rot) {
38
+ const ssq = colSumsOf(L, (v) => v * v);
39
+ const order = ssq.map((_, j) => j).sort((a, b) => ssq[b] - ssq[a] || a - b);
40
+ let out = L.map((r) => order.map((j) => r[j]));
41
+ let R = rot?.map((r) => order.map((j) => r[j]));
42
+ const sign = colSumsOf(out, (v) => v).map((s) => (s < 0 ? -1 : 1));
43
+ out = out.map((r) => r.map((v, j) => (sign[j] < 0 ? -v : v)));
44
+ R = R?.map((r) => r.map((v, j) => (sign[j] < 0 ? -v : v)));
45
+ return R === undefined ? { L: out } : { L: out, rot: R };
46
+ }
47
+ const matMul = (A, B) => A.map((row) => B[0].map((_, j) => {
48
+ let s = 0;
49
+ for (let k = 0; k < row.length; k++)
50
+ s += row[k] * B[k][j];
51
+ return s;
52
+ }));
53
+ const transpose = (A) => A[0].map((_, j) => A.map((r) => r[j]));
54
+ /** Varimax rotation (normalised, eps 1e-5, at most 1000 iterations); also used by omega */
55
+ export function varimax(L) {
56
+ const k = L[0].length;
57
+ const p = L.length;
58
+ const len = L.map((r) => Math.sqrt(sumOnce(r.map((v) => v * v))));
59
+ const X = L.map((r, i) => r.map((v) => v / len[i]));
60
+ const Xt = transpose(X);
61
+ let T = Array.from({ length: k }, (_, i) => Array.from({ length: k }, (_, j) => (i === j ? 1 : 0)));
62
+ let total = 0;
63
+ for (let it = 0; it < 1000; it++) {
64
+ const Z = matMul(X, T);
65
+ const css = Z[0].map((_, j) => {
66
+ let s = 0;
67
+ for (let i = 0; i < p; i++)
68
+ s += Z[i][j] * Z[i][j];
69
+ return s;
70
+ });
71
+ const W = Z.map((r) => r.map((z, j) => z ** 3 - (z * css[j]) / p));
72
+ const B = matMul(Xt, W);
73
+ const sv = svd(B);
74
+ T = matMul(sv.u, transpose(sv.v));
75
+ const previous = total;
76
+ total = sumOnce(sv.d);
77
+ if (total < previous * (1 + 1e-5))
78
+ break;
79
+ }
80
+ const Z = matMul(X, T);
81
+ return { loadings: Z.map((r, i) => r.map((v) => v * len[i])), rotmat: T };
82
+ }
83
+ /** Promax rotation (m = 4) */
84
+ function promax(L) {
85
+ const v = varimax(L);
86
+ const X = v.loadings;
87
+ const Q = X.map((r) => r.map((x) => x * Math.abs(x) ** 3));
88
+ const U0 = qrCoef(qr(X), Q);
89
+ const d = solve(matMul(transpose(U0), U0)).map((r, i) => r[i]);
90
+ const U = U0.map((r) => r.map((u, j) => u * Math.sqrt(d[j])));
91
+ return { loadings: matMul(X, U), rotmat: matMul(v.rotmat, U) };
92
+ }
93
+ /**
94
+ * Maximum-likelihood factor analysis of a data matrix (rows are observations) or, with `options.covmat`, of a
95
+ * covariance matrix. Equivalent to R's `factanal()` with `rotation` `"varimax"`, `"promax"` or `"none"`.
96
+ *
97
+ * @param x The data matrix (array of rows), or `null` with `options.covmat`.
98
+ * @param factors The number of factors.
99
+ *
100
+ * @example
101
+ * ```ts
102
+ * const fa = factanal(x, 2); // x: an n x 6 data matrix
103
+ * fa.uniquenesses; fa.loadings; fa.PVAL;
104
+ * ```
105
+ */
106
+ export function factanal(x, factors, options = {}) {
107
+ let cv;
108
+ let nObs;
109
+ if (options.covmat !== undefined) {
110
+ cv = options.covmat.map((r) => r.slice());
111
+ nObs = options.nObs ?? NaN;
112
+ }
113
+ else {
114
+ if (x === null)
115
+ throw new TypeError("neither 'x' nor 'covmat' supplied");
116
+ cv = cov(x);
117
+ nObs = x.length;
118
+ }
119
+ const p = cv.length;
120
+ if (p < 3)
121
+ throw new RangeError("factor analysis requires at least three variables");
122
+ const q = factors;
123
+ if (!Number.isInteger(q) || q < 1)
124
+ throw new RangeError("'factors' must be a positive integer");
125
+ const dof = ((p - q) ** 2 - p - q) / 2;
126
+ if (dof < 0)
127
+ throw new RangeError(`${q} ${q === 1 ? "factor is" : "factors are"} too many for ${p} variables`);
128
+ const sds = cv.map((r, i) => Math.sqrt(r[i]));
129
+ const S = cv.map((r, i) => r.map((v, j) => v / (sds[i] * sds[j])));
130
+ const lower = options.control?.lower ?? 0.005;
131
+ const start = options.control?.start?.slice() ?? solve(S).map((r, i) => (1 - q / (2 * p)) / r[i]);
132
+ const objective = (psi) => {
133
+ const e = eigen(scaled(S, psi), { symmetric: true, onlyValues: true }).values.slice(q);
134
+ return -(sumOnce(e.map((v) => Math.log(v) - v)) - q + p);
135
+ };
136
+ const gradient = (psi) => {
137
+ const L = loadingsAt(S, psi, q);
138
+ return psi.map((v, i) => {
139
+ let s = 0;
140
+ for (let k = 0; k < q; k++)
141
+ s += L[i][k] * L[i][k];
142
+ return (s + v - S[i][i]) / (v * v);
143
+ });
144
+ };
145
+ const fit = optim(start, objective, {
146
+ gr: gradient,
147
+ method: "L-BFGS-B",
148
+ lower,
149
+ upper: 1,
150
+ control: { fnscale: 1, parscale: new Array(p).fill(0.01) },
151
+ });
152
+ if (fit.convergence !== 0)
153
+ throw new Error("unable to optimize from this starting value");
154
+ const psi = fit.par;
155
+ let L = orderAndSignColumns(loadingsAt(S, psi, q)).L;
156
+ let rotmat;
157
+ const rotation = options.rotation ?? "varimax";
158
+ if (rotation !== "none" && q >= 2) {
159
+ const r = rotation === "varimax" ? varimax(L) : promax(L);
160
+ const sorted = orderAndSignColumns(r.loadings, r.rotmat);
161
+ L = sorted.L;
162
+ rotmat = sorted.rot;
163
+ }
164
+ else if (rotation !== "varimax" && rotation !== "promax" && rotation !== "none") {
165
+ throw new RangeError(`unknown rotation '${String(rotation)}'`);
166
+ }
167
+ let STATISTIC = NaN;
168
+ let PVAL = NaN;
169
+ if (!Number.isNaN(nObs) && dof > 0) {
170
+ STATISTIC = (nObs - 1 - (2 * p + 5) / 6 - (2 * q) / 3) * fit.value;
171
+ PVAL = pchisq(STATISTIC, dof, { lowerTail: false });
172
+ }
173
+ const out = {
174
+ uniquenesses: psi,
175
+ loadings: L,
176
+ STATISTIC,
177
+ dof,
178
+ PVAL,
179
+ converged: true,
180
+ objective: fit.value,
181
+ counts: fit.counts,
182
+ };
183
+ if (rotmat !== undefined)
184
+ out.rotmat = rotmat;
185
+ return out;
186
+ }
@@ -0,0 +1,56 @@
1
+ /** Options of {@link omega} */
2
+ export interface OmegaOptions {
3
+ /** The number of first-order (group) factors. Default 3. */
4
+ nfactors?: number;
5
+ /** A correlation (or covariance) matrix to analyse instead of the data `x` (pass `null` as `x`). */
6
+ covmat?: readonly (readonly number[])[];
7
+ }
8
+ /** Result of {@link omega} */
9
+ export interface OmegaResult {
10
+ /** Omega hierarchical: the share of the total variance due to the general factor */
11
+ omegaH: number;
12
+ /** Omega asymptotic: the general factor's share of the common variance */
13
+ omegaLim: number;
14
+ /** Cronbach's alpha (standardised: of the correlations) */
15
+ alpha: number;
16
+ /** Omega total */
17
+ omegaTot: number;
18
+ /** Guttman's lambda 6 */
19
+ G6: number;
20
+ /** Explained common variance of the general factor */
21
+ ECV: number;
22
+ /** The Schmid-Leiman matrix, p rows; columns as `slNames` */
23
+ sl: number[][];
24
+ /** `["g", "F1*", ..., "h2", "u2", "p2", "com"]` */
25
+ slNames: string[];
26
+ /** The varimax loadings of the first-order minres solution */
27
+ orthog: number[][];
28
+ /** The oblimin pattern (the varimax loadings for one factor) */
29
+ oblique: number[][];
30
+ /** The factor correlations (absent for one factor) */
31
+ phi?: number[][];
32
+ /** The loadings of the first-order factors on the general factor */
33
+ gloading: number[];
34
+ /** The item signs (-1 for a flipped item) */
35
+ key: number[];
36
+ /** Rows g, F1*, ...; columns total, general, group (NaN for a group with no items) */
37
+ omegaGroup: number[][];
38
+ warnings: string[];
39
+ messages: string[];
40
+ }
41
+ /**
42
+ * McDonald's omega (hierarchical, asymptotic and total) from a Schmid-Leiman transformation of an oblique minres
43
+ * factor solution. Equivalent to R's `psych::omega(x, nfactors)` with its defaults (`fm = "minres"`, `rotate =
44
+ * "oblimin"`, `option = "equal"`, `flip = TRUE`).
45
+ *
46
+ * @param x The data matrix (array of rows, NaN for missing values: correlations of pairwise complete observations),
47
+ * or `null` with `options.covmat`.
48
+ * @param options See {@link OmegaOptions}.
49
+ *
50
+ * @example
51
+ * ```ts
52
+ * const om = omega(x); // x: an n x 12 data matrix
53
+ * om.omegaH; om.omegaTot; om.sl;
54
+ * ```
55
+ */
56
+ export declare function omega(x: readonly (readonly number[])[] | null, options?: OmegaOptions): OmegaResult;
@@ -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
+ }
@@ -1,2 +1,2 @@
1
- /*! rStats.js 0.9.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{c as V}from"./chunks/chunk-MF4VBCHQ.js";import{d as T,e as O}from"./chunks/chunk-MSAUU6PY.js";import"./chunks/chunk-IVOBWYLV.js";import{a as q,b as Z,c as $,d as H,e as W,f as G,g as v,h as x,i as L,j as J,k as K,l as Y,m as ee,n as te,o as ne,p as re,q as oe,r as se,s as ie,t as ae,u as fe}from"./chunks/chunk-YC4JWUKG.js";import{a as j,b as ce,c as le,d as ue,e as me,f as he}from"./chunks/chunk-TOVTN5Y2.js";import{d as P}from"./chunks/chunk-BGVMSDVJ.js";import"./chunks/chunk-FC2TLHZC.js";import"./chunks/chunk-H2AP6TCR.js";var B=4*Number.EPSILON,de={4:[0,1],5:[.5,.5],6:[0,0],8:[1/3,1/3],9:[3/8,3/8]};function Ne(t,e,r){let s=t.length,f=i=>t[Math.min(Math.max(i,1),s)-1];if(r===7){let i=1+(s-1)*e,d=Math.floor(i),u=f(d),w=f(Math.ceil(i));if(i>d&&w!==u){let b=i-d;return(1-b)*u+b*w}return u}let o,n;if(r<=3){let i=r===3?s*e-.5:s*e;o=Math.floor(i*(1+B)),r===1?n=i>o?1:0:r===2?n=i>o?1:.5:n=i!==o||Math.abs(o%2)===1?1:0}else{let[i,d]=de[r],u=i+e*(s+1-i-d);o=Math.floor(u*(1+B)),n=u-o,Math.abs(n)<B&&(n=0)}let a=f(o),c=f(o+1);return n===1?c:n>0&&n<1&&a!==c?(1-n)*a+n*c:a}function F(t,e=[0,.25,.5,.75,1],r={}){let s=r.type??7;if(!(Number.isInteger(s)&&s>=1&&s<=9))throw new RangeError("'type' must be an integer in 1..9");let f=q(t,r.naRm);if(f===void 0)throw new RangeError("missing values and NaN's not allowed if 'na.rm' is FALSE");let o=f.sort((i,d)=>i-d),n=typeof e=="number"?[e]:Array.from(e),a=100*Number.EPSILON;if(n.some(i=>i<-a||i>1+a))throw new RangeError("'probs' outside [0,1]");let c=n.map(i=>Number.isNaN(i)||o.length===0?NaN:Ne(o,Math.min(Math.max(i,0),1),s));return typeof e=="number"?c[0]:c}function D(t,e={}){let[r,s]=F(t,[.25,.75],e);return s-r}function pe(t){let e=Array.from(t).filter(o=>!Number.isNaN(o)).sort((o,n)=>o-n),r=e.length;if(r===0)return[NaN,NaN,NaN,NaN,NaN];let s=Math.floor((r+3)/2)/2;return[1,s,(r+1)/2,r+1-s,r].map(o=>.5*(e[Math.floor(o)-1]+e[Math.ceil(o)-1]))}function ge(t,e={}){let r=q(t,e.naRm);if(r===void 0)return NaN;let s=e.center??x(r),f=e.constant??1.4826,o=e.low??!1,n=e.high??!1,a=r.map(i=>Math.abs(i-s)),c=a.length;if((o||n)&&c%2===0){if(o&&n)throw new RangeError("'low' and 'high' cannot be both TRUE");let i=c/2+(n?1:0),d=a.sort((u,w)=>u-w);return f*d[i-1]}return f*x(a)}function we(t,e){let r=t.length,s=new Array(r);if(e==="first"||e==="last"||e==="random"){let n=e==="random"?V(r):[],a=Array.from({length:r},(c,i)=>i);return a.sort((c,i)=>{let d=t[c]-t[i];return d!==0?d:e==="first"?c-i:e==="last"?i-c:n[c]-n[i]||c-i}),a.forEach((c,i)=>s[c]=i+1),s}let f=Array.from({length:r},(n,a)=>a).sort((n,a)=>t[n]-t[a]||n-a),o=0;for(;o<r;){let n=o;for(;n+1<r&&t[f[n+1]]===t[f[o]];)n++;let a=e==="average"?(o+n+2)/2:e==="min"?o+1:n+1;for(let c=o;c<=n;c++)s[f[c]]=a;o=n+1}return s}function I(t,e={}){let r=e.tiesMethod??"average";if(!["average","first","last","random","max","min"].includes(r))throw new RangeError(`invalid tiesMethod "${r}"`);let s=e.naLast??"last",f=Array.from(t),o=f.filter(u=>!Number.isNaN(u)),n=we(o,r),a=f.length-o.length,c=[],i=0,d=0;for(let u of f)Number.isNaN(u)?(d++,c.push(s==="keep"?NaN:s==="last"?o.length+d:d)):c.push(s==="first"?n[i++]+a:n[i++]);return c}var be=["pearson","kendall","spearman"],Me=["all.obs","complete.obs","pairwise.complete.obs","everything","na.or.complete"];function C(t,e,r,s){if(t===void 0)return r;if(e.includes(t))return t;let f=e.filter(o=>o.startsWith(t));if(t.length===0||f.length!==1)throw new RangeError(`invalid '${s}' argument`);return f[0]}function R(t){return t.length>0&&Array.isArray(t[0])}function Q(t){if(!R(t))return[Array.from(t)];let e=t[0].length;return Array.from({length:e},(r,s)=>t.map(f=>f[s]))}function U(t,e,r,s){let f=C(r.method,be,"pearson","method"),o=C(r.use,Me,"everything","use");if(e===void 0&&!R(t))throw new TypeError("supply both 'x' and 'y' or a matrix-like 'x'");let n=Q(t),a=e===void 0?n:Q(e),c=n[0]?.length??0;if(a.some(h=>h.length!==c))throw new RangeError("incompatible dimensions");let i=[...n,...a];if(o==="all.obs"&&i.some(h=>h.some(Number.isNaN)))throw new RangeError("missing observations in cov/cor");if(!s&&o==="pairwise.complete.obs"&&f!=="pearson")throw new RangeError("cannot handle 'pairwise.complete.obs'");let d;if((o==="complete.obs"||o==="na.or.complete")&&(d=Array.from({length:c},(h,m)=>i.every(l=>!Number.isNaN(l[m]))),!d.some(Boolean))){if(o==="complete.obs")throw new RangeError("no complete element pairs");return e===void 0||R(t)||R(e)?n.map(()=>a.map(()=>NaN)):NaN}let u=h=>{let m=d===void 0?h:h.filter((l,N)=>d[N]);return f==="spearman"&&o!=="pairwise.complete.obs"?I(m,{naLast:"keep"}):m},w=n.map(u),b=e===void 0?w:a.map(u),y=(h,m)=>{let l=h,N=m;if(o==="pairwise.complete.obs"){let p=h.map((k,M)=>!Number.isNaN(k)&&!Number.isNaN(m[M]));l=h.filter((k,M)=>p[M]),N=m.filter((k,M)=>p[M]),f==="spearman"&&(l=I(l),N=I(N))}else if(l.some(Number.isNaN)||N.some(Number.isNaN))return NaN;return f==="kendall"?s?O(l,N).tau:2*O(l,N).s:s?T(l,N)[0]:P(l,N)},E=w.map(h=>b.map(m=>y(h,m)));return s&&e===void 0&&o!=="pairwise.complete.obs"&&E.forEach((h,m)=>h[m]=1),e!==void 0&&!R(t)&&!R(e)?E[0][0]:E}function ke(t,e,r={}){return e!==void 0&&!Array.isArray(e)&&!ArrayBuffer.isView(e)?U(t,void 0,e,!1):U(t,e,r,!1)}function ye(t,e,r={}){return e!==void 0&&!Array.isArray(e)&&!ArrayBuffer.isView(e)?U(t,void 0,e,!0):U(t,e,r,!0)}function z(t,e={}){let r=Array.from(t).filter(Number.isFinite);if(r.length===0)return[];let s=e.n??5,f=e.minN??Math.floor(s/3),o=e.shrinkSml??.75,n=e.highUBias??1.5,a=e.u5Bias??.5+1.5*n,c=1/0,i=-1/0;for(let g of r)g<c&&(c=g),g>i&&(i=g);let d=i-c,u,w;if(d===0&&i===0)u=1,w=!0;else{u=Math.max(Math.abs(c),Math.abs(i));let A=(1+(a>=1.5*n+.5?1/(1+n):1.5/(1+a)))*Math.max(1,s)*Number.EPSILON;w=d<u*A*3}w?(u>10&&(u=9+u/10),u*=o,f>1&&(u/=f)):(u=s>1?d/s:d,d===1/0&&s>=2&&(u=i/s-c/s));let b=2**-20*Ae;u<b?u=b:u>Number.MAX_VALUE/1.25&&(u=Number.MAX_VALUE/1.25);let y=10**Math.floor(Math.log10(u)),E=[[2*y,n],[5*y,a],[10*y,n]],h=y;for(let[g,A]of E)if(g-u<A*(u-h))h=g;else break;let m=1e-10,l=Math.floor(c/h+m);for(;l*h>c+m*h;)l--;for(;!Number.isFinite(l*h);)l++;let N=Math.ceil(i/h-m);for(;N*h<i-m*h;)N++;for(;!Number.isFinite(N*h);)N--;let p=Math.trunc(.5+N-l);if(p<f){let g=f-p,A=Math.floor(g/2),_=g%2;c===0&&l===0&&i!==0?N+=g:i===0&&N===0&&c!==0?l-=g:l>=0?(N+=A,l-=A+_):(l-=A,N+=A+_),p=f}let k=l*h<c?l*h:c,M=N*h>i?N*h:i;if(p<=0)return[k];let S;if(Number.isFinite(M-k))S=j(k,M,p+1);else{let g=M/p-k/p;S=Array.from({length:p+1},(A,_)=>k+_*g),S[p]=M}let X=M/p-k/p;return S.map(g=>Math.abs(g)<1e-14*X?0:g)}var Ae=22250738585072014e-324;function Ee(t){return t===0||!Number.isFinite(t)?t:Number(t.toPrecision(5))}function xe(t,e){let r=t.length,[s,f]=L(t),o=f-s;switch(e.toLowerCase()){case"sturges":return Math.ceil(Math.log2(r)+1);case"scott":{let n=3.5*v(t)*r**-.3333333333333333;return n>0?Math.max(1,Math.ceil(o/n)):1}case"fd":case"freedman-diaconis":{let n=t.map(Ee),a=2*D(n);for(let c=1/8;a===0&&c>=1/512;c/=2){let[i,d]=F(n,[c,1-c]);a=(d-i)/(1-2*c)}return a===0&&(a=3.5*v(t)),a>0?Math.ceil(o/a*r**(1/3)):1}default:throw new RangeError("unknown 'breaks' algorithm")}}function Re(t,e){let r=t.slice(1).map((s,f)=>s-t[f]);return t.length>5?x(r):t.length<=3?e:Math.min(...r.filter(s=>s>0))}function Le(t,e={}){let r=Array.from(t).filter(Number.isFinite),s=r.length,f=e.right??!0,o=e.includeLowest??!0,n=e.breaks??"Sturges",a;if(typeof n!="string"&&typeof n!="number"&&n.length>1)a=[...n].sort((m,l)=>m-l);else{o=!0;let m=typeof n=="string"?xe(r,n):typeof n=="number"?n:n[0];if(!Number.isFinite(m)||m<1)throw new RangeError("invalid number of 'breaks'");m=Math.min(m,1e6);let[l,N]=L(r);a=z([l,N],{n:m,minN:1});for(let p=1;p<a.length;p++)if(!(a[p]-a[p-1]>0))throw new RangeError("'breaks' are not strictly increasing")}let c=a.length,[i,d]=s>0?L(r):[0,0],u=1e-7*Re(a,d-i),w=a.map((m,l)=>f?l===0&&o?m-u:m+u:l<c-1?m-u:o?m+u:m-u),b=new Array(Math.max(0,c-1)).fill(0),y=0;for(let m of r){let l=Ie(m,w,f,o);l>=0&&(b[l]++,y++)}if(y<s)throw new RangeError("some 'x' not counted; maybe 'breaks' do not span range of 'x'");let E=b.map((m,l)=>m/(s*(a[l+1]-a[l]))),h=b.map((m,l)=>.5*(a[l+1]+a[l]));return{breaks:a,counts:b,density:E,mids:h}}function Ie(t,e,r,s){let f=e.length-1;if(f<1)return-1;if(r){if(t===e[0]&&s)return 0;if(!(t>e[0]&&t<=e[f]))return-1;let a=1,c=f;for(;a<c;){let i=a+c>>1;t<=e[i]?c=i:a=i+1}return a-1}if(t===e[f]&&s)return f-1;if(!(t>=e[0]&&t<e[f]))return-1;let o=0,n=f-1;for(;o<n;){let a=o+n+1>>1;e[a]<=t?o=a:n=a-1}return o}function Se(t){let e=Array.from(t).filter(s=>!Number.isNaN(s)).sort((s,f)=>s-f),r=e.length;if(r<1)throw new RangeError("'x' must have 1 or more non-missing values");return s=>{if(Number.isNaN(s))return NaN;let f=0,o=r;for(;f<o;){let n=f+o>>1;e[n]<=s?f=n+1:o=n}return f/r}}export{D as IQR,ye as cor,ke as cov,Y as cummax,ee as cummin,K as cumprod,J as cumsum,me as cut,ae as cv,te as diff,Se as ecdf,he as findInterval,pe as fivenum,oe as geometricMean,Le as hist,re as kurtosis,ge as mad,H as mean,ie as meanAD,x as median,se as modes,z as pretty,$ as prod,F as quantile,L as range,I as rank,fe as scale,v as sd,ne as skewness,Z as sum,le as table,ce as tabulate,ue as unique,G as variance,W as weightedMean};
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;