View Javadoc
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  
19  import org.apache.commons.statistics.distribution.NormalDistribution;
20  import org.apache.commons.math4.legacy.exception.ConvergenceException;
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.stat.ranking.NaNStrategy;
25  import org.apache.commons.math4.legacy.stat.ranking.NaturalRanking;
26  import org.apache.commons.math4.legacy.stat.ranking.TiesStrategy;
27  import org.apache.commons.math4.core.jdkmath.JdkMath;
28  
29  import java.util.stream.IntStream;
30  
31  /**
32   * An implementation of the Mann-Whitney U test (also called Wilcoxon rank-sum test).
33   *
34   */
35  public class MannWhitneyUTest {
36  
37      /** Ranking algorithm. */
38      private NaturalRanking naturalRanking;
39  
40      /**
41       * Create a test instance using where NaN's are left in place and ties get
42       * the average of applicable ranks. Use this unless you are very sure of
43       * what you are doing.
44       */
45      public MannWhitneyUTest() {
46          naturalRanking = new NaturalRanking(NaNStrategy.FIXED,
47                  TiesStrategy.AVERAGE);
48      }
49  
50      /**
51       * Create a test instance using the given strategies for NaN's and ties.
52       * Only use this if you are sure of what you are doing.
53       *
54       * @param nanStrategy
55       *            specifies the strategy that should be used for Double.NaN's
56       * @param tiesStrategy
57       *            specifies the strategy that should be used for ties
58       */
59      public MannWhitneyUTest(final NaNStrategy nanStrategy,
60                              final TiesStrategy tiesStrategy) {
61          naturalRanking = new NaturalRanking(nanStrategy, tiesStrategy);
62      }
63  
64      /**
65       * Ensures that the provided arrays fulfills the assumptions.
66       *
67       * @param x first sample
68       * @param y second sample
69       * @throws NullArgumentException if {@code x} or {@code y} are {@code null}.
70       * @throws NoDataException if {@code x} or {@code y} are zero-length.
71       */
72      private void ensureDataConformance(final double[] x, final double[] y)
73          throws NullArgumentException, NoDataException {
74  
75          if (x == null ||
76              y == null) {
77              throw new NullArgumentException();
78          }
79          if (x.length == 0 ||
80              y.length == 0) {
81              throw new NoDataException();
82          }
83      }
84  
85      /** Concatenate the samples into one array.
86       * @param x first sample
87       * @param y second sample
88       * @return concatenated array
89       */
90      private double[] concatenateSamples(final double[] x, final double[] y) {
91          final double[] z = new double[x.length + y.length];
92  
93          System.arraycopy(x, 0, z, 0, x.length);
94          System.arraycopy(y, 0, z, x.length, y.length);
95  
96          return z;
97      }
98  
99      /**
100      * Computes the <a
101      * href="http://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U"> Mann-Whitney
102      * U statistic</a> comparing mean for two independent samples possibly of
103      * different length.
104      * <p>
105      * This statistic can be used to perform a Mann-Whitney U test evaluating
106      * the null hypothesis that the two independent samples has equal mean.
107      * </p>
108      * <p>
109      * Let X<sub>i</sub> denote the i'th individual of the first sample and
110      * Y<sub>j</sub> the j'th individual in the second sample. Note that the
111      * samples would often have different length.
112      * </p>
113      * <p>
114      * <strong>Preconditions</strong>:
115      * <ul>
116      * <li>All observations in the two samples are independent.</li>
117      * <li>The observations are at least ordinal (continuous are also ordinal).</li>
118      * </ul>
119      *
120      * @param x the first sample
121      * @param y the second sample
122      * @return Mann-Whitney U statistic (minimum of U<sup>x</sup> and U<sup>y</sup>)
123      * @throws NullArgumentException if {@code x} or {@code y} are {@code null}.
124      * @throws NoDataException if {@code x} or {@code y} are zero-length.
125      */
126     public double mannWhitneyU(final double[] x, final double[] y)
127         throws NullArgumentException, NoDataException {
128 
129         ensureDataConformance(x, y);
130 
131         final double[] z = concatenateSamples(x, y);
132         final double[] ranks = naturalRanking.rank(z);
133 
134         double sumRankX = 0;
135 
136         /*
137          * The ranks for x is in the first x.length entries in ranks because x
138          * is in the first x.length entries in z
139          */
140         sumRankX = IntStream.range(0, x.length).mapToDouble(i -> ranks[i]).sum();
141 
142         /*
143          * U1 = R1 - (n1 * (n1 + 1)) / 2 where R1 is sum of ranks for sample 1,
144          * e.g. x, n1 is the number of observations in sample 1.
145          */
146         final double u1 = sumRankX - ((long) x.length * (x.length + 1)) / 2;
147 
148         /*
149          * It can be shown that U1 + U2 = n1 * n2
150          */
151         final double u2 = (long) x.length * y.length - u1;
152 
153         return JdkMath.min(u1, u2);
154     }
155 
156     /**
157      * @param umin smallest Mann-Whitney U value
158      * @param n1 number of subjects in first sample
159      * @param n2 number of subjects in second sample
160      * @return two-sided asymptotic p-value
161      * @throws ConvergenceException if the p-value can not be computed
162      * due to a convergence error
163      * @throws MaxCountExceededException if the maximum number of
164      * iterations is exceeded
165      */
166     private double calculateAsymptoticPValue(final double umin,
167                                              final int n1,
168                                              final int n2)
169         throws ConvergenceException, MaxCountExceededException {
170 
171         /* long multiplication to avoid overflow (double not used due to efficiency
172          * and to avoid precision loss)
173          */
174         final long n1n2prod = (long) n1 * n2;
175 
176         // http://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U#Normal_approximation
177         final double eU = n1n2prod / 2.0;
178         final double varU = n1n2prod * (n1 + n2 + 1) / 12.0;
179 
180         final double z = (umin - eU) / JdkMath.sqrt(varU);
181 
182         // No try-catch or advertised exception because args are valid
183         // pass a null rng to avoid unneeded overhead as we will not sample from this distribution
184         final NormalDistribution standardNormal = NormalDistribution.of(0, 1);
185 
186         return 2 * standardNormal.cumulativeProbability(z);
187     }
188 
189     /**
190      * Returns the asymptotic <i>observed significance level</i>, or <a href=
191      * "http://www.cas.lancs.ac.uk/glossary_v1.1/hyptest.html#pvalue">
192      * p-value</a>, associated with a <a
193      * href="http://en.wikipedia.org/wiki/Mann%E2%80%93Whitney_U"> Mann-Whitney
194      * U statistic</a> comparing mean for two independent samples.
195      * <p>
196      * Let X<sub>i</sub> denote the i'th individual of the first sample and
197      * Y<sub>j</sub> the j'th individual in the second sample. Note that the
198      * samples would often have different length.
199      * </p>
200      * <p>
201      * <strong>Preconditions</strong>:
202      * <ul>
203      * <li>All observations in the two samples are independent.</li>
204      * <li>The observations are at least ordinal (continuous are also ordinal).</li>
205      * </ul><p>
206      * Ties give rise to biased variance at the moment. See e.g. <a
207      * href="http://mlsc.lboro.ac.uk/resources/statistics/Mannwhitney.pdf"
208      * >http://mlsc.lboro.ac.uk/resources/statistics/Mannwhitney.pdf</a>.</p>;
209      *
210      * @param x the first sample
211      * @param y the second sample
212      * @return asymptotic p-value
213      * @throws NullArgumentException if {@code x} or {@code y} are {@code null}.
214      * @throws NoDataException if {@code x} or {@code y} are zero-length.
215      * @throws ConvergenceException if the p-value can not be computed due to a
216      * convergence error
217      * @throws MaxCountExceededException if the maximum number of iterations
218      * is exceeded
219      */
220     public double mannWhitneyUTest(final double[] x, final double[] y)
221         throws NullArgumentException, NoDataException,
222         ConvergenceException, MaxCountExceededException {
223 
224         ensureDataConformance(x, y);
225 
226         final double uMin = mannWhitneyU(x, y);
227 
228         return calculateAsymptoticPValue(uMin, x.length, y.length);
229     }
230 }