@numero-uno-jpn/rstats 0.15.2 → 0.16.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 +280 -0
- package/README.ja.md +40 -33
- package/README.md +36 -28
- package/dist/chunks/chunk-2D2IQWUQ.js +2 -0
- package/dist/chunks/chunk-5UQCRBAG.js +2 -0
- package/dist/chunks/chunk-6CSTWA5E.js +2 -0
- package/dist/chunks/chunk-72Y3HZID.js +2 -0
- package/dist/chunks/chunk-BG2KLEHM.js +2 -0
- package/dist/chunks/chunk-CMEKBNHQ.js +2 -0
- package/dist/chunks/chunk-FLJNSXSW.js +2 -0
- package/dist/chunks/chunk-GM53LWSR.js +2 -0
- package/dist/chunks/chunk-JBCA56ZS.js +3 -0
- package/dist/chunks/chunk-K3RJAD2T.js +2 -0
- package/dist/chunks/chunk-KAZRWIB5.js +2 -0
- package/dist/chunks/chunk-KBVVIMXX.js +3 -0
- package/dist/chunks/chunk-N3SIFCZX.js +2 -0
- package/dist/chunks/chunk-QNNL7AZ3.js +2 -0
- package/dist/chunks/chunk-SC6CV4Z3.js +2 -0
- package/dist/chunks/chunk-SYWOBOTR.js +2 -0
- package/dist/chunks/chunk-URIO5LY5.js +2 -0
- package/dist/chunks/chunk-VTUGG2SV.js +2 -0
- package/dist/chunks/chunk-W26LRYOJ.js +2 -0
- package/dist/chunks/chunk-XHETEYVC.js +2 -0
- package/dist/chunks/{chunk-PWVQVJTP.js → chunk-YRZWONZB.js} +1 -1
- package/dist/chunks/chunk-ZGABZMWX.js +2 -0
- package/dist/data/grouping.js +20 -5
- package/dist/descriptive/basic.js +90 -8
- package/dist/descriptive/cov.js +12 -4
- package/dist/descriptive/dataFrames.d.ts +4 -2
- package/dist/descriptive/dataFrames.js +56 -18
- package/dist/descriptive/factanal.js +16 -7
- package/dist/descriptive/hist.d.ts +8 -5
- package/dist/descriptive/hist.js +71 -31
- package/dist/descriptive/missing.js +3 -1
- package/dist/descriptive/moments.js +72 -19
- package/dist/descriptive/omega.d.ts +1 -1
- package/dist/descriptive/omega.js +68 -9
- package/dist/descriptive/pivot.d.ts +21 -9
- package/dist/descriptive/pivot.js +161 -35
- package/dist/descriptive/quantile.js +2 -1
- package/dist/descriptive/rank.js +4 -1
- package/dist/descriptive/table.d.ts +3 -2
- package/dist/descriptive/table.js +24 -9
- package/dist/descriptive.js +2 -2
- package/dist/distributions/arcsine.js +19 -2
- package/dist/distributions/beta.js +35 -5
- package/dist/distributions/binomial.js +37 -14
- package/dist/distributions/bvnorm.js +11 -2
- package/dist/distributions/cauchy.js +87 -8
- package/dist/distributions/chisq.js +7 -3
- package/dist/distributions/exponential.js +11 -1
- package/dist/distributions/f.js +73 -22
- package/dist/distributions/gamma.js +61 -6
- package/dist/distributions/geometric.js +53 -14
- package/dist/distributions/hypergeometric.d.ts +5 -1
- package/dist/distributions/hypergeometric.js +93 -6
- package/dist/distributions/invgamma.js +6 -1
- package/dist/distributions/kumaraswamy.js +22 -4
- package/dist/distributions/laplace.js +31 -7
- package/dist/distributions/logistic.js +11 -2
- package/dist/distributions/lognormal.js +20 -3
- package/dist/distributions/multinomial.js +54 -11
- package/dist/distributions/nbeta.js +128 -35
- package/dist/distributions/nchisq.js +85 -14
- package/dist/distributions/negbinomial.js +100 -18
- package/dist/distributions/normal.js +35 -5
- package/dist/distributions/nt.d.ts +28 -3
- package/dist/distributions/nt.js +536 -35
- package/dist/distributions/pareto.js +9 -1
- package/dist/distributions/poisson.js +28 -3
- package/dist/distributions/signrank.js +7 -4
- package/dist/distributions/summary.js +450 -60
- package/dist/distributions/t.js +55 -3
- package/dist/distributions/triangular.js +45 -13
- package/dist/distributions/tukey.js +21 -2
- package/dist/distributions/uniform.js +2 -0
- package/dist/distributions/weibull.js +33 -3
- package/dist/distributions/wilcox.d.ts +9 -3
- package/dist/distributions/wilcox.js +155 -26
- package/dist/distributions.js +2 -2
- package/dist/htest/agreement.d.ts +3 -2
- package/dist/htest/agreement.js +76 -14
- package/dist/htest/ansariTest.d.ts +6 -1
- package/dist/htest/ansariTest.js +75 -8
- package/dist/htest/aov.d.ts +1 -1
- package/dist/htest/aov.js +48 -34
- package/dist/htest/binomTest.d.ts +5 -0
- package/dist/htest/binomTest.js +41 -17
- package/dist/htest/brunnerMunzelTest.d.ts +4 -3
- package/dist/htest/brunnerMunzelTest.js +7 -5
- package/dist/htest/chisqTest.d.ts +2 -1
- package/dist/htest/chisqTest.js +130 -43
- package/dist/htest/cor.d.ts +2 -1
- package/dist/htest/cor.js +17 -19
- package/dist/htest/core/ansari.d.ts +9 -0
- package/dist/htest/core/ansari.js +21 -1
- package/dist/htest/core/kolmogorov.d.ts +25 -0
- package/dist/htest/core/kolmogorov.js +123 -0
- package/dist/htest/core/mantelhaen.js +6 -4
- package/dist/htest/core/shapiro.d.ts +1 -1
- package/dist/htest/core/shapiro.js +5 -1
- package/dist/htest/dunnett.js +14 -5
- package/dist/htest/effectSize.d.ts +2 -0
- package/dist/htest/effectSize.js +91 -29
- package/dist/htest/fisherTest.d.ts +2 -2
- package/dist/htest/fisherTest.js +36 -18
- package/dist/htest/groups.d.ts +7 -0
- package/dist/htest/groups.js +21 -4
- package/dist/htest/ksTest.d.ts +3 -1
- package/dist/htest/ksTest.js +23 -2
- package/dist/htest/leveneTest.js +19 -3
- package/dist/htest/mantelhaenTest.js +125 -25
- package/dist/htest/mcnemarTest.js +32 -11
- package/dist/htest/multipleComparisons.d.ts +8 -1
- package/dist/htest/multipleComparisons.js +44 -21
- package/dist/htest/normalityTests.js +44 -10
- package/dist/htest/onewayTest.js +96 -5
- package/dist/htest/pAdjust.d.ts +3 -2
- package/dist/htest/pAdjust.js +38 -6
- package/dist/htest/pairwise.d.ts +1 -1
- package/dist/htest/pairwise.js +17 -15
- package/dist/htest/poissonTest.d.ts +1 -1
- package/dist/htest/poissonTest.js +111 -59
- package/dist/htest/polycor.js +27 -7
- package/dist/htest/power.d.ts +11 -1
- package/dist/htest/power.js +112 -8
- package/dist/htest/propTest.js +21 -4
- package/dist/htest/pwr.js +121 -24
- package/dist/htest/rankTests.js +29 -5
- package/dist/htest/tTest.js +44 -21
- package/dist/htest/trendTests.d.ts +7 -3
- package/dist/htest/trendTests.js +114 -20
- package/dist/htest/types.d.ts +5 -0
- package/dist/htest/types.js +7 -0
- package/dist/htest/varTest.js +45 -14
- package/dist/htest/wilcoxTest.js +114 -21
- package/dist/integrate/quadpack.js +27 -5
- package/dist/internal/covmat.d.ts +5 -0
- package/dist/internal/covmat.js +20 -0
- package/dist/internal/ddexp.d.ts +23 -1
- package/dist/internal/ddexp.js +86 -6
- package/dist/internal/discrete.d.ts +14 -0
- package/dist/internal/discrete.js +78 -5
- package/dist/internal/extremes.d.ts +9 -0
- package/dist/internal/extremes.js +24 -0
- package/dist/internal/fround.js +13 -4
- package/dist/internal/integer.d.ts +9 -0
- package/dist/internal/integer.js +12 -0
- package/dist/internal/invert.d.ts +5 -0
- package/dist/internal/invert.js +25 -7
- package/dist/internal/noncentral.d.ts +7 -0
- package/dist/internal/noncentral.js +9 -0
- package/dist/internal/poissonMixture.js +29 -6
- package/dist/internal/scaledInverse.d.ts +10 -0
- package/dist/internal/scaledInverse.js +22 -0
- package/dist/internal/seq.js +15 -2
- package/dist/internal/summary.d.ts +90 -0
- package/dist/internal/summary.js +458 -39
- package/dist/internal/uniroot.d.ts +7 -0
- package/dist/internal/uniroot.js +28 -3
- package/dist/linalg/basic.d.ts +3 -1
- package/dist/linalg/basic.js +51 -7
- package/dist/linalg/chol.js +4 -1
- package/dist/linalg/dot.d.ts +29 -0
- package/dist/linalg/dot.js +132 -0
- package/dist/linalg/eigen.d.ts +6 -1
- package/dist/linalg/eigen.js +71 -14
- package/dist/linalg/expm.d.ts +3 -2
- package/dist/linalg/expm.js +109 -15
- package/dist/linalg/kappa.js +58 -10
- package/dist/linalg/lu.d.ts +2 -1
- package/dist/linalg/lu.js +35 -5
- package/dist/linalg/matrix.d.ts +14 -0
- package/dist/linalg/matrix.js +24 -0
- package/dist/linalg/ops.js +60 -13
- package/dist/linalg/qr.d.ts +2 -1
- package/dist/linalg/qr.js +91 -23
- package/dist/linalg/schur.js +11 -3
- package/dist/linalg/solve.d.ts +6 -1
- package/dist/linalg/solve.js +147 -26
- package/dist/linalg/svd.d.ts +9 -2
- package/dist/linalg/svd.js +29 -11
- package/dist/linalg.js +2 -2
- package/dist/mixed.js +4 -4
- package/dist/models/anovaSequential.d.ts +16 -1
- package/dist/models/anovaSequential.js +124 -25
- package/dist/models/aovEz.js +140 -30
- package/dist/models/aovStrata.js +55 -22
- package/dist/models/carAnova.d.ts +1 -1
- package/dist/models/carAnova.js +83 -32
- package/dist/models/coxph.js +148 -66
- package/dist/models/estimable.d.ts +15 -0
- package/dist/models/estimable.js +68 -0
- package/dist/models/formula.d.ts +1 -1
- package/dist/models/formula.js +26 -8
- package/dist/models/glm.d.ts +35 -5
- package/dist/models/glm.js +398 -55
- package/dist/models/glmAnova.js +84 -13
- package/dist/models/glmConfint.d.ts +1 -1
- package/dist/models/glmConfint.js +115 -27
- package/dist/models/glmFamily.d.ts +10 -0
- package/dist/models/glmFamily.js +244 -40
- package/dist/models/lm.d.ts +12 -1
- package/dist/models/lm.js +235 -36
- package/dist/models/lmer.d.ts +20 -1
- package/dist/models/lmer.js +109 -27
- package/dist/models/lmerAnova.js +37 -4
- package/dist/models/lmerHypotheses.d.ts +6 -2
- package/dist/models/lmerHypotheses.js +14 -2
- package/dist/models/lmerTest.d.ts +9 -2
- package/dist/models/lmerTest.js +64 -19
- package/dist/models/mauchly.d.ts +4 -1
- package/dist/models/mauchly.js +34 -13
- package/dist/models/mixedStructure.js +6 -0
- package/dist/models/modelFrame.js +8 -2
- package/dist/models/modelMatrix.d.ts +3 -1
- package/dist/models/modelMatrix.js +40 -15
- package/dist/models/scaledTables.d.ts +8 -0
- package/dist/models/scaledTables.js +6 -0
- package/dist/models/survival.d.ts +6 -1
- package/dist/models/survival.js +67 -27
- package/dist/models/tiedTimes.d.ts +2 -0
- package/dist/models/tiedTimes.js +34 -0
- package/dist/numerics/deriv.d.ts +1 -1
- package/dist/numerics/deriv.js +64 -8
- package/dist/numerics/integrate.d.ts +9 -1
- package/dist/numerics/integrate.js +103 -16
- package/dist/numerics/interp.d.ts +8 -2
- package/dist/numerics/interp.js +352 -50
- package/dist/numerics/ode.js +55 -1
- package/dist/numerics.js +2 -2
- package/dist/optim/localmin.js +4 -0
- package/dist/optim/optim.d.ts +3 -1
- package/dist/optim/optim.js +80 -8
- package/dist/random/beta.js +53 -4
- package/dist/random/binomial.d.ts +14 -3
- package/dist/random/binomial.js +59 -24
- package/dist/random/continuous.js +33 -5
- package/dist/random/extra.js +42 -9
- package/dist/random/gamma.d.ts +4 -1
- package/dist/random/gamma.js +36 -8
- package/dist/random/hyper.js +9 -6
- package/dist/random/mt.js +17 -2
- package/dist/random/poisson.js +26 -3
- package/dist/random/r2dtable.d.ts +8 -1
- package/dist/random/r2dtable.js +24 -3
- package/dist/random/rank.d.ts +2 -0
- package/dist/random/rank.js +44 -4
- package/dist/random/sample.d.ts +12 -2
- package/dist/random/sample.js +57 -20
- package/dist/random/streams.js +4 -2
- package/dist/rstats.js +14 -14
- package/dist/special/besselIK.d.ts +12 -0
- package/dist/special/besselIK.js +168 -23
- package/dist/special/besselJY.d.ts +11 -1
- package/dist/special/besselJY.js +127 -19
- package/dist/special/besselSeries.d.ts +27 -0
- package/dist/special/besselSeries.js +45 -2
- package/dist/special/beta.js +11 -1
- package/dist/special/choose.js +17 -8
- package/dist/special/dd.js +122 -18
- package/dist/special/extra.js +14 -2
- package/dist/special/gamma.js +15 -2
- package/dist/special/igam.js +33 -6
- package/dist/special/incbet.js +100 -10
- package/dist/special/incbetLargeA.js +7 -2
- package/dist/special/incbetPrefactor.d.ts +5 -0
- package/dist/special/incbetPrefactor.js +14 -3
- package/dist/special/incbetTemme.d.ts +7 -0
- package/dist/special/incbetTemme.js +45 -12
- package/dist/special/loader.d.ts +1 -1
- package/dist/special/loader.js +179 -33
- package/dist/special/log1pmx.js +4 -0
- package/dist/special.js +2 -2
- package/dist/tests.js +11 -11
- package/llms.txt +12 -6
- package/package.json +1 -1
- package/dist/chunks/chunk-2CUKVVRO.js +0 -2
- package/dist/chunks/chunk-3WQCKGKP.js +0 -2
- package/dist/chunks/chunk-4Z2XDWKV.js +0 -2
- package/dist/chunks/chunk-AJBLCNZ7.js +0 -3
- package/dist/chunks/chunk-D4F7GQAY.js +0 -2
- package/dist/chunks/chunk-EBQMGCQZ.js +0 -2
- package/dist/chunks/chunk-HBMHR5SS.js +0 -2
- package/dist/chunks/chunk-IBPWRQIF.js +0 -2
- package/dist/chunks/chunk-JLAH3X77.js +0 -2
- package/dist/chunks/chunk-LG74QY5U.js +0 -2
- package/dist/chunks/chunk-PEYGUK32.js +0 -2
- package/dist/chunks/chunk-Q4PGYESP.js +0 -2
- package/dist/chunks/chunk-RCAL4VHM.js +0 -3
- package/dist/chunks/chunk-SREPSVTT.js +0 -2
- package/dist/chunks/chunk-UFT662QZ.js +0 -2
- package/dist/chunks/chunk-VWJ74UHC.js +0 -2
- package/dist/chunks/chunk-XNPU54NH.js +0 -2
- package/dist/chunks/chunk-XPLDEK6D.js +0 -2
- package/dist/chunks/chunk-YGT4P7EU.js +0 -2
- package/dist/chunks/chunk-YVREYVI2.js +0 -2
package/dist/htest/chisqTest.js
CHANGED
|
@@ -8,20 +8,21 @@
|
|
|
8
8
|
// for all cells, min(0.5, min |O - E|) (from R's output; scipy uses min(0.5, |O - E|) per cell).
|
|
9
9
|
// If that amount is 0, the result is labelled as uncorrected
|
|
10
10
|
// - A matrix with a single row or column becomes a goodness-of-fit test
|
|
11
|
-
// -
|
|
12
|
-
// 1-
|
|
13
|
-
// Fractional counts are accepted in both cases
|
|
11
|
+
// - Counts that are negative, NaN or Inf are errors in every shape (R lets Inf through in a vector or a 1-row or
|
|
12
|
+
// 1-column matrix and returns NaN; docs, "Inputs without meaning"). Fractional counts are accepted
|
|
14
13
|
// - Sums are taken in double-double (R's sum accumulates in extended precision)
|
|
15
14
|
// - Simulated p-values (Hope 1968; R's documented behaviour): (1 + #{simulated statistics >= (1 - 64 eps) times the
|
|
16
|
-
// observed one}) / (B + 1). Goodness of fit draws the B samples of size n = sum(x) at
|
|
17
|
-
// sample.int with prob) and counts them n at a time; contingency tables are drawn with Patefield's algorithm
|
|
15
|
+
// observed one}) / (B + 1). Goodness of fit draws the B samples of size n = sum(x) one at a time (the uniforms of
|
|
16
|
+
// R's sample.int with prob) and counts them n at a time; contingency tables are drawn with Patefield's algorithm
|
|
18
17
|
// (src/random/r2dtable.ts). The statistic is then the uncorrected one, and the parameter is NaN (R's NA). Tables
|
|
19
18
|
// with a zero margin are not simulated (ordinary test), as in R
|
|
20
19
|
// - Two factor vectors: the table of the complete pairs, with the distinct values sorted by code point (C locale)
|
|
21
20
|
import { pgamma1 } from "../distributions/gamma.js";
|
|
22
|
-
import { logFactorialTable, rcont2 } from "../random/r2dtable.js";
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
21
|
+
import { logFactorialTable, MAX_TABLE_TOTAL, rcont2 } from "../random/r2dtable.js";
|
|
22
|
+
import { sampleIntReplaceDrawer } from "../random/sample.js";
|
|
23
|
+
import { ldexp, productOver, squareOver } from "../internal/summary.js";
|
|
24
|
+
import { compareCodePoints } from "../models/modelFrame.js";
|
|
25
|
+
import { ddAdd, ddDiv, ddMul, ddSub } from "../special/dd.js";
|
|
25
26
|
import { simulatedMethod } from "./core/simulate.js";
|
|
26
27
|
/** Sum (accumulated in double-double, then rounded; with Inf present, the double sum = ±Inf or NaN) */
|
|
27
28
|
function ddSum(x) {
|
|
@@ -38,8 +39,6 @@ export function chisqTest(x, yOrOptions, maybeOptions) {
|
|
|
38
39
|
return chisqFactors(x, yOrOptions, maybeOptions ?? {});
|
|
39
40
|
return chisqCounts(x, yOrOptions ?? {});
|
|
40
41
|
}
|
|
41
|
-
/** Code-point order (the C locale) */
|
|
42
|
-
const byCodePoint = (a, b) => (a < b ? -1 : a > b ? 1 : 0);
|
|
43
42
|
function chisqFactors(x, y, options) {
|
|
44
43
|
if (x.length !== y.length)
|
|
45
44
|
throw new RangeError("'x' and 'y' must have the same length");
|
|
@@ -57,8 +56,8 @@ function chisqFactors(x, y, options) {
|
|
|
57
56
|
ys.push(w);
|
|
58
57
|
}
|
|
59
58
|
});
|
|
60
|
-
const rowLevels = [...new Set(xs)].sort(
|
|
61
|
-
const colLevels = [...new Set(ys)].sort(
|
|
59
|
+
const rowLevels = [...new Set(xs)].sort(compareCodePoints);
|
|
60
|
+
const colLevels = [...new Set(ys)].sort(compareCodePoints);
|
|
62
61
|
if (rowLevels.length < 2 || colLevels.length < 2)
|
|
63
62
|
throw new RangeError("'x' and 'y' must have at least 2 levels");
|
|
64
63
|
const ri = new Map(rowLevels.map((v, i) => [v, i]));
|
|
@@ -87,8 +86,10 @@ function chisqCounts(x, options) {
|
|
|
87
86
|
/** Number of replicates, checked when a simulation is run */
|
|
88
87
|
function replicates(options) {
|
|
89
88
|
const B = options.B ?? 2000;
|
|
90
|
-
|
|
91
|
-
|
|
89
|
+
// a fractional B ran more simulations than B + 1 counts (R divides by B + 1 as well): p-values above 1 (B = 2.1 gave
|
|
90
|
+
// 1.33, R 1.29). B = 0 simulates nothing (R's p = (1 + 0) / (0 + 1) = 1): an error too (#489)
|
|
91
|
+
if (!(Number.isInteger(B) && B >= 1 && B < 2 ** 31))
|
|
92
|
+
throw new RangeError("'B' must be a positive integer");
|
|
92
93
|
return B;
|
|
93
94
|
}
|
|
94
95
|
/** (1 + #{sims >= (1 - 64 eps) stat}) / (B + 1) */
|
|
@@ -98,7 +99,8 @@ function monteCarloP(sims, stat, B) {
|
|
|
98
99
|
for (let i = 0; i < sims.length; i++)
|
|
99
100
|
if (sims[i] >= threshold)
|
|
100
101
|
count++;
|
|
101
|
-
|
|
102
|
+
// the simulations actually made (R divides by B + 1 with a fractional B, of which only the integer part is run)
|
|
103
|
+
return (1 + count) / (Math.trunc(B) + 1);
|
|
102
104
|
}
|
|
103
105
|
function pValueOf(stat, df) {
|
|
104
106
|
return Number.isNaN(stat) ? NaN : pgamma1(stat, df / 2, 2, false, false);
|
|
@@ -113,7 +115,8 @@ function checkExpected(E) {
|
|
|
113
115
|
}
|
|
114
116
|
function goodnessOfFit(x, options) {
|
|
115
117
|
const k = x.length;
|
|
116
|
-
|
|
118
|
+
// (R lets Infinity through and returns NaN)
|
|
119
|
+
if (x.some((v) => !(v >= 0 && v < Infinity)))
|
|
117
120
|
throw new RangeError("all entries of 'x' must be non-negative and finite");
|
|
118
121
|
if (k < 2)
|
|
119
122
|
throw new TypeError("'x' must have at least 2 elements");
|
|
@@ -127,22 +130,40 @@ function goodnessOfFit(x, options) {
|
|
|
127
130
|
throw new RangeError("p contains missing values");
|
|
128
131
|
if (p.some((v) => v < 0))
|
|
129
132
|
throw new RangeError("probabilities must be non-negative");
|
|
133
|
+
if (p.some((v) => v === Infinity))
|
|
134
|
+
throw new RangeError("probabilities must be finite");
|
|
130
135
|
if (options.rescaleP ?? false) {
|
|
131
|
-
|
|
132
|
-
p =
|
|
136
|
+
// where the total of the finite weights overflows, the weights in units of 2^e, 2^e >= k, first (each weight was
|
|
137
|
+
// divided by Inf and became 0: p = c(1e308, 1e308) gave statistic Inf, p-value 0; R too; issue #303)
|
|
138
|
+
const total = ddSum(p);
|
|
139
|
+
const e = total < Infinity ? 0 : Math.ceil(Math.log2(k));
|
|
140
|
+
const ps = e === 0 ? p : p.map((v) => ldexp(v, -e));
|
|
141
|
+
const s = e === 0 ? total : ddSum(ps);
|
|
142
|
+
p = ps.map((v) => v / s);
|
|
133
143
|
}
|
|
134
144
|
else if (Math.abs(ddSum(p) - 1) > Math.sqrt(Number.EPSILON)) {
|
|
135
145
|
throw new RangeError("probabilities must sum to 1");
|
|
136
146
|
}
|
|
137
|
-
|
|
147
|
+
// where the total overflows (each count finite), the counts in units of 2^s, 2^s >= k and s even, so that their total
|
|
148
|
+
// cannot overflow; the statistic is scaled back by 2^s and the residuals by 2^(s/2). With s = 0 (the total finite)
|
|
149
|
+
// the values are those of the plain counts
|
|
150
|
+
const s = n < Infinity ? 0 : 2 * Math.ceil(Math.log2(k) / 2);
|
|
151
|
+
const xs = s === 0 ? x : x.map((v) => ldexp(v, -s));
|
|
152
|
+
const ns = s === 0 ? n : ddSum(xs);
|
|
153
|
+
const Es = p.map((v) => ns * v);
|
|
154
|
+
const E = s === 0 ? Es : Es.map((e) => ldexp(e, s));
|
|
138
155
|
checkExpected(E);
|
|
139
|
-
const
|
|
140
|
-
const stat = ddSum(
|
|
156
|
+
const Vs = p.map((v, i) => Es[i] * (1 - v));
|
|
157
|
+
const stat = ldexp(ddSum(xs.map((v, i) => squareOver(v - Es[i], Es[i]))), s);
|
|
141
158
|
let method = "Chi-squared test for given probabilities";
|
|
142
159
|
let df = k - 1;
|
|
143
160
|
let pValue;
|
|
144
161
|
if (options.simulatePValue ?? false) {
|
|
145
162
|
const B = replicates(options);
|
|
163
|
+
// a fractional total cannot be drawn as a sample: the columns of draws then outnumbered B and the p-value exceeded
|
|
164
|
+
// 1 (c(3.5, 4, 5) with B = 2 gave 1.33; R too)
|
|
165
|
+
if (!Number.isInteger(n))
|
|
166
|
+
throw new RangeError("the simulation needs counts summing to an integer");
|
|
146
167
|
method += simulatedMethod(B);
|
|
147
168
|
df = NaN;
|
|
148
169
|
pValue = monteCarloP(simulateGoodnessOfFit(n, p, E, B), stat, B);
|
|
@@ -158,30 +179,28 @@ function goodnessOfFit(x, options) {
|
|
|
158
179
|
pValue,
|
|
159
180
|
observed: x,
|
|
160
181
|
expected: E,
|
|
161
|
-
residuals:
|
|
162
|
-
stdres:
|
|
182
|
+
residuals: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Es[i]), s / 2)),
|
|
183
|
+
stdres: xs.map((v, i) => ldexp((v - Es[i]) / Math.sqrt(Vs[i]), s / 2)),
|
|
163
184
|
};
|
|
164
185
|
}
|
|
165
186
|
/**
|
|
166
|
-
* Statistics of B multinomial samples: B n categories
|
|
167
|
-
*
|
|
168
|
-
*
|
|
187
|
+
* Statistics of B multinomial samples: the B n categories of R's sample.int(k, B n, TRUE, prob = p), taken column by
|
|
188
|
+
* column of the n-row matrix, are drawn n at a time and counted (n is an integer here), without keeping the B n draws
|
|
189
|
+
* (#287): the same uniforms in the same order, so the same statistics. B n is limited to 2^27 draws (tens of seconds)
|
|
169
190
|
*/
|
|
170
191
|
function simulateGoodnessOfFit(n, p, E, B) {
|
|
171
192
|
const k = p.length;
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
193
|
+
if (B * n > 2 ** 27)
|
|
194
|
+
throw new RangeError("the simulation needs B * sum(x) <= 2^27 (134217728) draws");
|
|
195
|
+
const draw = sampleIntReplaceDrawer(k, p);
|
|
196
|
+
if (B * n === 0)
|
|
175
197
|
return new Float64Array(0);
|
|
176
|
-
|
|
177
|
-
throw new RangeError("invalid 'nrow' value (too large or NA)");
|
|
178
|
-
const cols = Math.ceil(draws.length / rows);
|
|
179
|
-
const out = new Float64Array(cols);
|
|
198
|
+
const out = new Float64Array(B);
|
|
180
199
|
const counts = new Float64Array(k);
|
|
181
|
-
for (let j = 0; j <
|
|
200
|
+
for (let j = 0; j < B; j++) {
|
|
182
201
|
counts.fill(0);
|
|
183
|
-
for (let i = 0; i <
|
|
184
|
-
counts[
|
|
202
|
+
for (let i = 0; i < n; i++)
|
|
203
|
+
counts[draw()]++;
|
|
185
204
|
let s = 0;
|
|
186
205
|
for (let c = 0; c < k; c++)
|
|
187
206
|
s += (counts[c] - E[c]) ** 2 / E[c];
|
|
@@ -194,6 +213,9 @@ function simulateTables(sr, sc, E, B) {
|
|
|
194
213
|
const nr = sr.length;
|
|
195
214
|
const nc = sc.length;
|
|
196
215
|
const total = sr.reduce((a, b) => a + b, 0);
|
|
216
|
+
// the table of log factorials has total + 1 entries: limited as in r2dtable (#285)
|
|
217
|
+
if (total > MAX_TABLE_TOTAL)
|
|
218
|
+
throw new RangeError("the simulation needs a total count of at most 16777216 (2^24)");
|
|
197
219
|
const fact = logFactorialTable(total);
|
|
198
220
|
const table = new Int32Array(nr * nc);
|
|
199
221
|
const out = new Float64Array(Math.trunc(B));
|
|
@@ -222,7 +244,7 @@ function contingency(x, options) {
|
|
|
222
244
|
throw new RangeError("at least one entry of 'x' must be positive");
|
|
223
245
|
const sr = x.map((r) => ddSum(r));
|
|
224
246
|
const sc = x[0].map((_, j) => ddSum(x.map((r) => r[j])));
|
|
225
|
-
const E = sr.map((a) => sc.map((b) => (a
|
|
247
|
+
const E = sr.map((a) => sc.map((b) => productOver(a, b, n)));
|
|
226
248
|
checkExpected(E.flat());
|
|
227
249
|
const diff = x.map((r, i) => r.map((v, j) => v - E[i][j]));
|
|
228
250
|
let method = "Pearson's Chi-squared test";
|
|
@@ -232,22 +254,24 @@ function contingency(x, options) {
|
|
|
232
254
|
const simulate = (options.simulatePValue ?? false) && sr.every((v) => v > 0) && sc.every((v) => v > 0);
|
|
233
255
|
const yates = !simulate && correct && nr === 2 && nc === 2 ? Math.min(0.5, ...diff.flat().map(Math.abs)) : 0;
|
|
234
256
|
if (simulate) {
|
|
235
|
-
// counts are integers for the simulation
|
|
257
|
+
// counts are integers for the simulation: the simulated tables have integer margins, and fractional observed
|
|
258
|
+
// counts would be compared with them (R truncates the margins and runs it)
|
|
259
|
+
if (x.some((r) => r.some((v) => !Number.isInteger(v))))
|
|
260
|
+
throw new RangeError("the simulation needs integer counts");
|
|
236
261
|
const B = replicates(options);
|
|
237
262
|
method += simulatedMethod(B);
|
|
238
|
-
stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d
|
|
263
|
+
stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(d, E[i][j]))));
|
|
239
264
|
df = NaN;
|
|
240
265
|
const sims = simulateTables(sr.map((v) => Math.trunc(v)), sc.map((v) => Math.trunc(v)), E, B);
|
|
241
266
|
pValue = monteCarloP(sims, stat, B);
|
|
242
267
|
}
|
|
243
268
|
else if (yates > 0) {
|
|
244
269
|
method += " with Yates' continuity correction";
|
|
245
|
-
stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (Math.abs(d) - yates
|
|
270
|
+
stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(Math.abs(d) - yates, E[i][j]))));
|
|
246
271
|
}
|
|
247
272
|
else {
|
|
248
|
-
stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => (d
|
|
273
|
+
stat = ddSum(diff.flatMap((r, i) => r.map((d, j) => squareOver(d, E[i][j]))));
|
|
249
274
|
}
|
|
250
|
-
const V = E.map((r, i) => r.map((e, j) => e * (1 - sr[i] / n) * (1 - sc[j] / n)));
|
|
251
275
|
return {
|
|
252
276
|
method,
|
|
253
277
|
statistic: stat,
|
|
@@ -258,6 +282,69 @@ function contingency(x, options) {
|
|
|
258
282
|
observed: x,
|
|
259
283
|
expected: E,
|
|
260
284
|
residuals: diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j]))),
|
|
261
|
-
stdres:
|
|
285
|
+
stdres: contingencyStdres(x, n, sr, sc, E, diff),
|
|
262
286
|
};
|
|
263
287
|
}
|
|
288
|
+
/**
|
|
289
|
+
* Standardized residuals (O - E) / sqrt(E (1 - row proportion) (1 - column proportion)) of a contingency table
|
|
290
|
+
* (#382). The complements 1 - row proportion and 1 - column proportion are the sums of the other rows and columns
|
|
291
|
+
* over n, and the margins, E, O - E and the variance are in double-double, rounded once at the end: 1 - sr / n in
|
|
292
|
+
* double lost the small margins (2^52 and 0.1: 0 for the complement, so -Infinity; integer tables such as
|
|
293
|
+
* [[1e15, 7], [3, 11]] were off by 8e-4), and O - E with E rounded to double was 0 in the cell of 2^52. A total
|
|
294
|
+
* beyond the double range keeps the old formula
|
|
295
|
+
*/
|
|
296
|
+
function contingencyStdres(x, n, sr, sc, E, diff) {
|
|
297
|
+
if (!Number.isFinite(n)) {
|
|
298
|
+
return diff.map((r, i) => r.map((d, j) => d / Math.sqrt(E[i][j] * (1 - sr[i] / n) * (1 - sc[j] / n))));
|
|
299
|
+
}
|
|
300
|
+
const srD = x.map((r) => ddSumOf(r));
|
|
301
|
+
const scD = x[0].map((_, j) => ddSumOf(x.map((r) => r[j])));
|
|
302
|
+
const nD = ddSumOfDD(srD);
|
|
303
|
+
const cr = othersSums(srD);
|
|
304
|
+
const cc = othersSums(scD);
|
|
305
|
+
const rowC = cr.map((c) => ddDiv(c, nD));
|
|
306
|
+
const colP = scD.map((c) => ddDiv(c, nD));
|
|
307
|
+
const colC = cc.map((c) => ddDiv(c, nD));
|
|
308
|
+
return x.map((r, i) => r.map((v, j) => {
|
|
309
|
+
const e = ddMul(srD[i], colP[j]);
|
|
310
|
+
const d = ddSub([v, 0], e);
|
|
311
|
+
const dd = d[0] + d[1];
|
|
312
|
+
const V = ddMul(ddMul(e, rowC[i]), colC[j]);
|
|
313
|
+
const vv = V[0] + V[1];
|
|
314
|
+
if (vv >= MIN_NORMAL || dd === 0)
|
|
315
|
+
return dd / Math.sqrt(vv);
|
|
316
|
+
// a variance below the normal range: divide by the square roots in turn
|
|
317
|
+
const ee = e[0] + e[1];
|
|
318
|
+
const rc = rowC[i][0] + rowC[i][1];
|
|
319
|
+
const ccj = colC[j][0] + colC[j][1];
|
|
320
|
+
return dd / Math.sqrt(ee) / Math.sqrt(rc) / Math.sqrt(ccj);
|
|
321
|
+
}));
|
|
322
|
+
}
|
|
323
|
+
const MIN_NORMAL = 2 ** -1022;
|
|
324
|
+
function ddSumOf(x) {
|
|
325
|
+
let s = [0, 0];
|
|
326
|
+
for (const v of x)
|
|
327
|
+
s = ddAdd(s, [v, 0]);
|
|
328
|
+
return s;
|
|
329
|
+
}
|
|
330
|
+
function ddSumOfDD(x) {
|
|
331
|
+
let s = [0, 0];
|
|
332
|
+
for (const v of x)
|
|
333
|
+
s = ddAdd(s, v);
|
|
334
|
+
return s;
|
|
335
|
+
}
|
|
336
|
+
/** For each i, the double-double sum of the entries other than x[i] (prefix and suffix sums) */
|
|
337
|
+
function othersSums(x) {
|
|
338
|
+
const m = x.length;
|
|
339
|
+
const suffix = new Array(m + 1);
|
|
340
|
+
suffix[m] = [0, 0];
|
|
341
|
+
for (let i = m - 1; i >= 0; i--)
|
|
342
|
+
suffix[i] = ddAdd(x[i], suffix[i + 1]);
|
|
343
|
+
const out = [];
|
|
344
|
+
let prefix = [0, 0];
|
|
345
|
+
for (let i = 0; i < m; i++) {
|
|
346
|
+
out.push(ddAdd(prefix, suffix[i + 1]));
|
|
347
|
+
prefix = ddAdd(prefix, x[i]);
|
|
348
|
+
}
|
|
349
|
+
return out;
|
|
350
|
+
}
|
package/dist/htest/cor.d.ts
CHANGED
|
@@ -30,7 +30,8 @@ export interface CorTestOptions extends CorOptions {
|
|
|
30
30
|
/**
|
|
31
31
|
* Compute an exact p-value (Kendall and Spearman). Default: as in R, exact when there are
|
|
32
32
|
* no ties and n < 50 (Kendall) or n <= 1290 (Spearman). With ties the approximation is
|
|
33
|
-
* always used.
|
|
33
|
+
* always used. Kendall's exact distribution takes about n^3 / 2 steps: for n above 1290 (about 5 s)
|
|
34
|
+
* `exact: true` without ties is a RangeError (R computes it however long it takes).
|
|
34
35
|
*/
|
|
35
36
|
exact?: boolean;
|
|
36
37
|
/** Confidence level of the interval (Pearson only; the interval needs at least 4 pairs). Default `0.95`. */
|
package/dist/htest/cor.js
CHANGED
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
import { pt1 } from "../distributions/t.js";
|
|
27
27
|
import { pnorm, qnorm } from "../distributions/normal.js";
|
|
28
28
|
import { ddAdd, ddDiv, ddMul, ddSub, twoProd, twoSum } from "../special/dd.js";
|
|
29
|
-
import {
|
|
29
|
+
import { centered, completePairs, rank, tieCounts } from "../internal/summary.js";
|
|
30
30
|
import { correlationData } from "./testFormula.js";
|
|
31
31
|
import { checkConfLevel, matchAlternative } from "./types.js";
|
|
32
32
|
const METHODS = ["pearson", "kendall", "spearman"];
|
|
@@ -73,27 +73,14 @@ function ddSqrt(a) {
|
|
|
73
73
|
const e = ddSub(a, twoProd(s, s));
|
|
74
74
|
return twoSum(s, e[0] / (2 * s));
|
|
75
75
|
}
|
|
76
|
-
/** Deviations (mean subtracted in double-double, scaled by a power of 2 to be near 1). Correlation is scale-invariant */
|
|
77
|
-
function scaledDeviations(x) {
|
|
78
|
-
const m = meanDD(x);
|
|
79
|
-
if (!Number.isFinite(m[0]))
|
|
80
|
-
return undefined;
|
|
81
|
-
const d = x.map((v) => ddSub([v, 0], m));
|
|
82
|
-
let mx = 0;
|
|
83
|
-
for (const v of d)
|
|
84
|
-
mx = Math.max(mx, Math.abs(v[0]));
|
|
85
|
-
if (mx === 0)
|
|
86
|
-
return d;
|
|
87
|
-
const f = 2 ** -Math.max(-1022, Math.floor(Math.log2(mx)));
|
|
88
|
-
return d.map((v) => [v[0] * f, v[1] * f]);
|
|
89
|
-
}
|
|
90
76
|
/** Pearson's correlation coefficient in double-double (so 1 - r is computed without cancellation near perfect correlation) */
|
|
91
77
|
export function pearsonDD(x, y) {
|
|
92
78
|
const n = x.length;
|
|
93
79
|
if (n < 2)
|
|
94
80
|
return [NaN, 0];
|
|
95
|
-
|
|
96
|
-
const
|
|
81
|
+
// deviations of the values scaled by a power of 2 first (the correlation does not depend on the scales)
|
|
82
|
+
const dx = centered(x)?.d;
|
|
83
|
+
const dy = centered(y)?.d;
|
|
97
84
|
if (dx === undefined || dy === undefined)
|
|
98
85
|
return [NaN, 0];
|
|
99
86
|
let sxy = [0, 0];
|
|
@@ -160,6 +147,8 @@ export function kendall(x, y) {
|
|
|
160
147
|
const tau = n < 2 || px === pairs || py === pairs ? NaN : px === 0 && py === 0 ? s / pairs : s / Math.sqrt((pairs - px) * (pairs - py));
|
|
161
148
|
return { s, tau, ties: tx.length > 0 || ty.length > 0, tx, ty };
|
|
162
149
|
}
|
|
150
|
+
/** Largest n for Kendall's exact p-value (#316) */
|
|
151
|
+
const MAX_KENDALL_EXACT_N = 1290;
|
|
163
152
|
/**
|
|
164
153
|
* Probability that a permutation of n distinct elements has at most c inversions. The inversion
|
|
165
154
|
* distribution is symmetric, so the upper tail P(T >= q) is computed as P(T <= N - q) (N = n(n-1)/2).
|
|
@@ -334,7 +323,9 @@ function corTestSamples(x, y, options) {
|
|
|
334
323
|
else if (alternative === "greater")
|
|
335
324
|
ci = [end(-sigma * qnorm(confLevel)), 1];
|
|
336
325
|
else {
|
|
337
|
-
|
|
326
|
+
// (for alpha below 1e-8 the upper probability itself: 1 - alpha loses its digits and rounds to 1 below 1.1e-16; review 58)
|
|
327
|
+
const a2 = (1 - confLevel) / 2;
|
|
328
|
+
const c = sigma * (a2 < 1e-8 ? qnorm(a2, { lowerTail: false }) : qnorm((1 + confLevel) / 2));
|
|
338
329
|
ci = [end(-c), end(c)];
|
|
339
330
|
}
|
|
340
331
|
result.confInt = ci;
|
|
@@ -358,6 +349,11 @@ function corTestSamples(x, y, options) {
|
|
|
358
349
|
return { ...base, statistic: NaN, statisticName: "T", pValue: NaN };
|
|
359
350
|
const exact = options.exact ?? n < 50;
|
|
360
351
|
if (exact && !k.ties) {
|
|
352
|
+
// the two runs of kendallCdf below take n (q + 1) + n (total - q + 1) steps, about n^3 / 2: limited to n <= 1290
|
|
353
|
+
// (the same number as the Spearman exact limit; about 5 s), checked before they allocate (#316)
|
|
354
|
+
if (n > MAX_KENDALL_EXACT_N) {
|
|
355
|
+
throw new RangeError(`the exact distribution of T for n = ${n} takes too long (at most ${MAX_KENDALL_EXACT_N}): use exact: false`);
|
|
356
|
+
}
|
|
361
357
|
const total = (n * (n - 1)) / 2;
|
|
362
358
|
const q = (k.s + total) / 2;
|
|
363
359
|
// P(T <= q) and P(T >= q) = P(T <= total - q)
|
|
@@ -371,8 +367,10 @@ function corTestSamples(x, y, options) {
|
|
|
371
367
|
const a2 = (t) => t * (t - 1);
|
|
372
368
|
const a3 = (t) => t * (t - 1) * (t - 2);
|
|
373
369
|
const a5 = (t) => t * (t - 1) * (2 * t + 5);
|
|
370
|
+
// For n = 2 every tie group has t <= 2, so the sums of t (t - 1) (t - 2)
|
|
371
|
+
// are 0 and the second term is 0 (its denominator is also 0: R gives 0/0).
|
|
374
372
|
const varS = (n * (n - 1) * (2 * n + 5) - v(a5, k.tx) - v(a5, k.ty)) / 18 +
|
|
375
|
-
(v(a3, k.tx) * v(a3, k.ty)) / (9 * n * (n - 1) * (n - 2)) +
|
|
373
|
+
(n < 3 ? 0 : (v(a3, k.tx) * v(a3, k.ty)) / (9 * n * (n - 1) * (n - 2))) +
|
|
376
374
|
(v(a2, k.tx) * v(a2, k.ty)) / (2 * n * (n - 1));
|
|
377
375
|
const s = continuity ? Math.sign(k.s) * (Math.abs(k.s) - 1) : k.s;
|
|
378
376
|
const z = s / Math.sqrt(varS);
|
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Throws a RangeError when the exact distribution for sample sizes m and n is too large to build: the two layers of
|
|
3
|
+
* ansariDist hold 2 (m + 1) (maxSum + 1) doubles (maxSum = floor((N + 1)^2 / 4), N = m + n) and the N passes take
|
|
4
|
+
* N (m + 1) (maxSum + 1) steps (m = n = 1000 asked for 16 GB). Checked before any allocation.
|
|
5
|
+
*
|
|
6
|
+
* @param m - Size of the first sample.
|
|
7
|
+
* @param n - Size of the second sample.
|
|
8
|
+
*/
|
|
9
|
+
export declare function checkAnsariExactSize(m: number, n: number): void;
|
|
1
10
|
/**
|
|
2
11
|
* P(AB <= q) (lowerTail) or P(AB > q) for the Ansari-Bradley statistic with sample sizes m and n, without ties.
|
|
3
12
|
*
|
|
@@ -7,7 +7,27 @@
|
|
|
7
7
|
// N - t + 1 positions, the position is picked with probability r / (N - t + 1). The probabilities are kept directly
|
|
8
8
|
// (counts overflow: C(100, 50) = 1e29), and tail probabilities are sums of positive terms.
|
|
9
9
|
import { choose } from "../../special/choose.js";
|
|
10
|
+
import { countAtMost } from "../../internal/integer.js";
|
|
10
11
|
const cache = new Map();
|
|
12
|
+
/** Largest number of doubles the two layers of ansariDist may hold (as #232's 2^24; 128 MB, #308) */
|
|
13
|
+
const MAX_EXACT_SIZE = 2 ** 24;
|
|
14
|
+
/** Largest work N (m + 1) (maxSum + 1) of ansariDist (m = n = 202 is about 5 s) */
|
|
15
|
+
const MAX_EXACT_WORK = 2 ** 32;
|
|
16
|
+
/**
|
|
17
|
+
* Throws a RangeError when the exact distribution for sample sizes m and n is too large to build: the two layers of
|
|
18
|
+
* ansariDist hold 2 (m + 1) (maxSum + 1) doubles (maxSum = floor((N + 1)^2 / 4), N = m + n) and the N passes take
|
|
19
|
+
* N (m + 1) (maxSum + 1) steps (m = n = 1000 asked for 16 GB). Checked before any allocation.
|
|
20
|
+
*
|
|
21
|
+
* @param m - Size of the first sample.
|
|
22
|
+
* @param n - Size of the second sample.
|
|
23
|
+
*/
|
|
24
|
+
export function checkAnsariExactSize(m, n) {
|
|
25
|
+
const N = m + n;
|
|
26
|
+
const cells = (m + 1) * (Math.floor((N + 1) ** 2 / 4) + 1);
|
|
27
|
+
if (2 * cells > MAX_EXACT_SIZE || N * cells > MAX_EXACT_WORK) {
|
|
28
|
+
throw new RangeError(`the exact distribution for m = ${m} and n = ${n} is too large to compute: use exact: false`);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
11
31
|
function ansariDist(m, n) {
|
|
12
32
|
const key = `${m},${n}`;
|
|
13
33
|
const hit = cache.get(key);
|
|
@@ -66,7 +86,7 @@ export function pansariExact(q, m, n, lowerTail = true) {
|
|
|
66
86
|
if (Number.isNaN(q) || !(m >= 1) || !(n >= 1) || m !== Math.floor(m) || n !== Math.floor(n))
|
|
67
87
|
return NaN;
|
|
68
88
|
const { min, probs } = ansariDist(m, n);
|
|
69
|
-
const k =
|
|
89
|
+
const k = countAtMost(q) - min; // index of the largest value <= q
|
|
70
90
|
let s = 0;
|
|
71
91
|
if (lowerTail) {
|
|
72
92
|
for (let i = 0; i <= Math.min(k, probs.length - 1); i++)
|
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Throws a RangeError when pkolmogorovExact(n, d) would need more than MAX_EXACT_WORK: the m x m matrix
|
|
3
|
+
* (m = 2 floor(n d) + 1) is raised to the n-th power with floor(log2 n) squarings and popcount(n) - 1 products, each
|
|
4
|
+
* m^3 multiply-adds (n 1e4 with d 0.4999 asked for an 800 MB matrix and hours of work). Checked before any allocation.
|
|
5
|
+
*
|
|
6
|
+
* @param n - Sample size.
|
|
7
|
+
* @param d - Value of the statistic.
|
|
8
|
+
*/
|
|
9
|
+
export declare function checkKolmogorovExactSize(n: number, d: number): void;
|
|
1
10
|
/**
|
|
2
11
|
* P(D_n < d), the exact distribution of the two-sided one-sample Kolmogorov-Smirnov statistic for a continuous
|
|
3
12
|
* distribution (Marsaglia, Tsang and Wang 2003). The matrix has size 2 floor(n d) + 1, so the cost grows like
|
|
@@ -24,3 +33,19 @@ export declare function pkolmogorovLimit(x: number, lowerTail?: boolean): number
|
|
|
24
33
|
* @param d - Value of the statistic.
|
|
25
34
|
*/
|
|
26
35
|
export declare function pkolmogorovOneSidedUpper(n: number, d: number): number;
|
|
36
|
+
/**
|
|
37
|
+
* P(D_n >= d), the upper tail of the two-sided one-sample statistic, as a sum of positive terms (#483), or NaN where
|
|
38
|
+
* that needs more than MAX_CHAIN_WORK terms. 1 - P(D_n < d) from pkolmogorovExact has absolute accuracy only (1e-22
|
|
39
|
+
* came out as 3e-15 at n = 99).
|
|
40
|
+
*
|
|
41
|
+
* N(t), the number of points at or below t, is a Markov chain: given N(t_k) = s, the count in (t_k, t_(k+1)] is
|
|
42
|
+
* Binomial(n - s, (t_(k+1) - t_k) / (1 - t_k)). D+ >= d when N(i/n - d) >= i for some i, D- >= d when
|
|
43
|
+
* N(j/n + d) <= j for some j (N(t-) = N(t) almost surely). Between the at most 2n breakpoints i/n - d and j/n + d the
|
|
44
|
+
* thresholds are constant, so the chain is stepped from one breakpoint to the next and the probability that leaves it
|
|
45
|
+
* across a threshold is added up. Each binomial row starts from dbinom1 at its mode and follows the ratio recurrence
|
|
46
|
+
* both ways until it underflows.
|
|
47
|
+
*
|
|
48
|
+
* @param n - Sample size, a positive integer.
|
|
49
|
+
* @param d - Value of the statistic, in (0, 1).
|
|
50
|
+
*/
|
|
51
|
+
export declare function pkolmogorovExactUpper(n: number, d: number): number;
|
|
@@ -11,8 +11,13 @@
|
|
|
11
11
|
// - One-sided statistic D_n^+ = sup (F_n(x) - F(x)) (Birnbaum and Tingey, Annals of Mathematical Statistics 22, 1951):
|
|
12
12
|
// P(D_n^+ >= d) = d sum_(j=0)^(floor(n (1 - d))) C(n, j) (1 - d - j/n)^(n-j) (d + j/n)^(j-1),
|
|
13
13
|
// whose terms are b(j; n, a) / a with a = d + j/n: binomial probabilities from Loader's dbinomRawDD.
|
|
14
|
+
// - Upper tail P(D_n >= d) as a sum of positive terms (#483): the counting process of the sample is a Markov chain
|
|
15
|
+
// with binomial steps between the breakpoints i/n - d and j/n + d, and the probability leaving it across either
|
|
16
|
+
// boundary is added up (the first-passage form of the statistic, e.g. Durbin, "Distribution theory for tests based
|
|
17
|
+
// on the sample distribution function", SIAM 1973).
|
|
14
18
|
import { ddAdd, ddDiv, twoProd, twoSum } from "../../special/dd.js";
|
|
15
19
|
import { dbinomRawDD } from "../../special/loader.js";
|
|
20
|
+
import { dbinom1 } from "../../distributions/binomial.js";
|
|
16
21
|
/** pi^2 / 8 as a double-double */
|
|
17
22
|
const PI2_8 = [1.2337005501361697, 7.831619385924639e-17];
|
|
18
23
|
/** H^n with the binary exponent kept apart: returns [matrix, e2] with the true power = matrix * 2^e2 */
|
|
@@ -65,6 +70,27 @@ function matPow(H, m, n) {
|
|
|
65
70
|
}
|
|
66
71
|
return [result, re];
|
|
67
72
|
}
|
|
73
|
+
/** Largest work m^3 (number of matrix products) of pkolmogorovExact that ksTest accepts: about 4 s (#307) */
|
|
74
|
+
const MAX_EXACT_WORK = 2 ** 33;
|
|
75
|
+
/**
|
|
76
|
+
* Throws a RangeError when pkolmogorovExact(n, d) would need more than MAX_EXACT_WORK: the m x m matrix
|
|
77
|
+
* (m = 2 floor(n d) + 1) is raised to the n-th power with floor(log2 n) squarings and popcount(n) - 1 products, each
|
|
78
|
+
* m^3 multiply-adds (n 1e4 with d 0.4999 asked for an 800 MB matrix and hours of work). Checked before any allocation.
|
|
79
|
+
*
|
|
80
|
+
* @param n - Sample size.
|
|
81
|
+
* @param d - Value of the statistic.
|
|
82
|
+
*/
|
|
83
|
+
export function checkKolmogorovExactSize(n, d) {
|
|
84
|
+
// the branches of pkolmogorovExact that use no matrix
|
|
85
|
+
if (Number.isNaN(d) || !(n >= 1) || n !== Math.floor(n) || d <= 1 / (2 * n) || d >= 1 || n * d < 1)
|
|
86
|
+
return;
|
|
87
|
+
const m = 2 * Math.floor(n * d) + 1;
|
|
88
|
+
const bits = n.toString(2);
|
|
89
|
+
const products = Math.max(1, bits.length - 1 + (bits.split("1").length - 2));
|
|
90
|
+
if (m ** 3 * products > MAX_EXACT_WORK) {
|
|
91
|
+
throw new RangeError(`the exact distribution of D for n = ${n} needs powers of a ${m} x ${m} matrix, too much work: use exact: false`);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
68
94
|
/**
|
|
69
95
|
* P(D_n < d), the exact distribution of the two-sided one-sample Kolmogorov-Smirnov statistic for a continuous
|
|
70
96
|
* distribution (Marsaglia, Tsang and Wang 2003). The matrix has size 2 floor(n d) + 1, so the cost grows like
|
|
@@ -174,6 +200,9 @@ export function pkolmogorovLimit(x, lowerTail = true) {
|
|
|
174
200
|
if (t <= 1e-17 * (s + first))
|
|
175
201
|
break;
|
|
176
202
|
}
|
|
203
|
+
// the series underflows below x = 0.0407; there sqrt(2 pi) / x overflows for subnormal x (Inf * 0)
|
|
204
|
+
if (first + s === 0)
|
|
205
|
+
return lowerTail ? 0 : 1;
|
|
177
206
|
const k = (Math.sqrt(2 * Math.PI) / x) * (first + s);
|
|
178
207
|
return lowerTail ? k : 1 - k;
|
|
179
208
|
}
|
|
@@ -219,3 +248,97 @@ export function pkolmogorovOneSidedUpper(n, d) {
|
|
|
219
248
|
}
|
|
220
249
|
return Math.min(d * s, 1);
|
|
221
250
|
}
|
|
251
|
+
/** Largest number of binomial terms of pkolmogorovExactUpper: about 4 s on the development machine (#483) */
|
|
252
|
+
const MAX_CHAIN_WORK = 2 ** 28;
|
|
253
|
+
/**
|
|
254
|
+
* P(D_n >= d), the upper tail of the two-sided one-sample statistic, as a sum of positive terms (#483), or NaN where
|
|
255
|
+
* that needs more than MAX_CHAIN_WORK terms. 1 - P(D_n < d) from pkolmogorovExact has absolute accuracy only (1e-22
|
|
256
|
+
* came out as 3e-15 at n = 99).
|
|
257
|
+
*
|
|
258
|
+
* N(t), the number of points at or below t, is a Markov chain: given N(t_k) = s, the count in (t_k, t_(k+1)] is
|
|
259
|
+
* Binomial(n - s, (t_(k+1) - t_k) / (1 - t_k)). D+ >= d when N(i/n - d) >= i for some i, D- >= d when
|
|
260
|
+
* N(j/n + d) <= j for some j (N(t-) = N(t) almost surely). Between the at most 2n breakpoints i/n - d and j/n + d the
|
|
261
|
+
* thresholds are constant, so the chain is stepped from one breakpoint to the next and the probability that leaves it
|
|
262
|
+
* across a threshold is added up. Each binomial row starts from dbinom1 at its mode and follows the ratio recurrence
|
|
263
|
+
* both ways until it underflows.
|
|
264
|
+
*
|
|
265
|
+
* @param n - Sample size, a positive integer.
|
|
266
|
+
* @param d - Value of the statistic, in (0, 1).
|
|
267
|
+
*/
|
|
268
|
+
export function pkolmogorovExactUpper(n, d) {
|
|
269
|
+
const [hi, lo] = twoProd(n, d);
|
|
270
|
+
// floor(n d) of the exact n d = hi + lo
|
|
271
|
+
let nd = Math.floor(hi);
|
|
272
|
+
if (nd === hi && lo < 0)
|
|
273
|
+
nd -= 1;
|
|
274
|
+
const pts = [];
|
|
275
|
+
for (let i = 0; i <= n; i++) {
|
|
276
|
+
const u = (i - hi - lo) / n;
|
|
277
|
+
if (u > 0 && u < 1)
|
|
278
|
+
pts.push({ t: u, up: true, i });
|
|
279
|
+
const l = (i + hi + lo) / n;
|
|
280
|
+
if (l > 0 && l < 1)
|
|
281
|
+
pts.push({ t: l, up: false, i });
|
|
282
|
+
}
|
|
283
|
+
// at most 2 nd + 1 live states per step, rows of about 100 terms before they underflow
|
|
284
|
+
if (pts.length * (2 * nd + 1) * Math.min(n + 1, 100) > MAX_CHAIN_WORK)
|
|
285
|
+
return NaN;
|
|
286
|
+
pts.sort((a, b) => a.t - b.t);
|
|
287
|
+
let upper = nd + 1; // N >= upper has crossed the upper threshold
|
|
288
|
+
let alive = new Float64Array(n + 1);
|
|
289
|
+
let next = new Float64Array(n + 1);
|
|
290
|
+
alive[0] = 1;
|
|
291
|
+
let sLo = 0; // the live states lie in [sLo, upper - 1]
|
|
292
|
+
let t = 0;
|
|
293
|
+
let p = 0;
|
|
294
|
+
let work = 0;
|
|
295
|
+
for (const pt of pts) {
|
|
296
|
+
const q = (pt.t - t) / (1 - t);
|
|
297
|
+
if (q > 0) {
|
|
298
|
+
const odds = q / (1 - q);
|
|
299
|
+
next.fill(0);
|
|
300
|
+
for (let s = sLo; s < upper; s++) {
|
|
301
|
+
const a = alive[s];
|
|
302
|
+
if (a === 0)
|
|
303
|
+
continue;
|
|
304
|
+
const m = n - s;
|
|
305
|
+
const c0 = Math.min(m, Math.floor((m + 1) * q));
|
|
306
|
+
const cu = upper - s; // c >= cu crosses
|
|
307
|
+
let v = dbinom1(c0, m, q, false);
|
|
308
|
+
for (let c = c0; c <= m && v !== 0; c++) {
|
|
309
|
+
if (c > c0)
|
|
310
|
+
v = (v * (m - c + 1) * odds) / c;
|
|
311
|
+
if (c >= cu)
|
|
312
|
+
p += a * v;
|
|
313
|
+
else
|
|
314
|
+
next[s + c] += a * v;
|
|
315
|
+
work++;
|
|
316
|
+
}
|
|
317
|
+
v = c0 > 0 ? dbinom1(c0 - 1, m, q, false) : 0;
|
|
318
|
+
for (let c = c0 - 1; c >= 0 && v !== 0; c--) {
|
|
319
|
+
if (c < c0 - 1)
|
|
320
|
+
v = (v * (c + 1)) / ((m - c) * odds);
|
|
321
|
+
if (c >= cu)
|
|
322
|
+
p += a * v;
|
|
323
|
+
else
|
|
324
|
+
next[s + c] += a * v;
|
|
325
|
+
work++;
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
if (work > 2 * MAX_CHAIN_WORK)
|
|
329
|
+
return NaN;
|
|
330
|
+
[alive, next] = [next, alive];
|
|
331
|
+
}
|
|
332
|
+
t = pt.t;
|
|
333
|
+
if (pt.up)
|
|
334
|
+
upper = pt.i + 1;
|
|
335
|
+
else {
|
|
336
|
+
for (let s = sLo; s <= pt.i; s++) {
|
|
337
|
+
p += alive[s];
|
|
338
|
+
alive[s] = 0;
|
|
339
|
+
}
|
|
340
|
+
sLo = Math.max(sLo, pt.i + 1);
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
return Math.min(p, 1);
|
|
344
|
+
}
|
|
@@ -6,10 +6,11 @@
|
|
|
6
6
|
// odds ratio (Mantel and Haenszel, JNCI 22, 1959; Birch, JRSS B 26, 1964), so their sum S has the density
|
|
7
7
|
// d0(s) psi^s / sum_t d0(t) psi^t, where d0 is the convolution of the K central hypergeometric densities. The
|
|
8
8
|
// conditional MLE of psi is the noncentrality whose mean equals the observed S, and the confidence limits are the
|
|
9
|
-
// noncentralities at which a one-sided probability equals alpha; the roots are found
|
|
10
|
-
//
|
|
9
|
+
// noncentralities at which a one-sided probability equals alpha; the roots are found on the log scale of psi to the
|
|
10
|
+
// precision of the doubles, as for fisherTest's 2 x 2 tables (src/htest/fisherTest.ts; R's uniroot conventions stop
|
|
11
|
+
// 1e-6 to 1e-2 from the roots).
|
|
11
12
|
import { dhyper1 } from "../../distributions/hypergeometric.js";
|
|
12
|
-
import {
|
|
13
|
+
import { logScaleRoot } from "../../internal/uniroot.js";
|
|
13
14
|
import { ddAdd } from "../../special/dd.js";
|
|
14
15
|
/** Compensated (double-double) sum of v[from..to) */
|
|
15
16
|
function sumRange(v, from, to) {
|
|
@@ -112,7 +113,8 @@ export class ConvolvedNoncentralHyper {
|
|
|
112
113
|
* t = 1/psi in [eps, 1]
|
|
113
114
|
*/
|
|
114
115
|
function oddsRoot(f, belowOne) {
|
|
115
|
-
|
|
116
|
+
// on the log scale to the precision of the doubles (R's uniroot conventions stopped 1e-6 to 1e-2 off; review 58)
|
|
117
|
+
return logScaleRoot(f, belowOne);
|
|
116
118
|
}
|
|
117
119
|
/** The conditional maximum likelihood estimate of the common odds ratio given the observed sum s */
|
|
118
120
|
export function conditionalMLE(h, s) {
|