ChiSquareTest.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.ChiSquaredDistribution;
  19. import org.apache.commons.math4.legacy.exception.DimensionMismatchException;
  20. import org.apache.commons.math4.legacy.exception.MaxCountExceededException;
  21. import org.apache.commons.math4.legacy.exception.NotPositiveException;
  22. import org.apache.commons.math4.legacy.exception.NotStrictlyPositiveException;
  23. import org.apache.commons.math4.legacy.exception.NullArgumentException;
  24. import org.apache.commons.math4.legacy.exception.OutOfRangeException;
  25. import org.apache.commons.math4.legacy.exception.ZeroException;
  26. import org.apache.commons.math4.legacy.exception.util.LocalizedFormats;
  27. import org.apache.commons.math4.core.jdkmath.JdkMath;
  28. import org.apache.commons.math4.legacy.core.MathArrays;

  29. /**
  30.  * Implements Chi-Square test statistics.
  31.  *
  32.  * <p>This implementation handles both known and unknown distributions.</p>
  33.  *
  34.  * <p>Two samples tests can be used when the distribution is unknown <i>a priori</i>
  35.  * but provided by one sample, or when the hypothesis under test is that the two
  36.  * samples come from the same underlying distribution.</p>
  37.  *
  38.  */
  39. public class ChiSquareTest {

  40.     /**
  41.      * Construct a ChiSquareTest.
  42.      */
  43.     public ChiSquareTest() {
  44.         super();
  45.     }

  46.     /**
  47.      * Computes the <a href="http://www.itl.nist.gov/div898/handbook/eda/section3/eda35f.htm">
  48.      * Chi-Square statistic</a> comparing <code>observed</code> and <code>expected</code>
  49.      * frequency counts.
  50.      * <p>
  51.      * This statistic can be used to perform a Chi-Square test evaluating the null
  52.      * hypothesis that the observed counts follow the expected distribution.</p>
  53.      * <p>
  54.      * <strong>Preconditions</strong>: <ul>
  55.      * <li>Expected counts must all be positive.
  56.      * </li>
  57.      * <li>Observed counts must all be &ge; 0.
  58.      * </li>
  59.      * <li>The observed and expected arrays must have the same length and
  60.      * their common length must be at least 2.
  61.      * </li></ul><p>
  62.      * If any of the preconditions are not met, an
  63.      * <code>IllegalArgumentException</code> is thrown.</p>
  64.      * <p><strong>Note: </strong>This implementation rescales the
  65.      * <code>expected</code> array if necessary to ensure that the sum of the
  66.      * expected and observed counts are equal.</p>
  67.      *
  68.      * @param observed array of observed frequency counts
  69.      * @param expected array of expected frequency counts
  70.      * @return chiSquare test statistic
  71.      * @throws NotPositiveException if <code>observed</code> has negative entries
  72.      * @throws NotStrictlyPositiveException if <code>expected</code> has entries that are
  73.      * not strictly positive
  74.      * @throws DimensionMismatchException if the arrays length is less than 2
  75.      */
  76.     public double chiSquare(final double[] expected, final long[] observed)
  77.         throws NotPositiveException, NotStrictlyPositiveException,
  78.         DimensionMismatchException {

  79.         if (expected.length < 2) {
  80.             throw new DimensionMismatchException(expected.length, 2);
  81.         }
  82.         if (expected.length != observed.length) {
  83.             throw new DimensionMismatchException(expected.length, observed.length);
  84.         }
  85.         MathArrays.checkPositive(expected);
  86.         MathArrays.checkNonNegative(observed);

  87.         double sumExpected = 0d;
  88.         double sumObserved = 0d;
  89.         for (int i = 0; i < observed.length; i++) {
  90.             sumExpected += expected[i];
  91.             sumObserved += observed[i];
  92.         }
  93.         double ratio = 1.0d;
  94.         boolean rescale = false;
  95.         if (JdkMath.abs(sumExpected - sumObserved) > 10E-6) {
  96.             ratio = sumObserved / sumExpected;
  97.             rescale = true;
  98.         }
  99.         double sumSq = 0.0d;
  100.         for (int i = 0; i < observed.length; i++) {
  101.             if (rescale) {
  102.                 final double dev = observed[i] - ratio * expected[i];
  103.                 sumSq += dev * dev / (ratio * expected[i]);
  104.             } else {
  105.                 final double dev = observed[i] - expected[i];
  106.                 sumSq += dev * dev / expected[i];
  107.             }
  108.         }
  109.         return sumSq;
  110.     }

  111.     /**
  112.      * Returns the <i>observed significance level</i>, or <a href=
  113.      * "http://www.cas.lancs.ac.uk/glossary_v1.1/hyptest.html#pvalue">
  114.      * p-value</a>, associated with a
  115.      * <a href="http://www.itl.nist.gov/div898/handbook/eda/section3/eda35f.htm">
  116.      * Chi-square goodness of fit test</a> comparing the <code>observed</code>
  117.      * frequency counts to those in the <code>expected</code> array.
  118.      * <p>
  119.      * The number returned is the smallest significance level at which one can reject
  120.      * the null hypothesis that the observed counts conform to the frequency distribution
  121.      * described by the expected counts.</p>
  122.      * <p>
  123.      * <strong>Preconditions</strong>: <ul>
  124.      * <li>Expected counts must all be positive.
  125.      * </li>
  126.      * <li>Observed counts must all be &ge; 0.
  127.      * </li>
  128.      * <li>The observed and expected arrays must have the same length and
  129.      * their common length must be at least 2.
  130.      * </li></ul><p>
  131.      * If any of the preconditions are not met, an
  132.      * <code>IllegalArgumentException</code> is thrown.</p>
  133.      * <p><strong>Note: </strong>This implementation rescales the
  134.      * <code>expected</code> array if necessary to ensure that the sum of the
  135.      * expected and observed counts are equal.</p>
  136.      *
  137.      * @param observed array of observed frequency counts
  138.      * @param expected array of expected frequency counts
  139.      * @return p-value
  140.      * @throws NotPositiveException if <code>observed</code> has negative entries
  141.      * @throws NotStrictlyPositiveException if <code>expected</code> has entries that are
  142.      * not strictly positive
  143.      * @throws DimensionMismatchException if the arrays length is less than 2
  144.      * @throws MaxCountExceededException if an error occurs computing the p-value
  145.      */
  146.     public double chiSquareTest(final double[] expected, final long[] observed)
  147.         throws NotPositiveException, NotStrictlyPositiveException,
  148.         DimensionMismatchException, MaxCountExceededException {

  149.         // pass a null rng to avoid unneeded overhead as we will not sample from this distribution
  150.         final ChiSquaredDistribution distribution =
  151.             ChiSquaredDistribution.of(expected.length - 1.0);
  152.         return distribution.survivalProbability(chiSquare(expected, observed));
  153.     }

  154.     /**
  155.      * Performs a <a href="http://www.itl.nist.gov/div898/handbook/eda/section3/eda35f.htm">
  156.      * Chi-square goodness of fit test</a> evaluating the null hypothesis that the
  157.      * observed counts conform to the frequency distribution described by the expected
  158.      * counts, with significance level <code>alpha</code>.  Returns true iff the null
  159.      * hypothesis can be rejected with 100 * (1 - alpha) percent confidence.
  160.      * <p>
  161.      * <strong>Example:</strong><br>
  162.      * To test the hypothesis that <code>observed</code> follows
  163.      * <code>expected</code> at the 99% level, use </p><p>
  164.      * <code>chiSquareTest(expected, observed, 0.01) </code></p>
  165.      * <p>
  166.      * <strong>Preconditions</strong>: <ul>
  167.      * <li>Expected counts must all be positive.
  168.      * </li>
  169.      * <li>Observed counts must all be &ge; 0.
  170.      * </li>
  171.      * <li>The observed and expected arrays must have the same length and
  172.      * their common length must be at least 2.
  173.      * <li> <code> 0 &lt; alpha &lt; 0.5 </code>
  174.      * </li></ul><p>
  175.      * If any of the preconditions are not met, an
  176.      * <code>IllegalArgumentException</code> is thrown.</p>
  177.      * <p><strong>Note: </strong>This implementation rescales the
  178.      * <code>expected</code> array if necessary to ensure that the sum of the
  179.      * expected and observed counts are equal.</p>
  180.      *
  181.      * @param observed array of observed frequency counts
  182.      * @param expected array of expected frequency counts
  183.      * @param alpha significance level of the test
  184.      * @return true iff null hypothesis can be rejected with confidence
  185.      * 1 - alpha
  186.      * @throws NotPositiveException if <code>observed</code> has negative entries
  187.      * @throws NotStrictlyPositiveException if <code>expected</code> has entries that are
  188.      * not strictly positive
  189.      * @throws DimensionMismatchException if the arrays length is less than 2
  190.      * @throws OutOfRangeException if <code>alpha</code> is not in the range (0, 0.5]
  191.      * @throws MaxCountExceededException if an error occurs computing the p-value
  192.      */
  193.     public boolean chiSquareTest(final double[] expected, final long[] observed,
  194.                                  final double alpha)
  195.         throws NotPositiveException, NotStrictlyPositiveException,
  196.         DimensionMismatchException, OutOfRangeException, MaxCountExceededException {

  197.         if (alpha <= 0 || alpha > 0.5) {
  198.             throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL,
  199.                                           alpha, 0, 0.5);
  200.         }
  201.         return chiSquareTest(expected, observed) < alpha;
  202.     }

  203.     /**
  204.      *  Computes the Chi-Square statistic associated with a
  205.      * <a href="http://www.itl.nist.gov/div898/handbook/prc/section4/prc45.htm">
  206.      *  chi-square test of independence</a> based on the input <code>counts</code>
  207.      *  array, viewed as a two-way table.
  208.      * <p>
  209.      * The rows of the 2-way table are
  210.      * <code>count[0], ... , count[count.length - 1] </code></p>
  211.      * <p>
  212.      * <strong>Preconditions</strong>: <ul>
  213.      * <li>All counts must be &ge; 0.
  214.      * </li>
  215.      * <li>The sum of each row and column must be &gt; 0.
  216.      * </li>
  217.      * <li>The count array must be rectangular (i.e. all count[i] subarrays
  218.      *  must have the same length).
  219.      * </li>
  220.      * <li>The 2-way table represented by <code>counts</code> must have at
  221.      *  least 2 columns and at least 2 rows.
  222.      * </li>
  223.      * </ul><p>
  224.      * If any of the preconditions are not met, an
  225.      * <code>IllegalArgumentException</code> is thrown.</p>
  226.      * <p>
  227.      * If a column or row contains only zeros this is invalid input and a
  228.      * <code>ZeroException</code> is thrown. The empty column/row should
  229.      * be removed from the input counts.</p>
  230.      *
  231.      * @param counts array representation of 2-way table
  232.      * @return chiSquare test statistic
  233.      * @throws NullArgumentException if the array is null
  234.      * @throws DimensionMismatchException if the array is not rectangular
  235.      * @throws NotPositiveException if {@code counts} has negative entries
  236.      * @throws ZeroException if the sum of a row or column is zero
  237.      */
  238.     public double chiSquare(final long[][] counts)
  239.         throws NullArgumentException, NotPositiveException,
  240.         DimensionMismatchException {

  241.         checkArray(counts);
  242.         int nRows = counts.length;
  243.         int nCols = counts[0].length;

  244.         // compute row, column and total sums
  245.         double[] rowSum = new double[nRows];
  246.         double[] colSum = new double[nCols];
  247.         double total = 0.0d;
  248.         for (int row = 0; row < nRows; row++) {
  249.             for (int col = 0; col < nCols; col++) {
  250.                 rowSum[row] += counts[row][col];
  251.                 colSum[col] += counts[row][col];
  252.                 total += counts[row][col];
  253.             }
  254.             checkNonZero(rowSum[row], "row", row);
  255.         }

  256.         for (int col = 0; col < nCols; col++) {
  257.             checkNonZero(colSum[col], "column", col);
  258.         }

  259.         // compute expected counts and chi-square
  260.         double sumSq = 0.0d;
  261.         double expected = 0.0d;
  262.         for (int row = 0; row < nRows; row++) {
  263.             for (int col = 0; col < nCols; col++) {
  264.                 expected = (rowSum[row] * colSum[col]) / total;
  265.                 sumSq += ((counts[row][col] - expected) *
  266.                         (counts[row][col] - expected)) / expected;
  267.             }
  268.         }
  269.         return sumSq;
  270.     }

  271.     /**
  272.      * Returns the <i>observed significance level</i>, or <a href=
  273.      * "http://www.cas.lancs.ac.uk/glossary_v1.1/hyptest.html#pvalue">
  274.      * p-value</a>, associated with a
  275.      * <a href="http://www.itl.nist.gov/div898/handbook/prc/section4/prc45.htm">
  276.      * chi-square test of independence</a> based on the input <code>counts</code>
  277.      * array, viewed as a two-way table.
  278.      * <p>
  279.      * The rows of the 2-way table are
  280.      * <code>count[0], ... , count[count.length - 1] </code></p>
  281.      * <p>
  282.      * <strong>Preconditions</strong>: <ul>
  283.      * <li>All counts must be &ge; 0.
  284.      * </li>
  285.      * <li>The sum of each row and column must be &gt; 0.
  286.      * </li>
  287.      * <li>The count array must be rectangular (i.e. all count[i] subarrays must have
  288.      *     the same length).
  289.      * </li>
  290.      * <li>The 2-way table represented by <code>counts</code> must have at least 2
  291.      *     columns and at least 2 rows.
  292.      * </li>
  293.      * </ul><p>
  294.      * If any of the preconditions are not met, an
  295.      * <code>IllegalArgumentException</code> is thrown.</p>
  296.      * <p>
  297.      * If a column or row contains only zeros this is invalid input and a
  298.      * <code>ZeroException</code> is thrown. The empty column/row should
  299.      * be removed from the input counts.</p>
  300.      *
  301.      * @param counts array representation of 2-way table
  302.      * @return p-value
  303.      * @throws NullArgumentException if the array is null
  304.      * @throws DimensionMismatchException if the array is not rectangular
  305.      * @throws NotPositiveException if {@code counts} has negative entries
  306.      * @throws MaxCountExceededException if an error occurs computing the p-value
  307.      * @throws ZeroException if the sum of a row or column is zero
  308.      */
  309.     public double chiSquareTest(final long[][] counts)
  310.         throws NullArgumentException, DimensionMismatchException,
  311.         NotPositiveException, MaxCountExceededException {

  312.         checkArray(counts);
  313.         double df = ((double) counts.length -1) * ((double) counts[0].length - 1);
  314.         // pass a null rng to avoid unneeded overhead as we will not sample from this distribution
  315.         final ChiSquaredDistribution distribution = ChiSquaredDistribution.of(df);
  316.         return distribution.survivalProbability(chiSquare(counts));
  317.     }

  318.     /**
  319.      * Performs a <a href="http://www.itl.nist.gov/div898/handbook/prc/section4/prc45.htm">
  320.      * chi-square test of independence</a> evaluating the null hypothesis that the
  321.      * classifications represented by the counts in the columns of the input 2-way table
  322.      * are independent of the rows, with significance level <code>alpha</code>.
  323.      * Returns true iff the null hypothesis can be rejected with 100 * (1 - alpha) percent
  324.      * confidence.
  325.      * <p>
  326.      * The rows of the 2-way table are
  327.      * <code>count[0], ... , count[count.length - 1] </code></p>
  328.      * <p>
  329.      * <strong>Example:</strong><br>
  330.      * To test the null hypothesis that the counts in
  331.      * <code>count[0], ... , count[count.length - 1] </code>
  332.      *  all correspond to the same underlying probability distribution at the 99% level, use</p>
  333.      * <p><code>chiSquareTest(counts, 0.01)</code></p>
  334.      * <p>
  335.      * <strong>Preconditions</strong>: <ul>
  336.      * <li>All counts must be &ge; 0.
  337.      * </li>
  338.      * <li>The sum of each row and column must be &gt; 0.
  339.      * </li>
  340.      * <li>The count array must be rectangular (i.e. all count[i] subarrays must have the
  341.      *     same length).</li>
  342.      * <li>The 2-way table represented by <code>counts</code> must have at least 2 columns and
  343.      *     at least 2 rows.</li>
  344.      * </ul><p>
  345.      * If any of the preconditions are not met, an
  346.      * <code>IllegalArgumentException</code> is thrown.</p>
  347.      * <p>
  348.      * If a column or row contains only zeros this is invalid input and a
  349.      * <code>ZeroException</code> is thrown. The empty column/row should
  350.      * be removed from the input counts.</p>
  351.      *
  352.      * @param counts array representation of 2-way table
  353.      * @param alpha significance level of the test
  354.      * @return true iff null hypothesis can be rejected with confidence
  355.      * 1 - alpha
  356.      * @throws NullArgumentException if the array is null
  357.      * @throws DimensionMismatchException if the array is not rectangular
  358.      * @throws NotPositiveException if {@code counts} has any negative entries
  359.      * @throws OutOfRangeException if <code>alpha</code> is not in the range (0, 0.5]
  360.      * @throws MaxCountExceededException if an error occurs computing the p-value
  361.      * @throws ZeroException if the sum of a row or column is zero
  362.      */
  363.     public boolean chiSquareTest(final long[][] counts, final double alpha)
  364.         throws NullArgumentException, DimensionMismatchException,
  365.         NotPositiveException, OutOfRangeException, MaxCountExceededException {

  366.         if (alpha <= 0 || alpha > 0.5) {
  367.             throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL,
  368.                                           alpha, 0, 0.5);
  369.         }
  370.         return chiSquareTest(counts) < alpha;
  371.     }

  372.     /**
  373.      * <p>Computes a
  374.      * <a href="http://www.itl.nist.gov/div898/software/dataplot/refman1/auxillar/chi2samp.htm">
  375.      * Chi-Square two sample test statistic</a> comparing bin frequency counts
  376.      * in <code>observed1</code> and <code>observed2</code>.  The
  377.      * sums of frequency counts in the two samples are not required to be the
  378.      * same.  The formula used to compute the test statistic is</p>
  379.      * <code>
  380.      * &sum;[(K * observed1[i] - observed2[i]/K)<sup>2</sup> / (observed1[i] + observed2[i])]
  381.      * </code> where
  382.      * <br><code>K = &radic;[&sum;(observed2 / &sum;(observed1)]</code>
  383.      *
  384.      * <p>This statistic can be used to perform a Chi-Square test evaluating the
  385.      * null hypothesis that both observed counts follow the same distribution.</p>
  386.      * <p>
  387.      * <strong>Preconditions</strong>: <ul>
  388.      * <li>Observed counts must be non-negative.
  389.      * </li>
  390.      * <li>Observed counts for a specific bin must not both be zero.
  391.      * </li>
  392.      * <li>Observed counts for a specific sample must not all be 0.
  393.      * </li>
  394.      * <li>The arrays <code>observed1</code> and <code>observed2</code> must have
  395.      * the same length and their common length must be at least 2.
  396.      * </li></ul><p>
  397.      * If any of the preconditions are not met, an
  398.      * <code>IllegalArgumentException</code> is thrown.</p>
  399.      *
  400.      * @param observed1 array of observed frequency counts of the first data set
  401.      * @param observed2 array of observed frequency counts of the second data set
  402.      * @return chiSquare test statistic
  403.      * @throws DimensionMismatchException the length of the arrays does not match
  404.      * @throws NotPositiveException if any entries in <code>observed1</code> or
  405.      * <code>observed2</code> are negative
  406.      * @throws ZeroException if either all counts of <code>observed1</code> or
  407.      * <code>observed2</code> are zero, or if the count at some index is zero
  408.      * for both arrays
  409.      * @since 1.2
  410.      */
  411.     public double chiSquareDataSetsComparison(long[] observed1, long[] observed2)
  412.         throws DimensionMismatchException, NotPositiveException, ZeroException {

  413.         // Make sure lengths are same
  414.         if (observed1.length < 2) {
  415.             throw new DimensionMismatchException(observed1.length, 2);
  416.         }
  417.         if (observed1.length != observed2.length) {
  418.             throw new DimensionMismatchException(observed1.length, observed2.length);
  419.         }

  420.         // Ensure non-negative counts
  421.         MathArrays.checkNonNegative(observed1);
  422.         MathArrays.checkNonNegative(observed2);

  423.         // Compute and compare count sums
  424.         long countSum1 = 0;
  425.         long countSum2 = 0;
  426.         boolean unequalCounts = false;
  427.         double weight = 0.0;
  428.         for (int i = 0; i < observed1.length; i++) {
  429.             countSum1 += observed1[i];
  430.             countSum2 += observed2[i];
  431.         }
  432.         // Ensure neither sample is uniformly 0
  433.         if (countSum1 == 0 || countSum2 == 0) {
  434.             throw new ZeroException();
  435.         }
  436.         // Compare and compute weight only if different
  437.         unequalCounts = countSum1 != countSum2;
  438.         if (unequalCounts) {
  439.             weight = JdkMath.sqrt((double) countSum1 / (double) countSum2);
  440.         }
  441.         // Compute ChiSquare statistic
  442.         double sumSq = 0.0d;
  443.         double dev = 0.0d;
  444.         double obs1 = 0.0d;
  445.         double obs2 = 0.0d;
  446.         for (int i = 0; i < observed1.length; i++) {
  447.             if (observed1[i] == 0 && observed2[i] == 0) {
  448.                 throw new ZeroException(LocalizedFormats.OBSERVED_COUNTS_BOTTH_ZERO_FOR_ENTRY, i);
  449.             } else {
  450.                 obs1 = observed1[i];
  451.                 obs2 = observed2[i];
  452.                 if (unequalCounts) { // apply weights
  453.                     dev = obs1/weight - obs2 * weight;
  454.                 } else {
  455.                     dev = obs1 - obs2;
  456.                 }
  457.                 sumSq += (dev * dev) / (obs1 + obs2);
  458.             }
  459.         }
  460.         return sumSq;
  461.     }

  462.     /**
  463.      * <p>Returns the <i>observed significance level</i>, or <a href=
  464.      * "http://www.cas.lancs.ac.uk/glossary_v1.1/hyptest.html#pvalue">
  465.      * p-value</a>, associated with a Chi-Square two sample test comparing
  466.      * bin frequency counts in <code>observed1</code> and
  467.      * <code>observed2</code>.
  468.      * </p>
  469.      * <p>The number returned is the smallest significance level at which one
  470.      * can reject the null hypothesis that the observed counts conform to the
  471.      * same distribution.
  472.      * </p>
  473.      * <p>See {@link #chiSquareDataSetsComparison(long[], long[])} for details
  474.      * on the formula used to compute the test statistic. The degrees of
  475.      * of freedom used to perform the test is one less than the common length
  476.      * of the input observed count arrays.
  477.      * </p>
  478.      * <strong>Preconditions</strong>: <ul>
  479.      * <li>Observed counts must be non-negative.
  480.      * </li>
  481.      * <li>Observed counts for a specific bin must not both be zero.
  482.      * </li>
  483.      * <li>Observed counts for a specific sample must not all be 0.
  484.      * </li>
  485.      * <li>The arrays <code>observed1</code> and <code>observed2</code> must
  486.      * have the same length and
  487.      * their common length must be at least 2.
  488.      * </li></ul><p>
  489.      * If any of the preconditions are not met, an
  490.      * <code>IllegalArgumentException</code> is thrown.</p>
  491.      *
  492.      * @param observed1 array of observed frequency counts of the first data set
  493.      * @param observed2 array of observed frequency counts of the second data set
  494.      * @return p-value
  495.      * @throws DimensionMismatchException the length of the arrays does not match
  496.      * @throws NotPositiveException if any entries in <code>observed1</code> or
  497.      * <code>observed2</code> are negative
  498.      * @throws ZeroException if either all counts of <code>observed1</code> or
  499.      * <code>observed2</code> are zero, or if the count at the same index is zero
  500.      * for both arrays
  501.      * @throws MaxCountExceededException if an error occurs computing the p-value
  502.      * @since 1.2
  503.      */
  504.     public double chiSquareTestDataSetsComparison(long[] observed1, long[] observed2)
  505.         throws DimensionMismatchException, NotPositiveException, ZeroException,
  506.         MaxCountExceededException {

  507.         // pass a null rng to avoid unneeded overhead as we will not sample from this distribution
  508.         final ChiSquaredDistribution distribution =
  509.                 ChiSquaredDistribution.of((double) observed1.length - 1);
  510.         return distribution.survivalProbability(
  511.                 chiSquareDataSetsComparison(observed1, observed2));
  512.     }

  513.     /**
  514.      * <p>Performs a Chi-Square two sample test comparing two binned data
  515.      * sets. The test evaluates the null hypothesis that the two lists of
  516.      * observed counts conform to the same frequency distribution, with
  517.      * significance level <code>alpha</code>.  Returns true iff the null
  518.      * hypothesis can be rejected with 100 * (1 - alpha) percent confidence.
  519.      * </p>
  520.      * <p>See {@link #chiSquareDataSetsComparison(long[], long[])} for
  521.      * details on the formula used to compute the Chisquare statistic used
  522.      * in the test. The degrees of of freedom used to perform the test is
  523.      * one less than the common length of the input observed count arrays.
  524.      * </p>
  525.      * <strong>Preconditions</strong>: <ul>
  526.      * <li>Observed counts must be non-negative.
  527.      * </li>
  528.      * <li>Observed counts for a specific bin must not both be zero.
  529.      * </li>
  530.      * <li>Observed counts for a specific sample must not all be 0.
  531.      * </li>
  532.      * <li>The arrays <code>observed1</code> and <code>observed2</code> must
  533.      * have the same length and their common length must be at least 2.
  534.      * </li>
  535.      * <li> <code> 0 &lt; alpha &lt; 0.5 </code>
  536.      * </li></ul><p>
  537.      * If any of the preconditions are not met, an
  538.      * <code>IllegalArgumentException</code> is thrown.</p>
  539.      *
  540.      * @param observed1 array of observed frequency counts of the first data set
  541.      * @param observed2 array of observed frequency counts of the second data set
  542.      * @param alpha significance level of the test
  543.      * @return true iff null hypothesis can be rejected with confidence
  544.      * 1 - alpha
  545.      * @throws DimensionMismatchException the length of the arrays does not match
  546.      * @throws NotPositiveException if any entries in <code>observed1</code> or
  547.      * <code>observed2</code> are negative
  548.      * @throws ZeroException if either all counts of <code>observed1</code> or
  549.      * <code>observed2</code> are zero, or if the count at the same index is zero
  550.      * for both arrays
  551.      * @throws OutOfRangeException if <code>alpha</code> is not in the range (0, 0.5]
  552.      * @throws MaxCountExceededException if an error occurs performing the test
  553.      * @since 1.2
  554.      */
  555.     public boolean chiSquareTestDataSetsComparison(final long[] observed1,
  556.                                                    final long[] observed2,
  557.                                                    final double alpha)
  558.         throws DimensionMismatchException, NotPositiveException,
  559.         ZeroException, OutOfRangeException, MaxCountExceededException {

  560.         if (alpha <= 0 ||
  561.             alpha > 0.5) {
  562.             throw new OutOfRangeException(LocalizedFormats.OUT_OF_BOUND_SIGNIFICANCE_LEVEL,
  563.                                           alpha, 0, 0.5);
  564.         }
  565.         return chiSquareTestDataSetsComparison(observed1, observed2) < alpha;
  566.     }

  567.     /**
  568.      * Checks to make sure that the input long[][] array is rectangular,
  569.      * has at least 2 rows and 2 columns, and has all non-negative entries.
  570.      *
  571.      * @param in input 2-way table to check
  572.      * @throws NullArgumentException if the array is null
  573.      * @throws DimensionMismatchException if the array is not valid
  574.      * @throws NotPositiveException if the array contains any negative entries
  575.      */
  576.     private void checkArray(final long[][] in)
  577.         throws NullArgumentException, DimensionMismatchException,
  578.         NotPositiveException {

  579.         if (in.length < 2) {
  580.             throw new DimensionMismatchException(in.length, 2);
  581.         }

  582.         if (in[0].length < 2) {
  583.             throw new DimensionMismatchException(in[0].length, 2);
  584.         }

  585.         MathArrays.checkRectangular(in);
  586.         MathArrays.checkNonNegative(in);
  587.     }

  588.     /**
  589.      * Check the array value is non-zero.
  590.      *
  591.      * @param value Value
  592.      * @param name Name of the array
  593.      * @param index Index in the array
  594.      * @throws ZeroException if the value is zero
  595.      */
  596.     private static void checkNonZero(double value, String name, int index) {
  597.         if (value == 0) {
  598.             throw new ZeroException(LocalizedFormats.OBSERVED_COUNTS_ALL_ZERO,
  599.                 name + " " + index);
  600.         }
  601.     }
  602. }