WilcoxonSignedRankTest.java

  1. /*
  2.  * Licensed to the Apache Software Foundation (ASF) under one or more
  3.  * contributor license agreements.  See the NOTICE file distributed with
  4.  * this work for additional information regarding copyright ownership.
  5.  * The ASF licenses this file to You under the Apache License, Version 2.0
  6.  * (the "License"); you may not use this file except in compliance with
  7.  * the License.  You may obtain a copy of the License at
  8.  *
  9.  *      http://www.apache.org/licenses/LICENSE-2.0
  10.  *
  11.  * Unless required by applicable law or agreed to in writing, software
  12.  * distributed under the License is distributed on an "AS IS" BASIS,
  13.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14.  * See the License for the specific language governing permissions and
  15.  * limitations under the License.
  16.  */
  17. package org.apache.commons.math4.legacy.stat.inference;

  18. import org.apache.commons.statistics.distribution.NormalDistribution;
  19. import org.apache.commons.math4.legacy.exception.ConvergenceException;
  20. import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
  21. import org.apache.commons.math4.legacy.exception.MaxCountExceededException;
  22. import org.apache.commons.math4.legacy.exception.NoDataException;
  23. import org.apache.commons.math4.legacy.exception.NullArgumentException;
  24. import org.apache.commons.math4.legacy.exception.NumberIsTooLargeException;
  25. import org.apache.commons.math4.legacy.stat.ranking.NaNStrategy;
  26. import org.apache.commons.math4.legacy.stat.ranking.NaturalRanking;
  27. import org.apache.commons.math4.legacy.stat.ranking.TiesStrategy;
  28. import org.apache.commons.math4.core.jdkmath.JdkMath;

  29. /**
  30.  * An implementation of the Wilcoxon signed-rank test.
  31.  *
  32.  */
  33. public class WilcoxonSignedRankTest {

  34.     /** Ranking algorithm. */
  35.     private NaturalRanking naturalRanking;

  36.     /**
  37.      * Create a test instance where NaN's are left in place and ties get
  38.      * the average of applicable ranks. Use this unless you are very sure
  39.      * of what you are doing.
  40.      */
  41.     public WilcoxonSignedRankTest() {
  42.         naturalRanking = new NaturalRanking(NaNStrategy.FIXED,
  43.                 TiesStrategy.AVERAGE);
  44.     }

  45.     /**
  46.      * Create a test instance using the given strategies for NaN's and ties.
  47.      * Only use this if you are sure of what you are doing.
  48.      *
  49.      * @param nanStrategy
  50.      *            specifies the strategy that should be used for Double.NaN's
  51.      * @param tiesStrategy
  52.      *            specifies the strategy that should be used for ties
  53.      */
  54.     public WilcoxonSignedRankTest(final NaNStrategy nanStrategy,
  55.                                   final TiesStrategy tiesStrategy) {
  56.         naturalRanking = new NaturalRanking(nanStrategy, tiesStrategy);
  57.     }

  58.     /**
  59.      * Ensures that the provided arrays fulfills the assumptions.
  60.      *
  61.      * @param x first sample
  62.      * @param y second sample
  63.      * @throws NullArgumentException if {@code x} or {@code y} are {@code null}.
  64.      * @throws NoDataException if {@code x} or {@code y} are zero-length.
  65.      * @throws DimensionMismatchException if {@code x} and {@code y} do not
  66.      * have the same length.
  67.      */
  68.     private void ensureDataConformance(final double[] x, final double[] y)
  69.         throws NullArgumentException, NoDataException, DimensionMismatchException {

  70.         if (x == null ||
  71.             y == null) {
  72.                 throw new NullArgumentException();
  73.         }
  74.         if (x.length == 0 ||
  75.             y.length == 0) {
  76.             throw new NoDataException();
  77.         }
  78.         if (y.length != x.length) {
  79.             throw new DimensionMismatchException(y.length, x.length);
  80.         }
  81.     }

  82.     /**
  83.      * Calculates y[i] - x[i] for all i.
  84.      *
  85.      * @param x first sample
  86.      * @param y second sample
  87.      * @return z = y - x
  88.      */
  89.     private double[] calculateDifferences(final double[] x, final double[] y) {

  90.         final double[] z = new double[x.length];

  91.         for (int i = 0; i < x.length; ++i) {
  92.             z[i] = y[i] - x[i];
  93.         }

  94.         return z;
  95.     }

  96.     /**
  97.      * Calculates |z[i]| for all i.
  98.      *
  99.      * @param z sample
  100.      * @return |z|
  101.      * @throws NullArgumentException if {@code z} is {@code null}
  102.      * @throws NoDataException if {@code z} is zero-length.
  103.      */
  104.     private double[] calculateAbsoluteDifferences(final double[] z)
  105.         throws NullArgumentException, NoDataException {

  106.         if (z == null) {
  107.             throw new NullArgumentException();
  108.         }

  109.         if (z.length == 0) {
  110.             throw new NoDataException();
  111.         }

  112.         final double[] zAbs = new double[z.length];

  113.         for (int i = 0; i < z.length; ++i) {
  114.             zAbs[i] = JdkMath.abs(z[i]);
  115.         }

  116.         return zAbs;
  117.     }

  118.     /**
  119.      * Computes the <a
  120.      * href="http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test">
  121.      * Wilcoxon signed ranked statistic</a> comparing mean for two related
  122.      * samples or repeated measurements on a single sample.
  123.      * <p>
  124.      * This statistic can be used to perform a Wilcoxon signed ranked test
  125.      * evaluating the null hypothesis that the two related samples or repeated
  126.      * measurements on a single sample has equal mean.
  127.      * </p>
  128.      * <p>
  129.      * Let X<sub>i</sub> denote the i'th individual of the first sample and
  130.      * Y<sub>i</sub> the related i'th individual in the second sample. Let
  131.      * Z<sub>i</sub> = Y<sub>i</sub> - X<sub>i</sub>.
  132.      * </p>
  133.      * <p>
  134.      * <strong>Preconditions</strong>:
  135.      * <ul>
  136.      * <li>The differences Z<sub>i</sub> must be independent.</li>
  137.      * <li>Each Z<sub>i</sub> comes from a continuous population (they must be
  138.      * identical) and is symmetric about a common median.</li>
  139.      * <li>The values that X<sub>i</sub> and Y<sub>i</sub> represent are
  140.      * ordered, so the comparisons greater than, less than, and equal to are
  141.      * meaningful.</li>
  142.      * </ul>
  143.      *
  144.      * @param x the first sample
  145.      * @param y the second sample
  146.      * @return wilcoxonSignedRank statistic (the larger of W+ and W-)
  147.      * @throws NullArgumentException if {@code x} or {@code y} are {@code null}.
  148.      * @throws NoDataException if {@code x} or {@code y} are zero-length.
  149.      * @throws DimensionMismatchException if {@code x} and {@code y} do not
  150.      * have the same length.
  151.      */
  152.     public double wilcoxonSignedRank(final double[] x, final double[] y)
  153.         throws NullArgumentException, NoDataException, DimensionMismatchException {

  154.         ensureDataConformance(x, y);

  155.         // throws IllegalArgumentException if x and y are not correctly
  156.         // specified
  157.         final double[] z = calculateDifferences(x, y);
  158.         final double[] zAbs = calculateAbsoluteDifferences(z);

  159.         final double[] ranks = naturalRanking.rank(zAbs);

  160.         double wPlus = 0;

  161.         for (int i = 0; i < z.length; ++i) {
  162.             if (z[i] > 0) {
  163.                 wPlus += ranks[i];
  164.             }
  165.         }

  166.         final int n = x.length;
  167.         final double wMinus = (((double) (n * (n + 1))) / 2.0) - wPlus;

  168.         return JdkMath.max(wPlus, wMinus);
  169.     }

  170.     /**
  171.      * Algorithm inspired by.
  172.      * http://www.fon.hum.uva.nl/Service/Statistics/Signed_Rank_Algorihms.html#C
  173.      * by Rob van Son, Institute of Phonetic Sciences & IFOTT,
  174.      * University of Amsterdam
  175.      *
  176.      * @param wMax largest Wilcoxon signed rank value
  177.      * @param n number of subjects (corresponding to x.length)
  178.      * @return two-sided exact p-value
  179.      */
  180.     private double calculateExactPValue(final double wMax, final int n) {

  181.         // Total number of outcomes (equal to 2^N but a lot faster)
  182.         final int m = 1 << n;

  183.         int largerRankSums = 0;

  184.         for (int i = 0; i < m; ++i) {
  185.             int rankSum = 0;

  186.             // Generate all possible rank sums
  187.             for (int j = 0; j < n; ++j) {

  188.                 // (i >> j) & 1 extract i's j-th bit from the right
  189.                 if (((i >> j) & 1) == 1) {
  190.                     rankSum += j + 1;
  191.                 }
  192.             }

  193.             if (rankSum >= wMax) {
  194.                 ++largerRankSums;
  195.             }
  196.         }

  197.         /*
  198.          * largerRankSums / m gives the one-sided p-value, so it's multiplied
  199.          * with 2 to get the two-sided p-value
  200.          */
  201.         return 2 * ((double) largerRankSums) / ((double) m);
  202.     }

  203.     /**
  204.      * @param wMin smallest Wilcoxon signed rank value
  205.      * @param n number of subjects (corresponding to x.length)
  206.      * @return two-sided asymptotic p-value
  207.      */
  208.     private double calculateAsymptoticPValue(final double wMin, final int n) {

  209.         final double es = (double) (n * (n + 1)) / 4.0;

  210.         /* Same as (but saves computations):
  211.          * final double VarW = ((double) (N * (N + 1) * (2*N + 1))) / 24;
  212.          */
  213.         final double varS = es * ((double) (2 * n + 1) / 6.0);

  214.         // - 0.5 is a continuity correction
  215.         final double z = (wMin - es - 0.5) / JdkMath.sqrt(varS);

  216.         // No try-catch or advertised exception because args are valid
  217.         // pass a null rng to avoid unneeded overhead as we will not sample from this distribution
  218.         final NormalDistribution standardNormal = NormalDistribution.of(0, 1);

  219.         return 2*standardNormal.cumulativeProbability(z);
  220.     }

  221.     /**
  222.      * Returns the <i>observed significance level</i>, or <a href=
  223.      * "http://www.cas.lancs.ac.uk/glossary_v1.1/hyptest.html#pvalue">
  224.      * p-value</a>, associated with a <a
  225.      * href="http://en.wikipedia.org/wiki/Wilcoxon_signed-rank_test">
  226.      * Wilcoxon signed ranked statistic</a> comparing mean for two related
  227.      * samples or repeated measurements on a single sample.
  228.      * <p>
  229.      * Let X<sub>i</sub> denote the i'th individual of the first sample and
  230.      * Y<sub>i</sub> the related i'th individual in the second sample. Let
  231.      * Z<sub>i</sub> = Y<sub>i</sub> - X<sub>i</sub>.
  232.      * </p>
  233.      * <p>
  234.      * <strong>Preconditions</strong>:
  235.      * <ul>
  236.      * <li>The differences Z<sub>i</sub> must be independent.</li>
  237.      * <li>Each Z<sub>i</sub> comes from a continuous population (they must be
  238.      * identical) and is symmetric about a common median.</li>
  239.      * <li>The values that X<sub>i</sub> and Y<sub>i</sub> represent are
  240.      * ordered, so the comparisons greater than, less than, and equal to are
  241.      * meaningful.</li>
  242.      * </ul>
  243.      *
  244.      * @param x the first sample
  245.      * @param y the second sample
  246.      * @param exactPValue
  247.      *            if the exact p-value is wanted (only works for x.length &gt;= 30,
  248.      *            if true and x.length &lt; 30, this is ignored because
  249.      *            calculations may take too long)
  250.      * @return p-value
  251.      * @throws NullArgumentException if {@code x} or {@code y} are {@code null}.
  252.      * @throws NoDataException if {@code x} or {@code y} are zero-length.
  253.      * @throws DimensionMismatchException if {@code x} and {@code y} do not
  254.      * have the same length.
  255.      * @throws NumberIsTooLargeException if {@code exactPValue} is {@code true}
  256.      * and {@code x.length} &gt; 30
  257.      * @throws ConvergenceException if the p-value can not be computed due to
  258.      * a convergence error
  259.      * @throws MaxCountExceededException if the maximum number of iterations
  260.      * is exceeded
  261.      */
  262.     public double wilcoxonSignedRankTest(final double[] x, final double[] y,
  263.                                          final boolean exactPValue)
  264.         throws NullArgumentException, NoDataException, DimensionMismatchException,
  265.         NumberIsTooLargeException, ConvergenceException, MaxCountExceededException {

  266.         ensureDataConformance(x, y);

  267.         final int n = x.length;
  268.         final double wMax = wilcoxonSignedRank(x, y);

  269.         if (exactPValue && n > 30) {
  270.             throw new NumberIsTooLargeException(n, 30, true);
  271.         }

  272.         if (exactPValue) {
  273.             return calculateExactPValue(wMax, n);
  274.         } else {
  275.             final double wMin = ( (double)(n*(n+1)) / 2.0 ) - wMax;
  276.             return calculateAsymptoticPValue(wMin, n);
  277.         }
  278.     }
  279. }