@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,117 @@
|
|
|
1
|
+
/** Result of {@link polychor} and {@link polyserial}. */
|
|
2
|
+
export interface PolycorResult {
|
|
3
|
+
/** The correlation (`NaN` where polycor returns NA). */
|
|
4
|
+
rho: number;
|
|
5
|
+
/** polycor's warnings, in order. */
|
|
6
|
+
warnings: string[];
|
|
7
|
+
}
|
|
8
|
+
/** Options of {@link polychor} and {@link polyserial}. */
|
|
9
|
+
export interface PolycorOptions {
|
|
10
|
+
/**
|
|
11
|
+
* Estimate the correlation and the thresholds together by maximum likelihood (polycor's `ML = TRUE`), instead of
|
|
12
|
+
* the two-step estimate. Default `false`.
|
|
13
|
+
*/
|
|
14
|
+
ML?: boolean;
|
|
15
|
+
/**
|
|
16
|
+
* Also return the variances of the estimates, the chi-square test of bivariate normality and the thresholds
|
|
17
|
+
* (polycor's `std.err = TRUE`). Without `ML`, the correlation is the maximum-likelihood one given the two-step
|
|
18
|
+
* thresholds. Default `false`.
|
|
19
|
+
*/
|
|
20
|
+
stdErr?: boolean;
|
|
21
|
+
}
|
|
22
|
+
/** Result of {@link polychor} with `stdErr`. */
|
|
23
|
+
export interface PolychorStdErrResult extends PolycorResult {
|
|
24
|
+
/**
|
|
25
|
+
* Variances and covariances of the estimates (the inverse of the negative Hessian of the log-likelihood at the
|
|
26
|
+
* maximum), in the order rho, the row thresholds, the column thresholds; 1 × 1 (rho alone) without `ML`.
|
|
27
|
+
*/
|
|
28
|
+
var: number[][];
|
|
29
|
+
/** Chi-square statistic of the test of bivariate normality. */
|
|
30
|
+
chisq: number;
|
|
31
|
+
/** Its degrees of freedom, r c − r − c. */
|
|
32
|
+
df: number;
|
|
33
|
+
/** The number of observations (the total of the table). */
|
|
34
|
+
n: number;
|
|
35
|
+
/** The row thresholds (the estimates with `ML`, the two-step ones otherwise). */
|
|
36
|
+
rowCuts: number[];
|
|
37
|
+
/** The column thresholds. */
|
|
38
|
+
colCuts: number[];
|
|
39
|
+
}
|
|
40
|
+
/** Result of {@link polyserial} with `stdErr`. */
|
|
41
|
+
export interface PolyserialStdErrResult extends PolycorResult {
|
|
42
|
+
/** Variances and covariances of the estimates, in the order rho, the thresholds; 1 × 1 (rho alone) without `ML`. */
|
|
43
|
+
var: number[][];
|
|
44
|
+
/** Chi-square statistic of the test of bivariate normality (polycor's, on a binned table). */
|
|
45
|
+
chisq: number;
|
|
46
|
+
/** Its degrees of freedom, 3 s − 1 for s categories. */
|
|
47
|
+
df: number;
|
|
48
|
+
/** The number of observations used. */
|
|
49
|
+
n: number;
|
|
50
|
+
/** The thresholds of the ordinal variable (the estimates with `ML`, the two-step ones otherwise). */
|
|
51
|
+
cuts: number[];
|
|
52
|
+
}
|
|
53
|
+
type Table = readonly (readonly number[])[];
|
|
54
|
+
/**
|
|
55
|
+
* Polychoric correlation of two ordinal variables. By default the two-step estimate: thresholds from the margins,
|
|
56
|
+
* then the maximum-likelihood correlation given them. Equivalent to polycor's `polychor(x, y)` or `polychor(table)`.
|
|
57
|
+
*
|
|
58
|
+
* Given `x` and `y`, the table has the sorted distinct values of `x` as rows and those of `y` as columns (pairs with
|
|
59
|
+
* a missing value are not counted). Rows and columns with a zero margin are removed with a warning; with fewer than
|
|
60
|
+
* two rows or columns left, `rho` is `NaN` (and the result has no other fields).
|
|
61
|
+
*
|
|
62
|
+
* With `ML`, the correlation and the thresholds are estimated together by maximum likelihood; with `stdErr`, the
|
|
63
|
+
* result also has their variances, the chi-square test of bivariate normality and the thresholds (with `stdErr`
|
|
64
|
+
* alone, the correlation is maximised given the two-step thresholds). The exact maximum is returned (R's optimisers
|
|
65
|
+
* stop about 1e-4 short of it). If the likelihood increases up to |rho| = 0.9999, `rho` is ±0.9999 with a warning.
|
|
66
|
+
*
|
|
67
|
+
* @param table - A contingency table (array of rows of counts).
|
|
68
|
+
* @param options - `ML` and `stdErr` (see {@link PolycorOptions}).
|
|
69
|
+
*
|
|
70
|
+
* @example
|
|
71
|
+
* ```ts
|
|
72
|
+
* polychor([[20, 8, 1], [5, 30, 9], [2, 6, 25]]).rho; // 0.785882312445335
|
|
73
|
+
* polychor([[20, 8, 1], [5, 30, 9], [2, 6, 25]], { ML: true }).rho; // 0.7911463316235798
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
export declare function polychor(table: Table, options: PolycorOptions & {
|
|
77
|
+
stdErr: true;
|
|
78
|
+
}): PolychorStdErrResult;
|
|
79
|
+
export declare function polychor(table: Table, options?: PolycorOptions): PolycorResult;
|
|
80
|
+
/**
|
|
81
|
+
* Polychoric correlation of two ordinal variables given as vectors of category codes (see the table form).
|
|
82
|
+
*
|
|
83
|
+
* @param x - Categories of the first variable.
|
|
84
|
+
* @param y - Categories of the second variable, the same length.
|
|
85
|
+
* @param options - `ML` and `stdErr` (see {@link PolycorOptions}).
|
|
86
|
+
*/
|
|
87
|
+
export declare function polychor(x: readonly number[], y: readonly number[], options: PolycorOptions & {
|
|
88
|
+
stdErr: true;
|
|
89
|
+
}): PolychorStdErrResult;
|
|
90
|
+
export declare function polychor(x: readonly number[], y: readonly number[], options?: PolycorOptions): PolycorResult;
|
|
91
|
+
/**
|
|
92
|
+
* Polyserial correlation of a numeric variable and an ordinal one. By default the two-step (ad hoc) estimate.
|
|
93
|
+
* Equivalent to polycor's `polyserial(x, y)`.
|
|
94
|
+
*
|
|
95
|
+
* Pairs with a missing value are dropped. The categories of `y` are its sorted distinct values, coded 1, 2, ...;
|
|
96
|
+
* with fewer than two, `rho` is `NaN` (and the result has no other fields). A two-step estimate beyond ±0.9999 is set
|
|
97
|
+
* to ±0.9999 with a warning.
|
|
98
|
+
*
|
|
99
|
+
* With `ML`, the correlation and the thresholds are estimated together by maximum likelihood; with `stdErr`, the
|
|
100
|
+
* result also has their variances, polycor's chi-square test of bivariate normality and the thresholds (with `stdErr`
|
|
101
|
+
* alone, the correlation is maximised given the two-step thresholds). The exact maximum is returned (R's optimisers
|
|
102
|
+
* stop about 1e-4 short of it). If the likelihood increases up to |rho| = 0.9999, `rho` is ±0.9999 with a warning.
|
|
103
|
+
*
|
|
104
|
+
* @param x - The numeric variable.
|
|
105
|
+
* @param y - Categories of the ordinal variable, the same length.
|
|
106
|
+
* @param options - `ML` and `stdErr` (see {@link PolycorOptions}).
|
|
107
|
+
*
|
|
108
|
+
* @example
|
|
109
|
+
* ```ts
|
|
110
|
+
* polyserial([0.2, -1.1, 0.8, 1.5, -0.3, 0.1, -0.9, 2.0], [1, 1, 2, 3, 2, 2, 1, 2]).rho; // 0.8085111526489707
|
|
111
|
+
* ```
|
|
112
|
+
*/
|
|
113
|
+
export declare function polyserial(x: readonly number[], y: readonly number[], options: PolycorOptions & {
|
|
114
|
+
stdErr: true;
|
|
115
|
+
}): PolyserialStdErrResult;
|
|
116
|
+
export declare function polyserial(x: readonly number[], y: readonly number[], options?: PolycorOptions): PolycorResult;
|
|
117
|
+
export {};
|
|
@@ -0,0 +1,468 @@
|
|
|
1
|
+
// Polychoric and polyserial correlations (polycor's polychor and polyserial): the two-step estimates (the defaults
|
|
2
|
+
// ML = FALSE, std.err = FALSE), the maximum-likelihood estimates (ML = TRUE) and the standard errors (std.err = TRUE).
|
|
3
|
+
//
|
|
4
|
+
// Written for rStats.js from oracle/polycor-behaviour.md (no ported code; the source of polycor and mvtnorm was not
|
|
5
|
+
// read). Polychoric: the thresholds are the normal quantiles of the cumulative margins, and rho minimises the
|
|
6
|
+
// negative log-likelihood of the table under a bivariate normal cut at those thresholds (cell probabilities from
|
|
7
|
+
// pbvnorm), by Brent's method on [−0.9999, 0.9999]. Polyserial: the ad hoc estimate from the correlation of x with the
|
|
8
|
+
// category codes, scaled by the normal densities at the thresholds.
|
|
9
|
+
//
|
|
10
|
+
// With ML or stdErr, the likelihood is maximised exactly (R's optimisers stop about 1e-4 short of the maximum): by
|
|
11
|
+
// Newton's method from the two-step values with the analytic gradient and Hessian of the log-likelihood, halving the
|
|
12
|
+
// step while the log-likelihood decreases. The variances are the inverse of the negative analytic Hessian at the
|
|
13
|
+
// maximum. The polychoric chi-square is evaluated so that the saturated tables (where it is a few times 1e-6) keep
|
|
14
|
+
// their relative accuracy: with ε = N P / n − 1 per cell, Σ n log(n / (N P)) = Σ n (ε − log(1 + ε)) + N Σ P over the
|
|
15
|
+
// empty cells, since the probabilities add up to 1.
|
|
16
|
+
import { pbvnorm } from "../distributions/bvnorm.js";
|
|
17
|
+
import { dnorm, pnorm, qnorm } from "../distributions/normal.js";
|
|
18
|
+
import { pearsonDD } from "./cor.js";
|
|
19
|
+
import { mean, sum, variance } from "../internal/summary.js";
|
|
20
|
+
import { optimize } from "../numerics/integrate.js";
|
|
21
|
+
import { solve } from "../linalg/solve.js";
|
|
22
|
+
import { formatR } from "./core/simulate.js";
|
|
23
|
+
const BOUND = 0.9999;
|
|
24
|
+
/** Normal quantiles of the cumulative proportions of the counts, without the last (which would be +Inf) */
|
|
25
|
+
function thresholds(counts) {
|
|
26
|
+
const n = sum(counts);
|
|
27
|
+
const out = [];
|
|
28
|
+
let c = 0;
|
|
29
|
+
for (let i = 0; i < counts.length - 1; i++) {
|
|
30
|
+
c += counts[i];
|
|
31
|
+
out.push(qnorm(c / n));
|
|
32
|
+
}
|
|
33
|
+
return out;
|
|
34
|
+
}
|
|
35
|
+
const sortedDistinct = (v) => [...new Set(v)].sort((a, b) => a - b);
|
|
36
|
+
/** "1 row with zero marginal removed", "2 rows with zero marginals removed" */
|
|
37
|
+
const removedWarning = (k, what) => k === 1 ? `1 ${what} with zero marginal removed` : `${k} ${what}s with zero marginals removed`;
|
|
38
|
+
const isVector = (v) => Array.isArray(v) || ArrayBuffer.isView(v);
|
|
39
|
+
/** Φ(hi) − Φ(lo) for lo ≤ hi, from the upper tails when both are positive (no cancellation near 1) */
|
|
40
|
+
const normalInterval = (lo, hi) => lo > 0 ? pnorm(lo, { lowerTail: false }) - pnorm(hi, { lowerTail: false }) : pnorm(hi) - pnorm(lo);
|
|
41
|
+
/** v standardised to mean 0 and sample standard deviation 1 */
|
|
42
|
+
function standardise(v) {
|
|
43
|
+
const m = mean(v);
|
|
44
|
+
const centred = v.map((x) => x - m);
|
|
45
|
+
const sd = Math.sqrt(variance(centred));
|
|
46
|
+
return centred.map((x) => x / sd);
|
|
47
|
+
}
|
|
48
|
+
/** ε − log(1 + ε) without cancellation for small ε */
|
|
49
|
+
function excessOverLog1p(e) {
|
|
50
|
+
if (Math.abs(e) >= 0.1)
|
|
51
|
+
return e - Math.log1p(e);
|
|
52
|
+
let term = e;
|
|
53
|
+
let total = 0;
|
|
54
|
+
for (let k = 2; k < 40; k++) {
|
|
55
|
+
term *= -e;
|
|
56
|
+
const add = term / k;
|
|
57
|
+
total += add;
|
|
58
|
+
if (Math.abs(add) <= 1e-17 * Math.abs(total))
|
|
59
|
+
break;
|
|
60
|
+
}
|
|
61
|
+
return -total;
|
|
62
|
+
}
|
|
63
|
+
const zeroMatrix = (p) => Array.from({ length: p }, () => new Array(p).fill(0));
|
|
64
|
+
/** Adds the log of a probability with the given gradient and Hessian, n times, to the log-likelihood */
|
|
65
|
+
function addLogTerm(acc, n, p, grad, hess) {
|
|
66
|
+
acc.value += n * Math.log(p);
|
|
67
|
+
const k = grad.length;
|
|
68
|
+
for (let a = 0; a < k; a++) {
|
|
69
|
+
acc.gradient[a] += (n * grad[a]) / p;
|
|
70
|
+
for (let b = 0; b < k; b++)
|
|
71
|
+
acc.hessian[a][b] += n * (hess[a][b] / p - (grad[a] * grad[b]) / (p * p));
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
const NO_DERIVATIVES = { r: 0, h: 0, k: 0, rr: 0, rh: 0, rk: 0, hh: 0, hk: 0, kk: 0 };
|
|
75
|
+
function cornerDerivatives(h, k, rho) {
|
|
76
|
+
if (h === -Infinity || k === -Infinity || (h === Infinity && k === Infinity))
|
|
77
|
+
return NO_DERIVATIVES;
|
|
78
|
+
if (h === Infinity)
|
|
79
|
+
return { ...NO_DERIVATIVES, k: dnorm(k), kk: -k * dnorm(k) };
|
|
80
|
+
if (k === Infinity)
|
|
81
|
+
return { ...NO_DERIVATIVES, h: dnorm(h), hh: -h * dnorm(h) };
|
|
82
|
+
const s2 = (1 - rho) * (1 + rho);
|
|
83
|
+
const s = Math.sqrt(s2);
|
|
84
|
+
const q = h * h - 2 * rho * h * k + k * k;
|
|
85
|
+
const density = Math.exp(-q / (2 * s2)) / (2 * Math.PI * s);
|
|
86
|
+
const u = (k - rho * h) / s;
|
|
87
|
+
const v = (h - rho * k) / s;
|
|
88
|
+
const dh = dnorm(h);
|
|
89
|
+
const dk = dnorm(k);
|
|
90
|
+
return {
|
|
91
|
+
r: density,
|
|
92
|
+
h: dh * pnorm(u),
|
|
93
|
+
k: dk * pnorm(v),
|
|
94
|
+
rr: density * (rho / s2 + (h * k * s2 - rho * q) / (s2 * s2)),
|
|
95
|
+
rh: (-density * (h - rho * k)) / s2,
|
|
96
|
+
rk: (-density * (k - rho * h)) / s2,
|
|
97
|
+
hh: -h * dh * pnorm(u) - (rho / s) * dh * dnorm(u),
|
|
98
|
+
hk: density,
|
|
99
|
+
kk: -k * dk * pnorm(v) - (rho / s) * dk * dnorm(v),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Log-likelihood of a contingency table under the bivariate normal cut at the thresholds (extended by ±Inf), with
|
|
104
|
+
* its derivatives in ρ alone, or in (ρ, the row thresholds, the column thresholds) with `freeCuts`.
|
|
105
|
+
*/
|
|
106
|
+
function polychoricLogLik(tab, rowCuts, colCuts, rho, freeCuts) {
|
|
107
|
+
const r = tab.length;
|
|
108
|
+
const c = tab[0].length;
|
|
109
|
+
const p = freeCuts ? r + c - 1 : 1;
|
|
110
|
+
const acc = { value: 0, gradient: new Array(p).fill(0), hessian: zeroMatrix(p) };
|
|
111
|
+
const rowParam = (i) => (freeCuts && i >= 1 && i <= r - 1 ? i : -1);
|
|
112
|
+
const colParam = (j) => (freeCuts && j >= 1 && j <= c - 1 ? r - 1 + j : -1);
|
|
113
|
+
const corners = rowCuts.map((h) => colCuts.map((k) => cornerDerivatives(h, k, rho)));
|
|
114
|
+
const terms = [];
|
|
115
|
+
for (let i = 0; i < r; i++) {
|
|
116
|
+
for (let j = 0; j < c; j++) {
|
|
117
|
+
const count = tab[i][j];
|
|
118
|
+
if (count === 0)
|
|
119
|
+
continue;
|
|
120
|
+
const prob = pbvnorm([rowCuts[i], colCuts[j]], [rowCuts[i + 1], colCuts[j + 1]], rho);
|
|
121
|
+
const grad = new Array(p).fill(0);
|
|
122
|
+
const hess = zeroMatrix(p);
|
|
123
|
+
for (const [ci, cj, sign] of [[i + 1, j + 1, 1], [i, j + 1, -1], [i + 1, j, -1], [i, j, 1]]) {
|
|
124
|
+
const d = corners[ci][cj];
|
|
125
|
+
const a = rowParam(ci);
|
|
126
|
+
const b = colParam(cj);
|
|
127
|
+
grad[0] += sign * d.r;
|
|
128
|
+
hess[0][0] += sign * d.rr;
|
|
129
|
+
if (a >= 0) {
|
|
130
|
+
grad[a] += sign * d.h;
|
|
131
|
+
hess[0][a] += sign * d.rh;
|
|
132
|
+
hess[a][0] += sign * d.rh;
|
|
133
|
+
hess[a][a] += sign * d.hh;
|
|
134
|
+
}
|
|
135
|
+
if (b >= 0) {
|
|
136
|
+
grad[b] += sign * d.k;
|
|
137
|
+
hess[0][b] += sign * d.rk;
|
|
138
|
+
hess[b][0] += sign * d.rk;
|
|
139
|
+
hess[b][b] += sign * d.kk;
|
|
140
|
+
}
|
|
141
|
+
if (a >= 0 && b >= 0) {
|
|
142
|
+
hess[a][b] += sign * d.hk;
|
|
143
|
+
hess[b][a] += sign * d.hk;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
addLogTerm(acc, count, prob, grad, hess);
|
|
147
|
+
terms.push(count * Math.log(prob));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
acc.value = sum(terms);
|
|
151
|
+
return acc;
|
|
152
|
+
}
|
|
153
|
+
/**
|
|
154
|
+
* Log-likelihood of the polyserial model: Σ_i [log φ(z_i) + log(Φ(τ_hi) − Φ(τ_lo))] with τ = (c − ρ z_i)/sqrt(1 − ρ²)
|
|
155
|
+
* at the thresholds around the category of observation i (0-based `category`), with its derivatives in ρ alone, or in
|
|
156
|
+
* (ρ, the thresholds) with `freeCuts`.
|
|
157
|
+
*/
|
|
158
|
+
function polyserialLogLik(z, category, cuts, rho, freeCuts) {
|
|
159
|
+
const p = freeCuts ? cuts.length + 1 : 1;
|
|
160
|
+
const acc = { value: 0, gradient: new Array(p).fill(0), hessian: zeroMatrix(p) };
|
|
161
|
+
const s2 = (1 - rho) * (1 + rho);
|
|
162
|
+
const s = Math.sqrt(s2);
|
|
163
|
+
const s3 = s2 * s;
|
|
164
|
+
const grad = new Array(p);
|
|
165
|
+
const hess = zeroMatrix(p);
|
|
166
|
+
const terms = [];
|
|
167
|
+
// adds sign × the derivatives of Φ(τ) at threshold index m (parameter m + 1)
|
|
168
|
+
const addBound = (m, zi, sign) => {
|
|
169
|
+
const c = cuts[m];
|
|
170
|
+
const t = (c - rho * zi) / s;
|
|
171
|
+
const dens = dnorm(t);
|
|
172
|
+
const tr = (rho * c - zi) / s3;
|
|
173
|
+
const tc = 1 / s;
|
|
174
|
+
const trr = c / s3 + (3 * rho * (rho * c - zi)) / (s3 * s2);
|
|
175
|
+
const trc = rho / s3;
|
|
176
|
+
grad[0] += sign * dens * tr;
|
|
177
|
+
hess[0][0] += sign * dens * (trr - t * tr * tr);
|
|
178
|
+
if (freeCuts) {
|
|
179
|
+
const a = m + 1;
|
|
180
|
+
grad[a] += sign * dens * tc;
|
|
181
|
+
const mixed = sign * dens * (trc - t * tr * tc);
|
|
182
|
+
hess[0][a] += mixed;
|
|
183
|
+
hess[a][0] += mixed;
|
|
184
|
+
hess[a][a] += sign * dens * (-t * tc * tc);
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
for (let i = 0; i < z.length; i++) {
|
|
188
|
+
const zi = z[i];
|
|
189
|
+
const j = category[i];
|
|
190
|
+
grad.fill(0);
|
|
191
|
+
for (const row of hess)
|
|
192
|
+
row.fill(0);
|
|
193
|
+
const hi = j < cuts.length ? (cuts[j] - rho * zi) / s : Infinity;
|
|
194
|
+
const lo = j > 0 ? (cuts[j - 1] - rho * zi) / s : -Infinity;
|
|
195
|
+
if (j < cuts.length)
|
|
196
|
+
addBound(j, zi, 1);
|
|
197
|
+
if (j > 0)
|
|
198
|
+
addBound(j - 1, zi, -1);
|
|
199
|
+
addLogTerm(acc, 1, normalInterval(lo, hi), grad, hess);
|
|
200
|
+
terms.push(Math.log(normalInterval(lo, hi)), dnorm(zi, { log: true }));
|
|
201
|
+
}
|
|
202
|
+
acc.value = sum(terms);
|
|
203
|
+
return acc;
|
|
204
|
+
}
|
|
205
|
+
/** Newton step (−H)⁻¹ g in the free parameters (0 elsewhere); gradient ascent scaled by the diagonal if not an ascent direction */
|
|
206
|
+
function newtonStep(at, free) {
|
|
207
|
+
const step = new Array(at.gradient.length).fill(0);
|
|
208
|
+
const g = free.map((a) => at.gradient[a]);
|
|
209
|
+
const negH = free.map((a) => free.map((b) => -at.hessian[a][b]));
|
|
210
|
+
let d;
|
|
211
|
+
try {
|
|
212
|
+
d = solve(negH, g);
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
d = undefined;
|
|
216
|
+
}
|
|
217
|
+
if (d === undefined || !d.every(Number.isFinite) || sum(d.map((v, k) => v * g[k])) <= 0) {
|
|
218
|
+
d = g.map((v, k) => v / Math.max(Math.abs(negH[k][k]), 1));
|
|
219
|
+
}
|
|
220
|
+
free.forEach((a, k) => (step[a] = d[k]));
|
|
221
|
+
return step;
|
|
222
|
+
}
|
|
223
|
+
/** The log-likelihood is no lower than `than`, up to its rounding */
|
|
224
|
+
const noLowerThan = (value, than) => value >= than - 1e-12 * Math.abs(than);
|
|
225
|
+
/**
|
|
226
|
+
* Newton iterations with step halving from theta, the correlation (first parameter) kept in [−0.9999, 0.9999] and
|
|
227
|
+
* fixed with `bounded`. Reaching the bound with the step pointing outwards fixes the correlation there.
|
|
228
|
+
*/
|
|
229
|
+
function newtonIterations(evaluate, start, startBounded) {
|
|
230
|
+
let theta = [...start];
|
|
231
|
+
let at = evaluate(theta);
|
|
232
|
+
let bounded = startBounded;
|
|
233
|
+
const all = theta.map((_, k) => k);
|
|
234
|
+
for (let iter = 0; iter < 200; iter++) {
|
|
235
|
+
const free = bounded ? all.slice(1) : all;
|
|
236
|
+
if (free.length === 0)
|
|
237
|
+
break;
|
|
238
|
+
const step = newtonStep(at, free);
|
|
239
|
+
if (!bounded && Math.abs(theta[0]) === BOUND && step[0] * theta[0] > 0) {
|
|
240
|
+
bounded = true;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
let scale = Math.abs(theta[0] + step[0]) > BOUND ? (Math.sign(step[0]) * BOUND - theta[0]) / step[0] : 1;
|
|
244
|
+
let accepted = false;
|
|
245
|
+
for (let halving = 0; halving < 60; halving++) {
|
|
246
|
+
const next = theta.map((v, k) => v + scale * step[k]);
|
|
247
|
+
if (scale * step[0] !== 0 && Math.abs(next[0]) >= BOUND * (1 - 1e-15))
|
|
248
|
+
next[0] = Math.sign(next[0]) * BOUND;
|
|
249
|
+
const nextAt = evaluate(next);
|
|
250
|
+
if (noLowerThan(nextAt.value, at.value)) {
|
|
251
|
+
const moved = Math.max(...next.map((v, k) => Math.abs(v - theta[k]) / Math.max(1, Math.abs(theta[k]))));
|
|
252
|
+
theta = next;
|
|
253
|
+
at = nextAt;
|
|
254
|
+
accepted = moved > 1e-12;
|
|
255
|
+
break;
|
|
256
|
+
}
|
|
257
|
+
scale /= 2;
|
|
258
|
+
}
|
|
259
|
+
if (!accepted)
|
|
260
|
+
break;
|
|
261
|
+
}
|
|
262
|
+
return { theta, at, bounded };
|
|
263
|
+
}
|
|
264
|
+
/**
|
|
265
|
+
* Maximises a log-likelihood whose first parameter is the correlation, kept in [−0.9999, 0.9999], by Newton's method
|
|
266
|
+
* with step halving. If the likelihood increases up to the bound, the correlation stays there (`bounded`) and the
|
|
267
|
+
* other parameters are maximised given it. Where the likelihood rises along a flat ridge towards the bound (cells
|
|
268
|
+
* whose probability goes to 0 have no cases), the iterations stall short of it: the point reached is compared with
|
|
269
|
+
* the maximum given the correlation at the bound on that side, and the bound is taken if it is no lower.
|
|
270
|
+
*/
|
|
271
|
+
function maximiseLogLik(evaluate, start) {
|
|
272
|
+
const found = newtonIterations(evaluate, [Math.max(-BOUND, Math.min(BOUND, start[0])), ...start.slice(1)], false);
|
|
273
|
+
if (found.bounded || found.theta[0] === 0)
|
|
274
|
+
return found;
|
|
275
|
+
const atBound = newtonIterations(evaluate, [Math.sign(found.theta[0]) * BOUND, ...found.theta.slice(1)], true);
|
|
276
|
+
return noLowerThan(atBound.at.value, found.at.value) ? atBound : found;
|
|
277
|
+
}
|
|
278
|
+
/** (−H)⁻¹, symmetrised; all infinite at the bound of the correlation (not a maximum, as R's 1 × 1 variance there) or where −H is singular */
|
|
279
|
+
function inverseNegHessian(hessian, bounded) {
|
|
280
|
+
const infinite = () => hessian.map((row) => row.map(() => Infinity));
|
|
281
|
+
if (bounded)
|
|
282
|
+
return infinite();
|
|
283
|
+
let inv;
|
|
284
|
+
try {
|
|
285
|
+
inv = solve(hessian.map((row) => row.map((v) => -v)));
|
|
286
|
+
}
|
|
287
|
+
catch {
|
|
288
|
+
return infinite();
|
|
289
|
+
}
|
|
290
|
+
return inv.map((row, a) => row.map((v, b) => (v + inv[b][a]) / 2));
|
|
291
|
+
}
|
|
292
|
+
const inadmissibleWarning = (rho) => `inadmissible correlation set to ${rho > 0 ? "0.9999" : "-0.9999"}`;
|
|
293
|
+
export function polychor(x, yOrOptions, maybeOptions) {
|
|
294
|
+
let tab;
|
|
295
|
+
let options;
|
|
296
|
+
if (!isVector(yOrOptions)) {
|
|
297
|
+
const t = x;
|
|
298
|
+
if (!t.every(isVector))
|
|
299
|
+
throw new TypeError("give a table (array of rows) or two vectors");
|
|
300
|
+
const k = t[0]?.length ?? 0;
|
|
301
|
+
if (t.some((r) => r.length !== k))
|
|
302
|
+
throw new TypeError("the table must have rows of equal length");
|
|
303
|
+
tab = t.map((r) => Array.from(r));
|
|
304
|
+
options = yOrOptions ?? {};
|
|
305
|
+
}
|
|
306
|
+
else {
|
|
307
|
+
const xs = x;
|
|
308
|
+
const y = yOrOptions;
|
|
309
|
+
if (xs.length !== y.length)
|
|
310
|
+
throw new RangeError("'x' and 'y' must have the same length");
|
|
311
|
+
const keep = xs.map((v, i) => !Number.isNaN(v) && !Number.isNaN(y[i]));
|
|
312
|
+
const xv = xs.filter((_, i) => keep[i]);
|
|
313
|
+
const yv = y.filter((_, i) => keep[i]);
|
|
314
|
+
const rows = new Map(sortedDistinct(xv).map((v, i) => [v, i]));
|
|
315
|
+
const cols = new Map(sortedDistinct(yv).map((v, j) => [v, j]));
|
|
316
|
+
tab = Array.from({ length: rows.size }, () => new Array(cols.size).fill(0));
|
|
317
|
+
xv.forEach((v, i) => tab[rows.get(v)][cols.get(yv[i])]++);
|
|
318
|
+
options = maybeOptions ?? {};
|
|
319
|
+
}
|
|
320
|
+
const { ML = false, stdErr = false } = options;
|
|
321
|
+
const warnings = [];
|
|
322
|
+
const rowSums = tab.map((r) => sum(r));
|
|
323
|
+
const zeroRows = rowSums.filter((s) => s === 0).length;
|
|
324
|
+
if (zeroRows > 0) {
|
|
325
|
+
warnings.push(removedWarning(zeroRows, "row"));
|
|
326
|
+
tab = tab.filter((_, i) => rowSums[i] !== 0);
|
|
327
|
+
}
|
|
328
|
+
const colSums = (tab[0] ?? []).map((_, j) => sum(tab.map((r) => r[j])));
|
|
329
|
+
const zeroCols = colSums.filter((s) => s === 0).length;
|
|
330
|
+
if (zeroCols > 0) {
|
|
331
|
+
warnings.push(removedWarning(zeroCols, "column"));
|
|
332
|
+
tab = tab.map((r) => r.filter((_, j) => colSums[j] !== 0));
|
|
333
|
+
}
|
|
334
|
+
const r = tab.length;
|
|
335
|
+
const c = tab[0]?.length ?? 0;
|
|
336
|
+
if (r < 2)
|
|
337
|
+
warnings.push("the table has fewer than 2 rows");
|
|
338
|
+
if (c < 2)
|
|
339
|
+
warnings.push("the table has fewer than 2 columns");
|
|
340
|
+
if (r < 2 || c < 2)
|
|
341
|
+
return { rho: NaN, warnings };
|
|
342
|
+
const rowCuts = [-Infinity, ...thresholds(tab.map((row) => sum(row))), Infinity];
|
|
343
|
+
const colCuts = [-Infinity, ...thresholds(tab[0].map((_, j) => sum(tab.map((row) => row[j])))), Infinity];
|
|
344
|
+
const negLogLik = (rho0) => {
|
|
345
|
+
const rho = Math.max(-BOUND, Math.min(BOUND, rho0));
|
|
346
|
+
const terms = [];
|
|
347
|
+
for (let i = 0; i < r; i++) {
|
|
348
|
+
for (let j = 0; j < c; j++) {
|
|
349
|
+
// an empty cell contributes 0, also where its probability underflows to 0
|
|
350
|
+
if (tab[i][j] === 0)
|
|
351
|
+
continue;
|
|
352
|
+
const p = pbvnorm([rowCuts[i], colCuts[j]], [rowCuts[i + 1], colCuts[j + 1]], rho);
|
|
353
|
+
terms.push(tab[i][j] * Math.log(p));
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
return -sum(terms);
|
|
357
|
+
};
|
|
358
|
+
const twoStep = optimize(negLogLik, -BOUND, BOUND).optimum;
|
|
359
|
+
if (!ML && !stdErr)
|
|
360
|
+
return { rho: twoStep, warnings };
|
|
361
|
+
// maximum likelihood: θ = (ρ, the inner row thresholds, the inner column thresholds) with ML, ρ alone otherwise
|
|
362
|
+
const extend = (cuts) => [-Infinity, ...cuts, Infinity];
|
|
363
|
+
const innerRow = rowCuts.slice(1, r);
|
|
364
|
+
const innerCol = colCuts.slice(1, c);
|
|
365
|
+
const evaluate = (theta) => ML
|
|
366
|
+
? polychoricLogLik(tab, extend(theta.slice(1, r)), extend(theta.slice(r)), theta[0], true)
|
|
367
|
+
: polychoricLogLik(tab, rowCuts, colCuts, theta[0], false);
|
|
368
|
+
const { theta, at, bounded } = maximiseLogLik(evaluate, ML ? [twoStep, ...innerRow, ...innerCol] : [twoStep]);
|
|
369
|
+
const rho = theta[0];
|
|
370
|
+
if (bounded)
|
|
371
|
+
warnings.push(inadmissibleWarning(rho));
|
|
372
|
+
if (!stdErr)
|
|
373
|
+
return { rho, warnings };
|
|
374
|
+
const fittedRow = ML ? extend(theta.slice(1, r)) : rowCuts;
|
|
375
|
+
const fittedCol = ML ? extend(theta.slice(r)) : colCuts;
|
|
376
|
+
const n = sum(tab.map((row) => sum(row)));
|
|
377
|
+
// chisq = 2 (−ℓ + Σ n_ij log((n_ij + 1e-6)/n)) = 2 Σ [n log(1 + 1e-6/n) + n (ε − log(1 + ε))] + 2 n Σ_{empty} P
|
|
378
|
+
const terms = [];
|
|
379
|
+
for (let i = 0; i < r; i++) {
|
|
380
|
+
for (let j = 0; j < c; j++) {
|
|
381
|
+
const count = tab[i][j];
|
|
382
|
+
const prob = pbvnorm([fittedRow[i], fittedCol[j]], [fittedRow[i + 1], fittedCol[j + 1]], rho);
|
|
383
|
+
if (count === 0)
|
|
384
|
+
terms.push(n * prob);
|
|
385
|
+
else
|
|
386
|
+
terms.push(count * Math.log1p(1e-6 / count), count * excessOverLog1p((n * prob) / count - 1));
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
return {
|
|
390
|
+
rho,
|
|
391
|
+
warnings,
|
|
392
|
+
var: inverseNegHessian(at.hessian, bounded),
|
|
393
|
+
chisq: 2 * sum(terms),
|
|
394
|
+
df: r * c - r - c,
|
|
395
|
+
n,
|
|
396
|
+
rowCuts: fittedRow.slice(1, r),
|
|
397
|
+
colCuts: fittedCol.slice(1, c),
|
|
398
|
+
};
|
|
399
|
+
}
|
|
400
|
+
/** polycor's chi-square for the polyserial model: the standardised codes and z binned, against the bivariate normal */
|
|
401
|
+
function polyserialChisq(codes, z, cuts, rho) {
|
|
402
|
+
const n = codes.length;
|
|
403
|
+
const quartiles = [qnorm(0.25), qnorm(0.5), qnorm(0.75)];
|
|
404
|
+
// classes of intervals closed on the right
|
|
405
|
+
const classOf = (v, bounds) => bounds.filter((b) => b < v).length;
|
|
406
|
+
const rowsBinned = standardise(codes).map((v) => classOf(v, cuts));
|
|
407
|
+
const colsBinned = standardise(z).map((v) => classOf(v, quartiles));
|
|
408
|
+
const counts = Array.from({ length: cuts.length + 1 }, () => new Array(4).fill(0));
|
|
409
|
+
rowsBinned.forEach((a, i) => counts[a][colsBinned[i]]++);
|
|
410
|
+
const rowBounds = [-Infinity, ...cuts, Infinity];
|
|
411
|
+
const colBounds = [-Infinity, ...quartiles, Infinity];
|
|
412
|
+
const terms = [];
|
|
413
|
+
counts.forEach((row, i) => row.forEach((count, j) => {
|
|
414
|
+
if (count === 0)
|
|
415
|
+
return;
|
|
416
|
+
const prob = pbvnorm([rowBounds[i], colBounds[j]], [rowBounds[i + 1], colBounds[j + 1]], rho);
|
|
417
|
+
terms.push(count * Math.log((count + 1e-6) / (prob * n)));
|
|
418
|
+
}));
|
|
419
|
+
return 2 * sum(terms);
|
|
420
|
+
}
|
|
421
|
+
export function polyserial(x, y, options = {}) {
|
|
422
|
+
if (x.length !== y.length)
|
|
423
|
+
throw new RangeError("'x' and 'y' must have the same length");
|
|
424
|
+
const { ML = false, stdErr = false } = options;
|
|
425
|
+
const keep = x.map((v, i) => !Number.isNaN(v) && !Number.isNaN(y[i]));
|
|
426
|
+
const xv = x.filter((_, i) => keep[i]);
|
|
427
|
+
const yv = y.filter((_, i) => keep[i]);
|
|
428
|
+
const n = xv.length;
|
|
429
|
+
const levels = sortedDistinct(yv);
|
|
430
|
+
if (levels.length < 2)
|
|
431
|
+
return { rho: NaN, warnings: ["y has fewer than 2 levels"] };
|
|
432
|
+
const code = new Map(levels.map((v, i) => [v, i + 1]));
|
|
433
|
+
const yc = yv.map((v) => code.get(v));
|
|
434
|
+
const counts = levels.map(() => 0);
|
|
435
|
+
for (const v of yc)
|
|
436
|
+
counts[v - 1]++;
|
|
437
|
+
const cuts = thresholds(counts);
|
|
438
|
+
const warnings = [];
|
|
439
|
+
let rho = (Math.sqrt((n - 1) / n) * Math.sqrt(variance(yc)) * pearsonDD(xv, yc)[0]) / sum(cuts.map((t) => dnorm(t)));
|
|
440
|
+
if (Math.abs(rho) > BOUND) {
|
|
441
|
+
const bounded = Math.sign(rho) * BOUND;
|
|
442
|
+
warnings.push(`initial correlation inadmissible, ${formatR(rho)}, set to ${formatR(bounded)}`);
|
|
443
|
+
rho = bounded;
|
|
444
|
+
}
|
|
445
|
+
if (!ML && !stdErr)
|
|
446
|
+
return { rho, warnings };
|
|
447
|
+
// maximum likelihood: θ = (ρ, the thresholds) with ML, ρ alone otherwise
|
|
448
|
+
const z = standardise(xv);
|
|
449
|
+
const category = yc.map((v) => v - 1);
|
|
450
|
+
const evaluate = (theta) => polyserialLogLik(z, category, ML ? theta.slice(1) : cuts, theta[0], ML);
|
|
451
|
+
const { theta, at, bounded } = maximiseLogLik(evaluate, ML ? [rho, ...cuts] : [rho]);
|
|
452
|
+
if (bounded)
|
|
453
|
+
warnings.push(inadmissibleWarning(theta[0]));
|
|
454
|
+
if (!stdErr)
|
|
455
|
+
return { rho: theta[0], warnings };
|
|
456
|
+
const fittedCuts = ML ? theta.slice(1) : cuts;
|
|
457
|
+
const s = levels.length;
|
|
458
|
+
return {
|
|
459
|
+
rho: theta[0],
|
|
460
|
+
warnings,
|
|
461
|
+
var: inverseNegHessian(at.hessian, bounded),
|
|
462
|
+
// at the estimates with ML, at the two-step values otherwise (as polycor)
|
|
463
|
+
chisq: polyserialChisq(yc, z, fittedCuts, ML ? theta[0] : rho),
|
|
464
|
+
df: 4 * s - s - 1,
|
|
465
|
+
n,
|
|
466
|
+
cuts: fittedCuts,
|
|
467
|
+
};
|
|
468
|
+
}
|