This is an automated email from the ASF dual-hosted git repository.
aherbert pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-statistics.git
The following commit(s) were added to refs/heads/master by this push:
new 28a6268c STATISTICS-104: Fix comparisons with rounding errors (#142)
28a6268c is described below
commit 28a6268cdfc52735b47596c4f8587f848b4c7d6c
Author: Alex Herbert <[email protected]>
AuthorDate: Fri Dec 4 09:29:11 2026 +0000
STATISTICS-104: Fix comparisons with rounding errors (#142)
Rounding errors in values used for comparisons create incorrect p-value
computations in inference tests: BinomialTest; FisherExactTest; and
UnconditionedExactTest.
Update the binomial distribution log probability computation. This now
handles symmetry in x or (n - x); sums terms in magnitude order; and
detects a bimodal distribution and returns only 1 value for both modes.
This impacts both the binomial distribution, and the hypergeometric
distribution.
The binomial distribution is now symmetric at the mode for bimodal
distributions; and is symmetric when the probability of success is 0.5.
The hypergeometric distribution is defined by the log probability
function for its PMF and cumulative probability functions. It sums 3
binomial log probabilities. This is now done in magnitude order. A
bimodal distribution is detected and the value of the upper mode in this
case is always used. The PMF now exploits parameter symmetry in the
number of successes (K) and sample size (n):
f(k; N, K, n) = f(k; N, n, K)
where N is the population size. The K or n that chooses a binomial
probability closest to 0.5 is chosen. This ensures the distribution is
symmetric when p=0.5.
A bug in the BinomialTest and FisherExactTest two-sided p-value
computation is now fixed at the mode. When k=mode then all other values
have equal or lower probability and the significance result is 1.0.
A bug in the BinomialTest where one side of a symmetric binomial
distribution computed values p(n-k) != p(k) is now fixed.
The FisherExactTest computes p-values for all possible 2x2 contingency
tables using the hypergeometric distribution. Because this now supports
parameter symmetry two symmetric contingency tables have the same
p-value.
This also fixes Boschloo's method in the UnconditionedExactTest which
computes Fisher p-values as a score to compare candidate contingency
tables.
The Z pooled/unpooled method of the UnconditionedExactTest has been
updated to use rational numbers for p-values and exploit symmetry to
compute the Z scores. Two scores from symmetric contingency tables now
have the same magnitude.
---
.../distribution/HypergeometricDistribution.java | 60 ++++-
.../distribution/SaddlePointExpansionUtils.java | 85 +++++--
.../distribution/BinomialDistributionTest.java | 121 ++++++++++
.../HypergeometricDistributionTest.java | 117 +++++++++
.../distribution/test.binomial.4.properties | 2 +-
.../commons/statistics/inference/BinomialTest.java | 27 ++-
.../statistics/inference/FisherExactTest.java | 15 +-
.../inference/UnconditionedExactTest.java | 173 ++++++++++----
.../statistics/inference/BinomialTestTest.java | 42 +++-
.../statistics/inference/FisherExactTestTest.java | 28 ++-
.../inference/UnconditionedExactTestTest.java | 265 +++++++++++++++++++--
src/changes/changes.xml | 16 ++
src/conf/pmd/pmd-ruleset.xml | 3 +-
src/conf/spotbugs/spotbugs-exclude-filter.xml | 8 +
14 files changed, 843 insertions(+), 119 deletions(-)
diff --git
a/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/HypergeometricDistribution.java
b/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/HypergeometricDistribution.java
index 5f1b0b81..9fef4bb5 100644
---
a/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/HypergeometricDistribution.java
+++
b/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/HypergeometricDistribution.java
@@ -63,13 +63,18 @@ public final class HypergeometricDistribution extends
AbstractDiscreteDistributi
private final int lowerBound;
/** The upper bound of the support (inclusive). */
private final int upperBound;
- /** Binomial probability of success (sampleSize / populationSize). */
+ /** The effective sample size for the binomial probability p and q.
+ * Either sampleSize or populationSize using sample vs. population
duality. */
+ private final int effectiveSampleSize;
+ /** Binomial probability of success (n / populationSize). */
private final double bp;
- /** Binomial probability of failure ((populationSize - sampleSize) /
populationSize). */
+ /** Binomial probability of failure ((populationSize - n) /
populationSize). */
private final double bq;
/** Cached midpoint of the CDF/SF. The array holds [x, cdf(x)] for the
midpoint x.
* Used for the cumulative probability functions. */
private double[] midpoint;
+ /** Used to return an equal value for a bimodel distribution. */
+ private final int upperMode;
/** Create an instance.
* @param populationSize Population size.
@@ -84,8 +89,26 @@ public final class HypergeometricDistribution extends
AbstractDiscreteDistributi
this.sampleSize = sampleSize;
lowerBound = getLowerDomain(populationSize, numberOfSuccesses,
sampleSize);
upperBound = getUpperDomain(numberOfSuccesses, sampleSize);
- bp = (double) sampleSize / populationSize;
- bq = (double) (populationSize - sampleSize) / populationSize;
+ // The PMF uses sample vs. population duality
+ // f(k; N, K, n) = f(k; N, n, K)
+ // k = number of successes; n = sample size
+ // Choose p = K / N or n / N closest to 0.5
+ // This ensures a symmetric distribution is chosen at p=0.5
+ // 2N * |K / N - 1 / 2| < 2N * |n / N - 1 / 2|
+ final long dk = Math.abs(2L * numberOfSuccesses - populationSize);
+ final long dn = Math.abs(2L * sampleSize - populationSize);
+ effectiveSampleSize = dk < dn ? numberOfSuccesses : sampleSize;
+ bp = (double) effectiveSampleSize / populationSize;
+ bq = (double) (populationSize - effectiveSampleSize) / populationSize;
+ // Compute the mode.
+ // This is to enforce exact equality at each mode of a bimodel
distribution.
+ final double v = ((double) numberOfSuccesses + 1) * ((double)
sampleSize + 1) / (populationSize + 2.0);
+ // mode is ceil(v) - 1 or floor(v).
+ // When v is an exact integer there are two modes.
+ // Note numberOfSuccesses <= populationSize so 0 < v < sampleSize + 1.
+ // No requirement to check 0 < m2 <= upperBound.
+ final double m2 = Math.floor(v);
+ upperMode = m2 == v ? (int) m2 : -1;
}
/**
@@ -229,13 +252,34 @@ public final class HypergeometricDistribution extends
AbstractDiscreteDistributi
* @return log(P(X = x))
*/
private double computeLogProbability(int x) {
+ // The PMF uses sample vs. population duality
+ // f(k; N, K, n) = f(k; N, n, K)
+ // K = number of successes, n = sample size, or vice versa.
+ // This is chosen in the constructor.
+ final int n = effectiveSampleSize;
+ final int k = effectiveSampleSize == sampleSize ? numberOfSuccesses :
sampleSize;
+
+ // Compute p1 + p2 - p3
+ // Sum terms in magnitude order to reduce cancellation.
+ // An exact sum with BigDecimal cannot create an equal PMF at a
bimodal distribution
+ // so this is handled by using the lower mode (upper mode > 0 or unset
at -1).
+ final int xx = x == upperMode ? x - 1 : x;
final double p1 =
- SaddlePointExpansionUtils.logBinomialProbability(x,
numberOfSuccesses, bp, bq);
+ SaddlePointExpansionUtils.logBinomialProbability(xx, k, bp,
bq);
final double p2 =
- SaddlePointExpansionUtils.logBinomialProbability(sampleSize -
x,
- populationSize - numberOfSuccesses, bp, bq);
+ SaddlePointExpansionUtils.logBinomialProbability(n - xx,
+ populationSize - k, bp, bq);
final double p3 =
- SaddlePointExpansionUtils.logBinomialProbability(sampleSize,
populationSize, bp, bq);
+ SaddlePointExpansionUtils.logBinomialProbability(n,
populationSize, bp, bq);
+ // All are negative. Use the largest magnitude term last.
+ if (p1 < p2) {
+ if (p1 < p3) {
+ return p2 - p3 + p1;
+ }
+ // p3 is largest ... fall-through
+ } else if (p2 < p3) {
+ return p1 - p3 + p2;
+ }
return p1 + p2 - p3;
}
diff --git
a/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/SaddlePointExpansionUtils.java
b/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/SaddlePointExpansionUtils.java
index 10a6a3a0..b85c3ed9 100644
---
a/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/SaddlePointExpansionUtils.java
+++
b/commons-statistics-distribution/src/main/java/org/apache/commons/statistics/distribution/SaddlePointExpansionUtils.java
@@ -29,41 +29,24 @@ final class SaddlePointExpansionUtils {
private static final double TWO_PI = 2 * Math.PI;
/** 1/10. */
private static final double ONE_TENTH = 0.1;
- /** The threshold value for switching the method to compute th Stirling
error. */
- private static final int STIRLING_ERROR_THRESHOLD = 15;
- /** Exact Stirling expansion error for certain values. */
+ /** Exact Stirling expansion error for integers. */
private static final double[] EXACT_STIRLING_ERRORS = {
0.0, /* 0.0 */
- 0.1534264097200273452913848, /* 0.5 */
0.0810614667953272582196702, /* 1.0 */
- 0.0548141210519176538961390, /* 1.5 */
0.0413406959554092940938221, /* 2.0 */
- 0.03316287351993628748511048, /* 2.5 */
0.02767792568499833914878929, /* 3.0 */
- 0.02374616365629749597132920, /* 3.5 */
0.02079067210376509311152277, /* 4.0 */
- 0.01848845053267318523077934, /* 4.5 */
0.01664469118982119216319487, /* 5.0 */
- 0.01513497322191737887351255, /* 5.5 */
0.01387612882307074799874573, /* 6.0 */
- 0.01281046524292022692424986, /* 6.5 */
0.01189670994589177009505572, /* 7.0 */
- 0.01110455975820691732662991, /* 7.5 */
0.010411265261972096497478567, /* 8.0 */
- 0.009799416126158803298389475, /* 8.5 */
0.009255462182712732917728637, /* 9.0 */
- 0.008768700134139385462952823, /* 9.5 */
0.008330563433362871256469318, /* 10.0 */
- 0.007934114564314020547248100, /* 10.5 */
0.007573675487951840794972024, /* 11.0 */
- 0.007244554301320383179543912, /* 11.5 */
0.006942840107209529865664152, /* 12.0 */
- 0.006665247032707682442354394, /* 12.5 */
0.006408994188004207068439631, /* 13.0 */
- 0.006171712263039457647532867, /* 13.5 */
0.005951370112758847735624416, /* 14.0 */
- 0.005746216513010115682023589, /* 14.5 */
0.005554733551962801371038690 /* 15.0 */
};
@@ -89,8 +72,8 @@ final class SaddlePointExpansionUtils {
* @return the Stirling's series error.
*/
static double getStirlingError(int z) {
- if (z <= STIRLING_ERROR_THRESHOLD) {
- return EXACT_STIRLING_ERRORS[2 * z];
+ if (z < EXACT_STIRLING_ERRORS.length) {
+ return EXACT_STIRLING_ERRORS[z];
}
final double z2 = (double) z * z;
return (0.083333333333333333333 -
@@ -151,6 +134,8 @@ final class SaddlePointExpansionUtils {
* @return log(p(x)).
*/
static double logBinomialProbability(int x, int n, double p, double q) {
+ // Handle special cases x=0, x=n.
+ // Otherwise log(x * (n-x) * 2pi) = -infinity.
if (x == 0) {
if (p < ONE_TENTH) {
// Subtract from 0 avoids returning -0.0 for p=0.0
@@ -166,11 +151,59 @@ final class SaddlePointExpansionUtils {
}
return n * Math.log(p);
}
- final int nMx = n - x;
- final double ret = getStirlingError(n) - getStirlingError(x) -
- getStirlingError(nMx) - getDeviancePart(x, n * p) -
- getDeviancePart(nMx, n * q);
- final double f = (TWO_PI * x * nMx) / n;
- return -0.5 * Math.log(f) + ret;
+
+ // 0 < x < n
+ // Edge case: Handle a bimodal distribution.
+ // The mode is ceil((n+1)*p) - 1 or floor((n+1)*p). When
+ // (n+1)*p is an integer the distribution has two modes.
+ // Test if the upper mode = x and compute for lower mode x-1.
+ // This cannot decrement x and continue as it may create 0.
+ // This does not catch an upper mode = n as it will have
+ // been handled above. So also check if the mode is n and x
+ // is the lower mode. Note if p=0 this cannot match x as
+ // it is non-zero; if p=1 it cannot match n. So this
+ // is bimodal only when p in (0, 1).
+ final double mode = (n + 1.0) * p;
+ if (mode == x || mode == n && n == x + 1) {
+ // Call again as the entry handles special cases.
+ // The result is an upper mode is evaluated as a lower mode;
+ // or if the upper mode is n, the lower mode is evaluated as
+ // an upper mode.
+ return logBinomialProbability(mode == x ? x - 1 : n, n, p, q);
+ }
+
+ // Sum terms in magnitude order. All are positive.
+ // This will respect symmetry in the binomial distribution.
+ // Larger n has a smaller Stirling error.
+ double ret = getStirlingError(n);
+ final double t1 = getStirlingError(x);
+ final double t2 = getStirlingError(n - x);
+ // This uses conditional load statements rather than explicit branches
+ ret -= t1 < t2 ? t1 : t2;
+ ret -= t1 < t2 ? t2 : t1;
+
+ double t3 = getDeviancePart(x, n * p);
+ double t4 = getDeviancePart(n - x, n * q);
+
+ // Multiply x * (n - x) first to respect symmetry
+ // Smallest when x = 1 = log(2pi * (n-1) / n) / 2 ~ log(2pi) / 2 ~ 0.91
+ // Largest when x = n-x = n/2 ~ log(2pi * n/4) / 2 ~ log(pi * n/2)
+ // This can be smaller or larger than the deviance parts
+ final double f = ((double) x * (n - x) * TWO_PI) / n;
+ final double t5 = 0.5 * Math.log(f);
+
+ // Sum remaining terms in magnitude order
+ if (t4 < t3) {
+ final double t = t4;
+ t4 = t3;
+ t3 = t;
+ }
+ if (t5 < t4) {
+ if (t5 < t3) {
+ return ret - t5 - t3 - t4;
+ }
+ return ret - t3 - t5 - t4;
+ }
+ return ret - t3 - t4 - t5;
}
}
diff --git
a/commons-statistics-distribution/src/test/java/org/apache/commons/statistics/distribution/BinomialDistributionTest.java
b/commons-statistics-distribution/src/test/java/org/apache/commons/statistics/distribution/BinomialDistributionTest.java
index 399a8d46..76508ae7 100644
---
a/commons-statistics-distribution/src/test/java/org/apache/commons/statistics/distribution/BinomialDistributionTest.java
+++
b/commons-statistics-distribution/src/test/java/org/apache/commons/statistics/distribution/BinomialDistributionTest.java
@@ -275,4 +275,125 @@ class BinomialDistributionTest extends
BaseDiscreteDistributionTest {
}
return new BigDecimal(nCk).multiply(result);
}
+
+ /**
+ * Test symmetry in the binomial distribution when p=0.5.
+ *
+ * <p>Inexact paired values either side of a symmetric distribution
created a bug in the
+ * BinomialTest in the inference module. See STATISTICS-104.
+ * Error cases were for n in {3, 13, 19, 21}.
+ */
+ @ParameterizedTest
+ @ValueSource(ints = {1, 2, 3, 10, 11, 12, 13, 19, 21, 30, 31, 100, 101})
+ void testSymmetry(int n) {
+ final BinomialDistribution dist = BinomialDistribution.of(n, 0.5);
+ for (int i = 0; i <= n / 2; i++) {
+ Assertions.assertEquals(dist.logProbability(i),
dist.logProbability(n - i));
+ }
+ }
+
+ /**
+ * Test symmetry at the mode when there are two modes. The mode is:
+ * <pre>
+ * int m1 = (int) Math.ceil((n + 1.0) * p) - 1;
+ * int m2 = (int) Math.floor((n + 1.0) * p);
+ * </pre>
+ *
+ * <p>There are two modes when (n+1) * p is an exact integer.
+ *
+ * <p>Inexact paired values at a bimodal distribution exposed a bug in the
+ * BinomialTest in the inference module. See STATISTICS-104.
+ */
+ @ParameterizedTest
+ @CsvSource({
+ // Require (n+1)*p to be integer
+ // p = integer / (n+1) is a representable double
+
+ // 1-digit representable double is the p=0.5 symmetry case
+
+ // 2-digit representable doubles
+ "3, 0.25", // 1/4
+ "3, 0.75", // 3/4
+ "7, 0.25", // 1/4
+ "7, 0.75", // 3/4
+ "11, 0.25", // 1/4
+ "11, 0.75", // 3/4
+ // 3-digit representable doubles
+ "7, 0.125", // 1/8
+ "7, 0.375", // 3/8
+ "7, 0.625", // 5/8
+ "7, 0.875", // 7/8
+ "15, 0.125", // 1/8
+ "15, 0.375", // 3/8
+ "15, 0.625", // 5/8
+ "15, 0.875", // 7/8
+ "23, 0.125", // 1/8
+ "23, 0.375", // 3/8
+ "23, 0.625", // 5/8
+ "23, 0.875", // 7/8
+ // Larger
+ "1023, 0.908203125", // 930/1024
+ "1023, 0.9091796875", // 931/1024
+ "1023, 0.91015625", // 932/1024
+ "1023, 0.9111328125", // 933/1024
+ "2147483647, 4.6566128730773926E-10", // 1/2^31
+ "2147483647, 0.16986663592979312", // 364785823/2^31
+ "2147483647, 0.8217924381606281", // 1764785823/2^31
+ "2147483647, 0.9999999995343387", // (2^31 - 1)/2^31
+ })
+ void testMode(int n, double p) {
+ final BinomialDistribution dist = BinomialDistribution.of(n, p);
+ final int m1 = (int) Math.ceil((n + 1.0) * p) - 1;
+ final int m2 = (int) Math.floor((n + 1.0) * p);
+ Assertions.assertEquals(m1 + 1, m2, () -> "m1 + 1: " + (n + 1.0) * p);
+ // Some cases fail unless the mode is handled within the
+ // saddle-point expansion
+ final double l1 = dist.logProbability(m1);
+ Assertions.assertEquals(l1, dist.logProbability(m2), "mode");
+ // Ensure coverage of logic to detect both lower and upper mode.
+ // The method must be called with a value that is not either mode.
+ if (m1 > 0) {
+ Assertions.assertTrue(dist.logProbability(m1 - 1) < l1, "Below
lower mode");
+ }
+ if (m2 < n) {
+ Assertions.assertTrue(dist.logProbability(m2 + 1) < l1, "Above
lower mode");
+ }
+ // Check the distribution is consistent. The rest of the probability
+ // should add to 1. This does not work when n is very large as
+ // the PMF or the CDF/SF are not accurate enough.
+ if (n < 100000) {
+ TestUtils.assertEquals(1, 2 * Math.exp(l1) +
+ dist.cumulativeProbability(m1 - 1) +
dist.survivalProbability(m2),
+ DoubleTolerances.ulps(10), "cdf(m1-1) + pmf(m1) + pmf(m+1) +
sf(m+1)");
+ }
+ }
+
+ /**
+ * STATISTICS-104 updated the binomial log probability to support symmetry.
+ * One test case resource file failed at the existing 2e-15 accuracy.
+ * This documents the change of tolerance around the failing value.
+ */
+ @Test
+ void testStatistics104PMF() {
+ final BinomialDistribution dist = BinomialDistribution.of(10, 0.3);
+ // R value from the reference file:
+ // 1.3778099999999990615e-04
+ // Java implementation can output either:
+ // 1.377810000000004E-4
+ // 1.377809999999999E-4
+ // This is due to a difference in the JDK Math implementation.
+ // The saddle-point expansion uses log and the PMF uses exp.
+ // log(1.377810000000004E-4) and log(1.377809999999999E-4) are 2 ULP
apart.
+ final double pj = dist.probability(9);
+ // The exact result sits in between the two values above.
+ // new BigDecimal(1 - 0.7).pow(9).multiply(new
BigDecimal(0.7)).multiply(new BigDecimal(10)).doubleValue()
+ final double expected = 1.3778100000000018E-4;
+ TestUtils.assertEquals(expected, pj, DoubleTolerances.ulps(10));
+ // The two PMF values are +8 or -10 to the exact result.
+ // If the Java version computes the upper one then it is 18 ULP
different from R
+ // but closer to the exact result.
+ // The test case has been updated to use 2^-48 relative eps (5 bits) ~
4e-15.
+ TestUtils.assertEquals(expected, 1.377810000000004E-4,
DoubleTolerances.ulps(8));
+ TestUtils.assertEquals(expected, 1.377809999999999E-4,
DoubleTolerances.ulps(10));
+ }
}
diff --git
a/commons-statistics-distribution/src/test/java/org/apache/commons/statistics/distribution/HypergeometricDistributionTest.java
b/commons-statistics-distribution/src/test/java/org/apache/commons/statistics/distribution/HypergeometricDistributionTest.java
index 4f30a9d9..af36f3c0 100644
---
a/commons-statistics-distribution/src/test/java/org/apache/commons/statistics/distribution/HypergeometricDistributionTest.java
+++
b/commons-statistics-distribution/src/test/java/org/apache/commons/statistics/distribution/HypergeometricDistributionTest.java
@@ -277,4 +277,121 @@ class HypergeometricDistributionTest extends
BaseDiscreteDistributionTest {
testCumulativeProbabilityInverseMapping(dist, points);
testSurvivalProbabilityInverseMapping(dist, points);
}
+
+ /**
+ * Test parameter symmetry in the hypergeometric distribution.
+ * The distribution has parameter symmetry for K and n:
+ * <pre>
+ * f(k; N, K, n) = f(k; N, n, K)
+ * </pre>
+ *
+ * <p>Inexact paired values using symmetric 2x2 contingency tables created
a bug in
+ * the FisherExactTest in the inference module. See STATISTICS-104.
+ */
+ @ParameterizedTest
+ @CsvSource({
+ "7, 2, 3",
+ "30, 10, 14",
+ "30, 20, 14",
+ "30, 10, 18",
+ "30, 20, 18",
+ })
+ void testParameterSymmetry(int nn, int k, int n) {
+ final HypergeometricDistribution dist1 =
HypergeometricDistribution.of(nn, k, n);
+ final HypergeometricDistribution dist2 =
HypergeometricDistribution.of(nn, n, k);
+ final int lo = dist1.getSupportLowerBound();
+ final int hi = dist2.getSupportUpperBound();
+ Assertions.assertEquals(lo, dist2.getSupportLowerBound());
+ Assertions.assertEquals(hi, dist2.getSupportUpperBound());
+ for (int i = lo; i <= hi; i++) {
+ Assertions.assertEquals(dist1.logProbability(i),
dist2.logProbability(i));
+ }
+ }
+
+ /**
+ * Test symmetry in the hypergeometric distribution. Note it is symmetric
when the
+ * population proportion of successes equals 0.5, i.e. K (or n) = N/2 for
an even population
+ * size N. This test does not specify n. It can be any value as the
distribution is
+ * symmetric when p=0.5. The support for parameter symmetry of K or n
should not
+ * choose the min or max (which is consistent) but the value which creates
the
+ * binomial probability closest to 0.5. This is also consistent but
enforces
+ * symmetry support when either K = N/2, or n = N/2. The underlying
binomial
+ * probability computations are symmetric when p=0.5.
+ *
+ * <p>Inexact paired values either side of a symmetric distribution
created a bug in
+ * the FisherExactTest in the inference module. See STATISTICS-104.
+ */
+ @ParameterizedTest
+ @CsvSource({
+ "8, 4",
+ // STATISTICS-104 case had a table using: N=30, k=10, n=15.
+ // By parameter symmetry this is 30, 15, 10.
+ // Note the UnconditionedExactTest uses a 2x2 contingency table: {{7,
12}, {8, 3}}.
+ // This creates N=30; k=19; n=15. Using a fixed margin of n=15 the
Boschloo
+ // method enumerates all k in [0, 30]. Symmetry must be enforced
otherwise
+ // tables with the same two-sided p-value are different due to
rounding error.
+ "30, 15",
+ // Large
+ "300, 150",
+ })
+ void testSymmetry(int nn, int k) {
+ for (int n = 0; n <= nn; n++) {
+ final HypergeometricDistribution dist =
HypergeometricDistribution.of(nn, k, n);
+ final int lo = dist.getSupportLowerBound();
+ final int hi = dist.getSupportUpperBound();
+ for (int i = lo, j = hi; i < j; i++, j--) {
+ Assertions.assertEquals(dist.logProbability(i),
dist.logProbability(j));
+ }
+ }
+ }
+
+ /**
+ * Test symmetry at the mode when there are two modes. The mode is:
+ * <pre>
+ * double v = ((double) k + 1) * ((double) n + 1) / (N + 2.0);
+ * int m1 = (int) Math.ceil(v) - 1;
+ * int m2 = (int) Math.floor(v);
+ * </pre>
+ *
+ * <p>There are two modes when v is an exact integer.
+ *
+ * <p>Inexact paired values at a hypergeometric distribution mode exposed
a bug in the
+ * FisherExactTest in the inference module. See STATISTICS-104.
+ */
+ @ParameterizedTest
+ @CsvSource({
+ "2, 1, 1", // v = 2 * 2 / 4
+ "4, 1, 2", // v = 2 * 3 / 6
+ "7, 2, 2", // v = 3 * 3 / 9
+ "10, 1, 5", // v = 2 * 6 / 12
+ "16, 2, 5", // v = 3 * 6 / 18
+ "16, 14, 5", // v = 15 * 6 / 18
+ // Larger
+ "1798, 9, 179", // v = 10 * 180 / 1800
+ "1798, 19, 179", // v = 20 * 180 / 1800
+ "1798, 129, 179", // v = 130 * 180 / 1800
+ "1798, 179, 179", // v = 180 * 180 / 1800
+ "17999998, 9, 1799999", // v = 10 * 1800000 / 18000000
+ "17999998, 999, 1799999", // v = 1000 * 1800000 / 18000000
+ })
+ void testMode(int nn, int k, int n) {
+ final HypergeometricDistribution dist =
HypergeometricDistribution.of(nn, k, n);
+ final double v = ((double) k + 1) * ((double) n + 1) / (nn + 2.0);
+ final int m1 = (int) Math.ceil(v) - 1;
+ final int m2 = (int) Math.floor(v);
+ Assertions.assertEquals(m1 + 1, m2, () -> "m1 + 1: " + v);
+ // Some cases fail unless the mode is handled within the
+ // hypergeometric distribution. Using an exact BigDecimal summation of
+ // the 3 log PMF values does not work.
+ final double l1 = dist.logProbability(m1);
+ Assertions.assertEquals(l1, dist.logProbability(m2), "mode");
+ // Check the distribution is consistent. The rest of the probability
+ // should add to 1. This does not work when n is very large as
+ // the PMF or the CDF/SF are not accurate enough.
+ if (dist.getSupportUpperBound() - dist.getSupportLowerBound() < 10000)
{
+ TestUtils.assertEquals(1, 2 * Math.exp(l1) +
+ dist.cumulativeProbability(m1 - 1) +
dist.survivalProbability(m2),
+ DoubleTolerances.ulps(10), "cdf(m1-1) + pmf(m1) + pmf(m+1) +
sf(m+1)");
+ }
+ }
}
diff --git
a/commons-statistics-distribution/src/test/resources/org/apache/commons/statistics/distribution/test.binomial.4.properties
b/commons-statistics-distribution/src/test/resources/org/apache/commons/statistics/distribution/test.binomial.4.properties
index 1dd2fee0..d587787c 100644
---
a/commons-statistics-distribution/src/test/resources/org/apache/commons/statistics/distribution/test.binomial.4.properties
+++
b/commons-statistics-distribution/src/test/resources/org/apache/commons/statistics/distribution/test.binomial.4.properties
@@ -55,5 +55,5 @@ isf.values = 0, 0, 0, 0, 1, 1, 8, 7, 6, 5, 5, 10
# Overridden tolerances
cdf.relative = 1e-15
-pmf.relative = 2e-15
+pmf.relative = 4e-15
sf.relative = 1.1e-15
diff --git
a/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/BinomialTest.java
b/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/BinomialTest.java
index 068d44f4..8eb78d98 100644
---
a/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/BinomialTest.java
+++
b/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/BinomialTest.java
@@ -123,7 +123,7 @@ public final class BinomialTest {
} else if (alternative == AlternativeHypothesis.LESS_THAN) {
p = distribution.cumulativeProbability(numberOfSuccesses);
} else {
- p = twoSidedBinomialTest(numberOfTrials, numberOfSuccesses,
probability, distribution);
+ p = twoSidedBinomialTest(numberOfSuccesses, distribution);
}
return new BaseSignificanceResult((double) numberOfSuccesses /
numberOfTrials, p);
}
@@ -132,21 +132,30 @@ public final class BinomialTest {
* Returns the <i>observed significance level</i>, or p-value, associated
with a
* two-sided binomial test about the probability of success \( \pi \).
*
- * @param n Number of trials performed.
* @param k Number of successes observed.
- * @param probability Assumed probability of a single trial under the null
- * hypothesis.
* @param distribution Binomial distribution.
* @return p-value
*/
- private static double twoSidedBinomialTest(int n, int k, double
probability,
+ private static double twoSidedBinomialTest(int k,
BinomialDistribution
distribution) {
+ // Obtain n and p from the distribution
+ final int n = distribution.getNumberOfTrials();
+ final double probability = distribution.getProbabilityOfSuccess();
+
// Find all i where Pr(X = i) <= Pr(X = k) and sum them.
// Exploit the known unimodal distribution to increase the
// search speed. Note the search depends only on magnitude differences.
// The current BinomialDistribution is faster using log probability
// as it omits a call to Math.exp.
+ // Note: This compares probabilities without a relative tolerance (t).
+ // It could be added using statistic + log1p(t).
+ // On small n distributions a failed p-value comparison can
significantly change the
+ // result. This is handled by supporting symmetry in the binomial
+ // distribution. Values (m-i) and (m+i) either side of the mode will
have
+ // equal p-values when the distribution is symmetric (p=0.5).
+ // The special case at the mode returns 1.
+
// Use the mode as the point of largest probability.
// The lower or upper mode is important for the search below.
final int m1 = (int) Math.ceil((n + 1.0) * probability) - 1;
@@ -170,11 +179,7 @@ public final class BinomialTest {
return distribution.cumulativeProbability(i) +
distribution.survivalProbability(k - 1);
}
- // k == mode
- // Edge case where the sum of probabilities will be either
- // 1 or 1 - Pr(X = mode) where mode != k
- final double pk = distribution.probability(k);
- final double pm = distribution.probability(k == m1 ? m2 : m1);
- return pm > pk ? 1 - pm : 1;
+ // k == mode : all p(i) are equal or lower
+ return 1.0;
}
}
diff --git
a/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/FisherExactTest.java
b/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/FisherExactTest.java
index 0c733c51..349f02b2 100644
---
a/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/FisherExactTest.java
+++
b/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/FisherExactTest.java
@@ -187,6 +187,13 @@ public final class FisherExactTest {
// The current HypergeometricDistribution is faster using log
probability
// as it omits a call to Math.exp.
+ // Note: This does not search <= pK with a relative tolerance (t):
log(pk) + log1p(t)
+ // On small table sizes equal values occur at the mode of a bimodal
+ // hypergeometric distribution, or where the entire distribution is
symmetric:
+ // N/2 = k (or n by parameter symmetry). The underlying hypergeometric
distribution
+ // implementation handles either case of known symmetry.
+ // The special case at the mode returns 1.
+
// Use the mode as the point of largest probability.
// The lower or upper mode is important for the search below.
final int nn = distribution.getPopulationSize();
@@ -216,11 +223,7 @@ public final class FisherExactTest {
return distribution.cumulativeProbability(i) +
distribution.survivalProbability(k - 1);
}
- // k == mode
- // Edge case where the sum of probabilities will be either
- // 1 or 1 - Pr(X = mode) where mode != k
- final double pk = distribution.probability(k);
- final double pm = distribution.probability(k == m1 ? m2 : m1);
- return pm > pk ? 1 - pm : 1;
+ // k == mode : all p(i) are equal or lower
+ return 1.0;
}
}
diff --git
a/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/UnconditionedExactTest.java
b/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/UnconditionedExactTest.java
index 9b455640..7156c5da 100644
---
a/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/UnconditionedExactTest.java
+++
b/commons-statistics-inference/src/main/java/org/apache/commons/statistics/inference/UnconditionedExactTest.java
@@ -269,7 +269,8 @@ public final class UnconditionedExactTest {
* An expandable list of (x,y) values. This allows tracking 2D positions
stored as
* a single index.
*/
- private static class XYList {
+ // package-private for testing
+ static final class XYList {
/** The maximum size of array to allocate. */
private final int max;
/** Width, or maximum x value (exclusive). */
@@ -389,7 +390,7 @@ public final class UnconditionedExactTest {
* values have been observed. This prevents storing a large number of NaN
* candidates.
*/
- static class Candidates {
+ static final class Candidates {
/** The maximum size of array to allocate. */
private final int max;
/** Relative distance from lowest candidate. */
@@ -655,9 +656,9 @@ public final class UnconditionedExactTest {
// Exhaustive switch statement
switch (method) {
case Z_POOLED:
- return statisticZ(a, b, m, n, true);
+ return statisticZ(a, b, m, n, true, true);
case Z_UNPOOLED:
- return statisticZ(a, b, m, n, false);
+ return statisticZ(a, b, m, n, false, true);
case BOSCHLOO:
return statisticBoschloo(a, b, m, n);
}
@@ -735,29 +736,69 @@ public final class UnconditionedExactTest {
/**
* Compute the statistic from a Z-test.
*
+ * <pre>
+ * z = (p1 - p0) / sqrt(v) ; v = variance
+ * = (a/m - b/n) / sqrt(v)
+ * = (n*a - m*b) / (m*n) / sqrt(v)
+ * </pre>
+ *
+ * <p>The computation can be computed without the normalization division
by (n*m).
+ * In this case the returned z statistic is too large. It can be compared
to other
+ * z-statistics with less rounding error. The numerator is exact as a long.
+ * The denominator sqrt(v) may be inexact and there is rounding error of
the
+ * rational number p / q.
+ *
* @param a Observed value for a.
* @param b Observed value for b.
* @param m Column sum m.
* @param n Column sum n.
* @param pooled true to use a pooled variance.
+ * @param normalize true to use normalized p0 and p1
* @return z
*/
- private static double statisticZ(int a, int b, int m, int n, boolean
pooled) {
- final double p0 = (double) a / m;
- final double p1 = (double) b / n;
- // Avoid NaN generation 0 / 0 when the variance is 0
- if (p0 != p1) {
- final double variance;
- if (pooled) {
- // Integer sums will not overflow
- final double p = (double) (a + b) / (m + n);
- variance = p * (1 - p) * (1.0 / m + 1.0 / n);
- } else {
- variance = p0 * (1 - p0) / m + p1 * (1 - p1) / n;
- }
- return (p0 - p1) / Math.sqrt(variance);
+ private static double statisticZ(int a, int b, int m, int n, boolean
pooled, boolean normalize) {
+ // This computation suffers from rounding error.
+ // Use rational numbers where the numerator is exact. Rounding error
+ // is from the division and potentially inexact denominator.
+ // Note that the product m*n < 2^31 as this is limited by the maximum
number of tables.
+ // Tables require m+n < 2^31 and integer sums will not overflow.
+ // p0 = a/m, p1 = b/n. Use a common denominator m*n.
+ final long na = (long) n * a;
+ final long mb = (long) m * b;
+ // Avoid NaN generation 0 / 0 when the variance is 0.
+ // These are the special cases a=b=0 and a=m,b=n (zero numerators in
the variance).
+ if (na == mb) {
+ return 0;
+ }
+ final double variance;
+ final double mn = (double) m * n;
+ if (pooled) {
+ // p = (a+b) / (m+n)
+ // v = p * (1-p) * (1/m + 1/n)
+ // [ (a+b) * ((m+n)-(a+b)) / (m+n)^2 ] * ((m+n) / (m*n))
+ // The numerator is an exact long. The error is by rounding a
constant division.
+ variance = (a + b) * (long) (m + n - a - b) / (mn * (m + n));
+ } else {
+ // v = p0 * (1 - p0) / m + p1 * (1 - p1) / n
+ // (p0 - p0^2) / m + (p1 - p1^2) / n
+ // (a/m - a^2/m^2) / m + (b/n - b^2/n^2) / n
+ // (m*a - a*a) / m^3 + (n*b - b*b) / n^3
+ // (n^3 * (m*a - a*a) + m^3 * (n*b - b*b)) / (m^3 * n^3)
+ // Use of the common denominator does not eliminate rounding error
+ // Here use the form where the numerators are exact longs. The
cube is exact
+ // when the integer m or n <= 208063.
+ final double m3 = (double) m * m * m;
+ final double n3 = (double) n * n * n;
+ variance = ((long) (m - a) * a) / m3 + ((long) (n - b) * b) / n3;
}
- return 0;
+ // z = (p0 - p1) / sqrt(variance)
+ // (p0 - p1) = (a/m - b/n)
+ // = (n*a - m*b) / (m*n)
+ // numerator is exact as a long
+ // m*n is constant and may be exact
+ // variance is rounded
+ // Use an option to avoid the (m*n) factor.
+ return (na - mb) / ((normalize ? mn : 1) * Math.sqrt(variance));
}
/**
@@ -771,9 +812,20 @@ public final class UnconditionedExactTest {
* @param tableList List to track more extreme tables.
* @return observed z
*/
- private double findExtremeTablesZ(int a, int b, int m, int n, boolean
pooled, XYList tableList) {
- final double statistic = statisticZ(a, b, m, n, pooled);
- // Identify more extreme tables using the alternate hypothesis
+ // package-private for testing
+ double findExtremeTablesZ(int a, int b, int m, int n, boolean pooled,
XYList tableList) {
+ // Identify more extreme tables using the alternate hypothesis.
+ // Note the computation of the z statistic suffers from rounding error.
+ // The less-than-or-equal test does not allow for this. The computation
+ // matches an exact reference on small tables (hundreds of
observations)
+ // and has exact identity when table columns are swapped (m, n) <=>
(n, m) for
+ // any size table. On very large tables a few ULP difference to
misclassify tables
+ // (changing the table list) will not cascade into large relative
changes in the
+ // final statistic p-value as the list change is small compared to the
total
+ // table count.
+
+ // Use a statistic without the rounding error from division by the
(m*n) constant.
+ final double statistic = statisticZ(a, b, m, n, pooled, false);
final DoublePredicate test;
if (alternative == AlternativeHypothesis.GREATER_THAN) {
test = z -> z >= statistic;
@@ -788,36 +840,47 @@ public final class UnconditionedExactTest {
final double za = Math.abs(statistic);
test = z -> Math.abs(z) >= za;
}
- // Precompute factors
- final double mn = (double) m + n;
- final double norm = 1.0 / m + 1.0 / n;
+ // This duplicates statisticZ with pre-computed factors and using a=i;
b=j.
+ final double mn = (double) m * n;
+ // Pooled normalising factor
+ final double norm = mn * (m + n);
+ // Unpooled normalising factors
+ final double m3 = (double) m * m * m;
+ final double n3 = (double) n * n * n;
double z;
- // Process all possible tables
+ // Process all possible tables.
+ // Handle the special cases i=j=0 and i=m,j=n (no variance) outside
the loop.
+ // The inner loop over j adjusts the start and end to avoid these.
+ // Note a mirror of columns (m, n) <=> (n, m) negates the z-score so
the inference
+ // test is symmetric.
+ if (test.test(0)) {
+ tableList.add(0, 0);
+ tableList.add(m, n);
+ }
for (int i = 0; i <= m; i++) {
- final double p0 = (double) i / m;
- final double vp0 = p0 * (1 - p0) / m;
- for (int j = 0; j <= n; j++) {
- final double p1 = (double) j / n;
- // Avoid NaN generation 0 / 0 when the variance is 0
- if (p0 == p1) {
- z = 0;
+ final long ni = (long) n * i;
+ // Pooled variance
+ final long mpnmi = m + n - i;
+ // Unpooled variance
+ final double vi = ((long) (m - i) * i) / m3;
+ final int endN = i == m ? n - 1 : n;
+ for (int j = i == 0 ? 1 : 0; j <= endN; j++) {
+ final long mj = (long) m * j;
+ final double variance;
+ if (pooled) {
+ variance = (i + j) * (mpnmi - j) / norm;
} else {
- final double variance;
- if (pooled) {
- // Integer sums will not overflow
- final double p = (i + j) / mn;
- variance = p * (1 - p) * norm;
- } else {
- variance = vp0 + p1 * (1 - p1) / n;
- }
- z = (p0 - p1) / Math.sqrt(variance);
+ variance = vi + ((long) (n - j) * j) / n3;
}
+ // Avoid division of (ni - mj) by (m*n)
+ z = (ni - mj) / Math.sqrt(variance);
if (test.test(z)) {
tableList.add(i, j);
}
}
}
- return statistic;
+ // Recompute the correct Z
+ return statisticZ(a, b, m, n, pooled, true);
}
/**
@@ -855,6 +918,13 @@ public final class UnconditionedExactTest {
// two-sided: Find all i where Pr(X = i) <= Pr(X = k) and sum them.
// Logic is the same as FisherExactTest but using the probability
(PMF), which
// is cached, rather than the logProbability.
+
+ // Note: This does not search <= pK with a relative tolerance (t): pk
* (1+t)
+ // On small table sizes equal values occur at the mode of a bimodal
+ // hypergeometric distribution, or where the entire distribution is
symmetric:
+ // N/2 = k (or n by parameter symmetry). The underlying hypergeometric
distribution
+ // implementation handles either case of known symmetry.
+ // The special case at the mode returns 1.
final double pk = distribution.pmf(k);
final int m1 = distribution.getLowerMode();
@@ -878,11 +948,8 @@ public final class UnconditionedExactTest {
return distribution.cdf(i) +
distribution.sf(k - 1);
}
- // k == mode
- // Edge case where the sum of probabilities will be either
- // 1 or 1 - Pr(X = mode) where mode != k
- final double pm = distribution.pmf(k == m1 ? m2 : m1);
- return pm > pk ? 1 - pm : 1;
+ // k == mode : all p(i) are equal or lower
+ return 1.0;
}
/**
@@ -897,6 +964,16 @@ public final class UnconditionedExactTest {
* @return observed p-value
*/
private double findExtremeTablesBoschloo(int a, int b, int m, int n,
XYList tableList) {
+ // Note: This compares probabilities without a relative tolerance (t).
+ // It could be added using statistic * (1+t).
+ // On small input tables a misclassification can significantly change
the result
+ // as the table list size change is relatively large compared to the
total table count.
+ // This is currently handled by supporting symmetry in the
hypergeometric
+ // distribution used to compute the Fisher p-value. This removes
+ // misclassifcation in the two-sided case when values on either side of
+ // the mode for a symmetric distribution are equal. The 2x2 table
candidates
+ // corresponding to each side will have the same p-value.
+
final double statistic = statisticBoschloo(a, b, m, n);
// Function to compute the statistic
diff --git
a/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/BinomialTestTest.java
b/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/BinomialTestTest.java
index 497b5f44..9d78cae5 100644
---
a/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/BinomialTestTest.java
+++
b/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/BinomialTestTest.java
@@ -120,7 +120,7 @@ class BinomialTestTest {
// Find all i where Pr(X = i) <= Pr(X = k) and sum them.
expected = Math.min(maxP, Arrays.stream(pk).filter(x -> x <=
pk[k]).sum());
TestUtils.assertProbability(expected,
- twoSided.test(n, k, p).getPValue(), eps,
+ twoSided.test(n, k, p).getPValue(), eps,
() -> "two-sided: k=" + k);
});
}
@@ -277,4 +277,44 @@ class BinomialTestTest {
new double[] {4.229481760264341e-05, 0.9999911956737946,
2.399451075709081e-05}));
return builder.build();
}
+
+ /**
+ * Test the two-sided p-value. When alternative p(i) have the same
probability within
+ * rounding error to the input p(k) they can be misclassified as less
extreme, i.e. not
+ * counted as less-than-or-equal-to p(k). This can change the computed
+ * p-value for the test statistic by a large amount.
+ * See STATISTICS-104.
+ */
+ @ParameterizedTest
+ @MethodSource
+ void testTwoSidedPValue(int n, int k, double probability, double p) {
+ final BinomialTest test =
BinomialTest.withDefaults().with(AlternativeHypothesis.TWO_SIDED);
+ final double p1 = test.test(n, k, probability).getPValue();
+ TestUtils.assertRelativelyEquals(p, p1, 1e-15, "p-value");
+ }
+
+ static Stream<Arguments> testTwoSidedPValue() {
+ // Cases for STATISTICS-104
+ // Note that many cases uses a symmetric distribution (p=0.5).
+ // This is fixed in the BinomialDistribution to use symmetry when
p=0.5.
+ // Other cases use the observed value at the mode (see p=0.75 example).
+ // This is fixed in the BinomialDistribution to return the same value
+ // for each mode of a bimodal distribution.
+ return Stream.of(
+ // Cases at the mode of the distribution
+ Arguments.of(3, 2, 0.5, 1.0),
+ Arguments.of(21, 10, 0.5, 1.0),
+ // These cases are below the mode of a symmetric distribution.
+ // The upper half probability should equal the lower half at the
target k.
+ // p(k; n, p) = Binom(n, k) * p^k (1-p)^k
+ Arguments.of(13, 3, 0.5,
+ BinomialDistribution.of(13, 0.5).cumulativeProbability(3) +
+ BinomialDistribution.of(13, 0.5).survivalProbability(13 - 4)),
+ Arguments.of(19, 5, 0.5,
+ BinomialDistribution.of(19, 0.5).cumulativeProbability(5) +
+ BinomialDistribution.of(19, 0.5).survivalProbability(19 - 6)),
+ // A case at the mode of a non-symmetric distribution
+ Arguments.of(11, 9, 0.75, 1.0)
+ );
+ }
}
diff --git
a/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/FisherExactTestTest.java
b/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/FisherExactTestTest.java
index 065709fb..0a645dbf 100644
---
a/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/FisherExactTestTest.java
+++
b/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/FisherExactTestTest.java
@@ -184,8 +184,8 @@ class FisherExactTestTest {
int i = 0;
for (final AlternativeHypothesis h : AlternativeHypothesis.values()) {
final SignificanceResult r =
FisherExactTest.withDefaults().with(h).test(table);
- Assertions.assertEquals(statistic, r.getStatistic(), "statistic
mismatch");
- TestUtils.assertProbability(p[i++], r.getPValue(), 8e-15,
"p-value");
+ Assertions.assertEquals(statistic, r.getStatistic(), () -> h + ":
statistic mismatch");
+ TestUtils.assertProbability(p[i++], r.getPValue(), 1e-14, () -> h
+ ": p-value");
}
}
@@ -217,4 +217,28 @@ class FisherExactTestTest {
new double[] {1, 1, 0.5}));
return builder.build();
}
+
+ /**
+ * Test the two-sided p-value. When alternative tables have the same
probability within
+ * rounding error to the input table they can be misclassified as less
extreme, i.e. not
+ * counted as less-than-or-equal-to the input table. This can change the
computed
+ * p-value for the test statistic by a large amount.
+ * See STATISTICS-104.
+ */
+ @ParameterizedTest
+ @MethodSource
+ void testTwoSidedPValue(int a, int b, int c, int d, double p) {
+ final int[][] table = {{a, b}, {c, d}};
+ final FisherExactTest test =
FisherExactTest.withDefaults().with(AlternativeHypothesis.TWO_SIDED);
+ final double p1 = test.test(table).getPValue();
+ TestUtils.assertRelativelyEquals(p, p1, 8e-15, "p-value");
+ }
+
+ static Stream<Arguments> testTwoSidedPValue() {
+ // Cases for STATISTICS-104
+ return Stream.of(
+ Arguments.of(0, 2, 2, 3, 1.0),
+ Arguments.of(2, 8, 13, 7, 502.0 / 10005)
+ );
+ }
}
diff --git
a/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/UnconditionedExactTestTest.java
b/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/UnconditionedExactTestTest.java
index c67e30b9..98ad5c1e 100644
---
a/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/UnconditionedExactTestTest.java
+++
b/commons-statistics-inference/src/test/java/org/apache/commons/statistics/inference/UnconditionedExactTestTest.java
@@ -16,16 +16,21 @@
*/
package org.apache.commons.statistics.inference;
+import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.BitSet;
import java.util.Optional;
import java.util.SplittableRandom;
import java.util.function.Consumer;
+import java.util.function.Predicate;
import java.util.stream.IntStream;
import java.util.stream.Stream;
+import org.apache.commons.numbers.fraction.BigFraction;
import
org.apache.commons.statistics.inference.UnconditionedExactTest.Candidates;
import org.apache.commons.statistics.inference.UnconditionedExactTest.Method;
import org.apache.commons.statistics.inference.UnconditionedExactTest.Result;
+import org.apache.commons.statistics.inference.UnconditionedExactTest.XYList;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
@@ -225,6 +230,21 @@ class UnconditionedExactTestTest {
Assertions.assertEquals(pval,
UnconditionedExactTest.withDefaults().test(table).getStatistic(), "test
statistic");
}
+ /**
+ * Test the two-sided p-value.
+ * Reuses the test cases from the FisherExactTest to ensure the test
statistic is
+ * computed correctly.
+ */
+ @ParameterizedTest
+ @MethodSource(value =
{"org.apache.commons.statistics.inference.FisherExactTestTest#testTwoSidedPValue"})
+ void testTwoSidedPValue(int a, int b, int c, int d, double p) {
+ final int[][] table = {{a, b}, {c, d}};
+ final FisherExactTest test =
FisherExactTest.withDefaults().with(AlternativeHypothesis.TWO_SIDED);
+ final double p1 = test.test(table).getPValue();
+ Assertions.assertEquals(p1,
UnconditionedExactTest.withDefaults().statistic(table), "statistic");
+ Assertions.assertEquals(p1,
UnconditionedExactTest.withDefaults().test(table).getStatistic(), "test
statistic");
+ }
+
/**
* Test the unconditioned exact test.
*
@@ -297,16 +317,23 @@ class UnconditionedExactTestTest {
// require('Exact')
// exact.test(matrix(c(7, 12, 8, 3), 2, 2), method='z-pooled',
alternative='g', npNumbers=33)[c(1,3)]
- // The implementation more closely matches SciPy than R for the z
value; the p-value
- // is dependent on the z computation and also the sum to find the
nuisance parameter.
- // This particularly effects the test without optimization using R as
the reference.
+ // The p-value is dependent on the z computation and also the sum to
find the
+ // nuisance parameter. This particularly effects the test without
optimization using
+ // R as the reference.
+ // Following STATISTICS-104 the Z computation was updated to remove
sources of
+ // rounding error. The value closely matches an exact BigFraction
computation.
+ // These changes allow the count of more extreme tables to be higher,
and the
+ // p-values rise. These are higher compared to the SciPy/R references.
final Stream.Builder<Arguments> builder = Stream.builder();
- // SciPy
+ // STATISTICS-104: SciPy does not compute Z to sufficient precision
for equality testing.
+ // This is the case from the barnard_exact documentation.
builder.add(Arguments.of(7, 12, 8, 3,
Method.Z_POOLED, 33, true,
new double[] {-1.8943380760602064},
- new double[] {0.06815343273153582, 1, 0.034076716365767874},
1e-15, 7e-15));
+ // SciPy 0.06815343273153582, 1, 0.034076716365767874
+ // Updated with STATISTICS-104 result
+ new double[] {0.0682183, 1, 0.0682183 / 2}, 1e-15, 1e-5));
// R without optimization
// exact.test(matrix(c(7, 12, 8, 3), 2, 2), method='z-pooled',
alternative='t', npNumbers=15, ref.pvalue=FALSE)[c(1,3)]
builder.add(Arguments.of(7, 12, 8, 3,
@@ -323,8 +350,8 @@ class UnconditionedExactTestTest {
builder.add(Arguments.of(74, 31, 43, 32,
Method.Z_POOLED, 33, true,
new double[] {1.8225863590257527},
- // R: 0.070148380863900003, 0.046915929572300001, 1
- new double[] {0.070148380862763000, 0.04691595404276874, 1},
1e-15, 2e-13));
+ // Java: 0.07014838093473463 , 0.04691595404277304
+ new double[] {0.070148380862763000, 0.04691595404276874, 1},
1e-15, 1e-8));
// Larger tables.
builder.add(Arguments.of(123, 92, 424, 113,
@@ -345,7 +372,7 @@ class UnconditionedExactTestTest {
new double[] {-0.08382278919954203},
// R: 1 , 1, 0.47180327976999997 (33
points)
// 0.47653831055000001 (100
points)
- new double[] {0.9480782554147217, 1, 0.4765383214549828}, 1e-15,
1e-12));
+ new double[] {0.9480782554147217, 1, 0.4765383214549828}, 1e-14,
1e-12));
builder.add(Arguments.of(67, 42, 23, 88,
Method.Z_POOLED, 33, true,
new double[] {6.145972185362486},
@@ -388,16 +415,17 @@ class UnconditionedExactTestTest {
// require('Exact')
// exact.test(matrix(c(7, 12, 8, 3), 2, 2), method='z-unpooled',
alternative='g', npNumbers=33)[c(1,3)]
- // The implementation more closely matches SciPy than R for the z
value; the p-value
- // is dependent on the z computation and also the sum to find the
nuisance parameter.
- // This particularly effects the test without optimization using R as
the reference.
+ // See notes in testZPooled regarding accuracy of Z computations.
final Stream.Builder<Arguments> builder = Stream.builder();
- // SciPy
+ // STATISTICS-104: SciPy does not compute Z to sufficient precision
for equality testing.
+ // This is the case from the barnard_exact documentation.
builder.add(Arguments.of(7, 12, 8, 3,
Method.Z_UNPOOLED, 33, true,
new double[] {-2.018932132718121},
- new double[] {0.06815343273153582, 1, 0.034076716365767874},
1e-15, 7e-15));
+ // SciPy: 0.06815343273153582, 1, 0.034076716365767874
+ // Updated with STATISTICS-104 result
+ new double[] {0.0682183, 1, 0.0682183 / 2}, 1e-15, 1e-5));
// R without optimization
// exact.test(matrix(c(7, 12, 8, 3), 2, 2), method='z-unpooled',
alternative='t', npNumbers=15, ref.pvalue=FALSE)[c(1,3)]
builder.add(Arguments.of(7, 12, 8, 3,
@@ -428,7 +456,7 @@ class UnconditionedExactTestTest {
new double[] {-0.0837781159838051},
// R: 1 , 1, 0.47180327976999997 (33
points)
// 0.47653831055000001 (100
points)
- new double[] {0.9480782554147217, 1, 0.4765383214549828}, 1e-15,
1e-12));
+ new double[] {0.9480782554147217, 1, 0.4765383214549828}, 1e-14,
1e-12));
builder.add(Arguments.of(67, 42, 23, 88,
Method.Z_UNPOOLED, 33, true,
new double[] {6.838950390748158},
@@ -509,7 +537,7 @@ class UnconditionedExactTestTest {
builder.add(Arguments.of(8, 2, 1, 5,
Method.BOSCHLOO, 33, true,
new double[] {0.034965034965000003, 0.024475524475524483,
0.9991258741258742},
- new double[] {0.019304891712500001, 0.012192436131969697,
0.9870565910170339}, 1e-12, 4e-10));
+ new double[] {0.019304891712500001, 0.012192436131969697,
0.9870565910170339}, 1.1e-12, 4e-10));
// SciPy example for Boschloo's test
// BoschlooExactResult(statistic=0.048312210086912236,
pvalue=0.0711281286030935)
@@ -621,4 +649,211 @@ class UnconditionedExactTestTest {
return builder.build();
}
+
+ /**
+ * Test the Z pooled or unpooled statistic.
+ *
+ * <p>This test compares the Z value with one computed using an exact
Z-squared
+ * BigFraction. This can be converted to double (0.5 ULP rounding error)
and the square root
+ * is the closest representable Z.
+ *
+ * <p>If the number of tables is small, the logic to identify more extreme
tables is
+ * tested. It is assumed that if the tables are correctly identified, the
remaining
+ * p-value computation with the optimised search for the nuisance
parameter will
+ * be correct as it only requires the tables and not the Z statistic.
+ *
+ * <p>Note: STATISTICS-104 describes cases where the more extreme tables
are incorrect
+ * due to rounding error in Z. For example 1 - 1/3 is not equal magnitude
to 0 - 2/3. This
+ * creates Z values that should have equal magnitude fail the {@code <=}
comparison.
+ * The cases here passed if the original implementation for Z using double
probabilities
+ * p0 = a/m and p1 = b/n used a 3 ULP tolerance for equality on Z. The new
version
+ * uses rational numbers to represent the probabilities and omits a final
common denominator
+ * which is constant. This reduces rounding errors. These cases pass with
0 ULP
+ * tolerance. However this increased accuracy means that the
implementation differs
+ * from reference implementations in R or scipy.stats. This fixture
validates the
+ * inference test is functioning as expected when identifying extreme
tables.
+ */
+ @ParameterizedTest
+ @MethodSource(value = {"testZ"})
+ void testZ(int a, int b, int c, int d, Method method) {
+ final int[][] table = {{a, b}, {c, d}};
+ UnconditionedExactTest test =
UnconditionedExactTest.withDefaults().with(method);
+ final double statistic = test.statistic(table);
+ final int m = a + c;
+ final int n = b + d;
+ final boolean pooled = method == Method.Z_POOLED;
+ final double z = z(a, b, m, n, pooled);
+ // Equal to 1 ULP
+ TestUtils.assertRelativelyEquals(z, statistic, 0x1p-52, "statistic");
+
+ // Check symmetry (reversed columns get the reversed Z score).
+ final int[][] table2 = {{b, a}, {d, c}};
+ final double statistic2 = test.statistic(table2);
+ Assertions.assertEquals(statistic, 0 - statistic2);
+
+ // If the number of tables is small compute all the z-squared values.
+ // Then test the division of z into more extreme tables using the
+ // alternate hypothesis.
+ final long total = (m + 1L) * (n + 1L);
+ if (total > 1000000) {
+ // This is here to prevent very large cases.
+ // The case with ~200000 tables runs in less than 0.5 seconds.
+ Assertions.fail("Number of tables is too high: " + total);
+ }
+ final int n1 = n + 1;
+ final BigFraction[] zz = new BigFraction[(int) total];
+ for (int i = 0; i <= m; i++) {
+ for (int j = 0; j <= n; j++) {
+ zz[i * n1 + j] = zSquared(i, j, m, n, pooled);
+ }
+ }
+ for (final AlternativeHypothesis h : AlternativeHypothesis.values()) {
+ final XYList actual = new XYList(m, n);
+ test.with(h).findExtremeTablesZ(a, b, m, n, pooled, actual);
+
+ final BigFraction t = zz[a * n1 + b];
+ // The z-squared value is exact so the comparison <= or >= is exact
+ final Predicate<BigFraction> check;
+ if (h == AlternativeHypothesis.GREATER_THAN) {
+ check = z2 -> z2.compareTo(t) >= 0;
+ } else if (h == AlternativeHypothesis.LESS_THAN) {
+ check = z2 -> z2.compareTo(t) <= 0;
+ } else {
+ // two-sided
+ if (t.signum() == 0) {
+ // Early exit: all tables are as extreme
+ continue;
+ }
+ final BigFraction tt = t.abs();
+ check = z2 -> z2.abs().compareTo(tt) >= 0;
+ }
+ final BitSet expected = new BitSet((int) total);
+ for (int i = 0; i <= m; i++) {
+ for (int j = 0; j <= n; j++) {
+ if (check.test(zz[i * n1 + j])) {
+ expected.set(j * actual.getWidth() + i);
+ }
+ }
+ }
+ Assertions.assertEquals(expected.cardinality(), actual.size(),
+ () -> "Size mismatch: " + h);
+ // Extract actual indices
+ final BitSet actualIndices = new BitSet((int) total);
+ for (int i = 0; i < actual.size(); i++) {
+ actualIndices.set(actual.get(i));
+ }
+ Assertions.assertEquals(expected, actualIndices, "index mismatch");
+
+ // Swap the columns. The result is reversed.
+ // Swap hypothesis
+ AlternativeHypothesis h2 = AlternativeHypothesis.TWO_SIDED;
+ if (h == AlternativeHypothesis.GREATER_THAN) {
+ h2 = AlternativeHypothesis.LESS_THAN;
+ } else if (h == AlternativeHypothesis.LESS_THAN) {
+ h2 = AlternativeHypothesis.GREATER_THAN;
+ }
+ // process (n, m) instead of (m, n)
+ final XYList actualReversed = new XYList(n, m);
+ test.with(h2).findExtremeTablesZ(b, a, n, m, pooled,
actualReversed);
+
+ Assertions.assertEquals(expected.cardinality(),
actualReversed.size(),
+ () -> "Size mismatch (reversed columns): " + h);
+ // Get the original indices
+ final BitSet expectedReversed = new BitSet(m * n);
+ expected.stream().forEach(index -> {
+ final int x = index % actual.getWidth();
+ final int y = index / actual.getWidth();
+ // This swaps y * w + x and uses the reversed width
+ expectedReversed.set(x * actualReversed.getWidth() + y);
+ });
+ actualIndices.clear();
+ for (int i = 0; i < actualReversed.size(); i++) {
+ actualIndices.set(actualReversed.get(i));
+ }
+ Assertions.assertEquals(expectedReversed, actualIndices, "index
mismatch (reversed columns)");
+ }
+ }
+
+ static Stream<Arguments> testZ() {
+ // Note that computation of the Z statistic has rounding error.
+ // This tests the computation against a high-precision reference.
+
+ final Stream.Builder<Arguments> builder = Stream.builder();
+ final Method[] methods = {Method.Z_POOLED, Method.Z_UNPOOLED};
+ for (final Method m : methods) {
+ builder.add(Arguments.of(7, 12, 8, 3, m));
+ builder.add(Arguments.of(8, 2, 1, 5, m));
+ builder.add(Arguments.of(74, 31, 43, 32, m));
+ builder.add(Arguments.of(67, 42, 23, 88, m));
+ builder.add(Arguments.of(7, 12, 7, 12, m));
+ builder.add(Arguments.of(123, 92, 424, 113, m));
+ builder.add(Arguments.of(123, 92, 424, 313, m));
+ // Some Z are infinite
+ builder.add(Arguments.of(1, 0, 0, 1, m));
+ builder.add(Arguments.of(0, 1, 1, 0, m));
+ // STATISTICS-104
+ builder.add(Arguments.of(1, 1, 0, 2, m));
+ }
+ return builder.build();
+ }
+
+ /**
+ * Compute the exact value of Z squared. This is signed to allow the
closest
+ * equivalent double to be obtained. Does not fully support infinite Z. In
this case
+ * the result is a signed value of 2^1024. Conversion to double will be
the correct
+ * signed infinity.
+ *
+ * @param a Observed value for a.
+ * @param b Observed value for b.
+ * @param m Column sum m.
+ * @param n Column sum n.
+ * @param pooled true to use a pooled variance.
+ * @return signed Z^2
+ */
+ static BigFraction zSquared(int a, int b, int m, int n, boolean pooled) {
+ final BigFraction p0 = BigFraction.of(a, m);
+ final BigFraction p1 = BigFraction.of(b, n);
+ BigFraction delta = p0.subtract(p1);
+ final int sign = delta.signum();
+ if (sign == 0) {
+ return BigFraction.ZERO;
+ }
+ // Compute the variance
+ final BigFraction v;
+ if (pooled) {
+ // p = (a+b) / (m+n)
+ // v = p * (1-p) * (1/m + 1/n)
+ final BigFraction p = BigFraction.of((long) a + b, (long) m + n);
+ final BigFraction f = BigFraction.of(1, m).add(BigFraction.of(1,
n));
+ v = p.multiply(BigFraction.ONE.subtract(p)).multiply(f);
+ } else {
+ // v = p0 * (1 - p0) / m + p1 * (1 - p1) / n
+ final BigFraction v1 =
p0.multiply(BigFraction.ONE.subtract(p0)).divide(m);
+ final BigFraction v2 =
p1.multiply(BigFraction.ONE.subtract(p1)).divide(n);
+ v = v1.add(v2);
+ }
+ if (v.signum() == 0) {
+ // delta / 0 = infinity
+ final BigInteger large = BigInteger.ONE.shiftLeft(1024);
+ return BigFraction.of(sign < 0 ? large.negate() : large);
+ }
+ // z = (p0 - p1) / sqrt(v)
+ // Return signed zSquared
+ return delta.multiply(delta.abs()).divide(v);
+ }
+
+ /**
+ * Compute the closest representable double value of Z.
+ *
+ * @param a Observed value for a.
+ * @param b Observed value for b.
+ * @param m Column sum m.
+ * @param n Column sum n.
+ * @param pooled true to use a pooled variance.
+ * @return z
+ */
+ static double z(int a, int b, int m, int n, boolean pooled) {
+ final BigFraction zz = zSquared(a, b, m, n, pooled);
+ return Math.copySign(Math.sqrt(zz.abs().doubleValue()), zz.signum());
+ }
}
diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 24645a30..529b4518 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -53,6 +53,22 @@ If the output is not quite correct, check for invisible
trailing spaces!
</properties>
<body>
<release version="1.4" date="TBD" description="Adds new features (requires
Java 8).">
+ <action dev="aherbert" type="fix" due-to="Alex Herbert, Eran Shaham"
issue="STATISTICS-104">
+ "distribution/inference": Improve values used for inference
comparisons.
+ This changes the binomial and hypergeometric distributions and the
+ BinomialTest, FisherExactTest and UnconditionedExactTest.
+ The inference tests compare values using less-than-or-equal-to.
+ Rounding errors in the computation for values that should be exactly
equal
+ caused the p-value for the statistic to have high error.
+ Exactly equal values occur due to symmetry in the underlying binomial
+ and hypergeometric distributions. These distributions are now symmetric
+ at the mode when bimodal; the binomial distribution is symmetric when
+ the probability of success is 0.5; the hypergeometric distribution
+ has parameter symmetry for number of successes (K) and sample size (n),
+ and supports symmetry when either K or n = N / 2 where N is the
+ population size. The computation of the Z statistic for the
+ UnconditionedExactTest was reimplemented to reduce rounding error.
+ </action>
<action dev="aherbert" type="add" due-to="Alex Herbert"
issue="STATISTICS-101">
"ZetaDistribution": Add a zeta distribution. This is the large N limit
of the ZipfDistribution.
diff --git a/src/conf/pmd/pmd-ruleset.xml b/src/conf/pmd/pmd-ruleset.xml
index ffb7b922..b23f0b08 100644
--- a/src/conf/pmd/pmd-ruleset.xml
+++ b/src/conf/pmd/pmd-ruleset.xml
@@ -182,7 +182,8 @@
value="./ancestor-or-self::ClassDeclaration[@SimpleName='AbstractContinuousDistribution'
or @SimpleName='KolmogorovSmirnovTest' or
@SimpleName='KolmogorovSmirnovDistribution'
or @SimpleName='MannWhitneyUTest' or @SimpleName='BracketFinder'
- or @SimpleName='BrentOptimizer' or
@SimpleName='UnconditionedExactTest']"/>
+ or @SimpleName='BrentOptimizer' or
@SimpleName='UnconditionedExactTest'
+ or @SimpleName='SaddlePointExpansionUtils']"/>
</properties>
</rule>
<rule ref="category/java/design.xml/GodClass">
diff --git a/src/conf/spotbugs/spotbugs-exclude-filter.xml
b/src/conf/spotbugs/spotbugs-exclude-filter.xml
index 1d0ba089..620b24af 100644
--- a/src/conf/spotbugs/spotbugs-exclude-filter.xml
+++ b/src/conf/spotbugs/spotbugs-exclude-filter.xml
@@ -35,6 +35,7 @@
<Or>
<Method name="getStirlingError" />
<Method name="getDeviancePart" />
+ <Method name="logBinomialProbability" />
</Or>
<Bug pattern="FE_FLOATING_POINT_EQUALITY" />
</Match>
@@ -66,6 +67,13 @@
<Bug pattern="FE_FLOATING_POINT_EQUALITY" />
</Match>
+ <!-- Testing the mode as a double is an integer -->
+ <Match>
+ <Class
name="org.apache.commons.statistics.distribution.HypergeometricDistribution" />
+ <Method name="<init>"/>
+ <Bug pattern="FE_FLOATING_POINT_EQUALITY" />
+ </Match>
+
<!-- Intentional use of floating-point loop counters -->
<Match>
<Class
name="org.apache.commons.statistics.distribution.AbstractContinuousDistribution"
/>