~ubuntu-branches/ubuntu/oneiric/commons-math/oneiric

« back to all changes in this revision

Viewing changes to src/test/java/org/apache/commons/math/random/RandomDataTest.java

  • Committer: Bazaar Package Importer
  • Author(s): Damien Raude-Morvan, Torsten Werner, Damien Raude-Morvan
  • Date: 2011-03-07 21:14:46 UTC
  • mfrom: (1.1.3 upstream)
  • Revision ID: james.westby@ubuntu.com-20110307211446-4zea7og4eeyzhpai
Tags: 2.2-1
[ Torsten Werner ]
* Change maintainers into Maintainers.

[ Damien Raude-Morvan ]
* New upstream release (Closes: #617209).
* d/control: Bump Standards-Version to 3.9.1 (no changes needed).
* d/copyright: Refresh years, upgrade to DEP5 r166 and relicence my work
  under Apache-2.0.
* d/ant.properties: Set junit.jar to /usr/share/java/junit4.jar
  to ensure unit tests are launched.
* d/docs: Install upstream RELEASE-NOTES.

Show diffs side-by-side

added added

removed removed

Lines of Context:
24
24
import junit.framework.AssertionFailedError;
25
25
 
26
26
import org.apache.commons.math.RetryTestCase;
 
27
import org.apache.commons.math.TestUtils;
 
28
import org.apache.commons.math.distribution.BetaDistributionImpl;
 
29
import org.apache.commons.math.distribution.BinomialDistributionImpl;
 
30
import org.apache.commons.math.distribution.BinomialDistributionTest;
 
31
import org.apache.commons.math.distribution.CauchyDistributionImpl;
 
32
import org.apache.commons.math.distribution.ChiSquaredDistributionImpl;
 
33
import org.apache.commons.math.distribution.FDistributionImpl;
 
34
import org.apache.commons.math.distribution.GammaDistributionImpl;
 
35
import org.apache.commons.math.distribution.HypergeometricDistributionImpl;
 
36
import org.apache.commons.math.distribution.HypergeometricDistributionTest;
 
37
import org.apache.commons.math.distribution.PascalDistributionImpl;
 
38
import org.apache.commons.math.distribution.PascalDistributionTest;
27
39
import org.apache.commons.math.distribution.PoissonDistribution;
28
40
import org.apache.commons.math.distribution.PoissonDistributionImpl;
 
41
import org.apache.commons.math.distribution.TDistributionImpl;
 
42
import org.apache.commons.math.distribution.WeibullDistributionImpl;
 
43
import org.apache.commons.math.distribution.ZipfDistributionImpl;
 
44
import org.apache.commons.math.distribution.ZipfDistributionTest;
29
45
import org.apache.commons.math.stat.Frequency;
30
46
import org.apache.commons.math.stat.descriptive.SummaryStatistics;
31
47
import org.apache.commons.math.stat.inference.ChiSquareTest;
32
48
import org.apache.commons.math.stat.inference.ChiSquareTestImpl;
 
49
import org.apache.commons.math.util.FastMath;
33
50
 
34
51
/**
35
52
 * Test cases for the RandomData class.
36
53
 *
37
 
 * @version $Revision: 924362 $ $Date: 2009-04-05 11:55:59 -0500 (Sun, 05 Apr
 
54
 * @version $Revision: 1042376 $ $Date: 2009-04-05 11:55:59 -0500 (Sun, 05 Apr
38
55
 *          2009) $
39
56
 */
40
57
 
45
62
        randomData = new RandomDataImpl();
46
63
    }
47
64
 
48
 
    protected long smallSampleSize = 1000;
49
 
    protected double[] expected = { 250, 250, 250, 250 };
50
 
    protected int largeSampleSize = 10000;
51
 
    private String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
 
65
    protected final long smallSampleSize = 1000;
 
66
    protected final double[] expected = { 250, 250, 250, 250 };
 
67
    protected final int largeSampleSize = 10000;
 
68
    private final String[] hex = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9",
52
69
            "a", "b", "c", "d", "e", "f" };
53
70
    protected RandomDataImpl randomData = null;
54
 
    protected ChiSquareTestImpl testStatistic = new ChiSquareTestImpl();
 
71
    protected final ChiSquareTestImpl testStatistic = new ChiSquareTestImpl();
55
72
 
56
73
    public void testNextIntExtremeValues() {
57
74
        int x = randomData.nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE);
179
196
 
180
197
    /**
181
198
     * Make sure that empirical distribution of random Poisson(4)'s has P(X <=
182
 
     * 5) close to actual cumulative Poisson probablity and that nextPoisson
 
199
     * 5) close to actual cumulative Poisson probability and that nextPoisson
183
200
     * fails when mean is non-positive TODO: replace with statistical test,
184
201
     * adding test stat to TestStatistic
185
202
     */
192
209
        }
193
210
        Frequency f = new Frequency();
194
211
        for (int i = 0; i < largeSampleSize; i++) {
195
 
            try {
196
 
                f.addValue(randomData.nextPoisson(4.0d));
197
 
            } catch (Exception ex) {
198
 
                fail(ex.getMessage());
199
 
            }
 
212
            f.addValue(randomData.nextPoisson(4.0d));
200
213
        }
201
214
        long cumFreq = f.getCount(0) + f.getCount(1) + f.getCount(2)
202
215
                + f.getCount(3) + f.getCount(4) + f.getCount(5);
220
233
    }
221
234
 
222
235
    public void testNextPoissonConsistency() throws Exception {
 
236
        
 
237
        // Reseed randomGenerator to get fixed sequence
 
238
        randomData.reSeed(1000);  
 
239
        
223
240
        // Small integral means
224
241
        for (int i = 1; i < 100; i++) {
225
242
            checkNextPoissonConsistency(i);
226
243
        }
227
244
        // non-integer means
228
 
        RandomData randomData = new RandomDataImpl();
229
245
        for (int i = 1; i < 10; i++) {
230
246
            checkNextPoissonConsistency(randomData.nextUniform(1, 1000));
231
247
        }
243
259
     * to the corresponding expected distribution computed using PoissonDistributionImpl.
244
260
     * Uses ChiSquare test of goodness of fit to evaluate the null hypothesis that the
245
261
     * distributions are the same. If the null hypothesis can be rejected with confidence
246
 
     * 1 - alpha, the check fails.  This check will fail randomly with probability alpha.
 
262
     * 1 - alpha, the check fails.
247
263
     */
248
264
    public void checkNextPoissonConsistency(double mean) throws Exception {
249
265
        // Generate sample values
250
 
        int sampleSize = 1000;        // Number of deviates to generate
251
 
        int minExpectedCount = 7;     // Minimum size of expected bin count
 
266
        final int sampleSize = 1000;        // Number of deviates to generate
 
267
        final int minExpectedCount = 7;     // Minimum size of expected bin count
252
268
        long maxObservedValue = 0;
253
 
        double alpha = 0.001;         // Probability of false failure
 
269
        final double alpha = 0.001;         // Probability of false failure
254
270
        Frequency frequency = new Frequency();
255
271
        for (int i = 0; i < sampleSize; i++) {
256
272
            long value = randomData.nextPoisson(mean);
284
300
        while (!widthSufficient) {
285
301
            lowerBinMass = poissonDistribution.cumulativeProbability(lower, lower + binWidth - 1);
286
302
            upperBinMass = poissonDistribution.cumulativeProbability(upper - binWidth + 1, upper);
287
 
            widthSufficient = Math.min(lowerBinMass, upperBinMass) * sampleSize >= minExpectedCount;
 
303
            widthSufficient = FastMath.min(lowerBinMass, upperBinMass) * sampleSize >= minExpectedCount;
288
304
            binWidth++;
289
305
        }
290
306
 
339
355
            // Fail if we can reject null hypothesis that distributions are the same
340
356
            assertFalse(chiSquareTest.chiSquareTest(expected, observed, alpha));
341
357
        } catch (AssertionFailedError ex) {
342
 
            StringBuffer msgBuffer = new StringBuffer();
 
358
            StringBuilder msgBuffer = new StringBuilder();
343
359
            DecimalFormat df = new DecimalFormat("#.##");
344
360
            msgBuffer.append("Chisquare test failed for mean = ");
345
361
            msgBuffer.append(mean);
368
384
        }
369
385
    }
370
386
 
371
 
    /** test dispersion and failute modes for nextHex() */
 
387
    /** test dispersion and failure modes for nextHex() */
372
388
    public void testNextHex() {
373
389
        try {
374
390
            randomData.nextHexString(-1);
423
439
                testStatistic.chiSquare(expected, observed) < 37.70);
424
440
    }
425
441
 
426
 
    /** test dispersion and failute modes for nextHex() */
 
442
    /** test dispersion and failure modes for nextHex() */
427
443
    public void testNextSecureHex() {
428
444
        try {
429
445
            randomData.nextSecureHexString(-1);
544
560
         * t-test at .001-level TODO: replace with externalized t-test, with
545
561
         * test statistic defined in TestStatistic
546
562
         */
547
 
        assertTrue(Math.abs(xbar) / (s / Math.sqrt(n)) < 3.29);
 
563
        assertTrue(FastMath.abs(xbar) / (s / FastMath.sqrt(n)) < 3.29);
548
564
    }
549
565
 
550
566
    /** test failure modes and distribution of nextExponential() */
774
790
        fail("permutation not found");
775
791
        return -1;
776
792
    }
 
793
    
 
794
    public void testNextInversionDeviate() throws Exception {
 
795
        // Set the seed for the default random generator
 
796
        randomData.reSeed(100);
 
797
        double[] quantiles = new double[10];
 
798
        for (int i = 0; i < 10; i++) {
 
799
            quantiles[i] = randomData.nextUniform(0, 1);
 
800
        }
 
801
        // Reseed again so the inversion generator gets the same sequence
 
802
        randomData.reSeed(100);
 
803
        BetaDistributionImpl betaDistribution = new BetaDistributionImpl(2, 4);
 
804
        /*
 
805
         *  Generate a sequence of deviates using inversion - the distribution function
 
806
         *  evaluated at the random value from the distribution should match the uniform
 
807
         *  random value used to generate it, which is stored in the quantiles[] array.
 
808
         */
 
809
        for (int i = 0; i < 10; i++) {
 
810
            double value = randomData.nextInversionDeviate(betaDistribution);
 
811
            assertEquals(betaDistribution.cumulativeProbability(value), quantiles[i], 10E-9);
 
812
        } 
 
813
    }
 
814
    
 
815
    public void testNextBeta() throws Exception {
 
816
        double[] quartiles = TestUtils.getDistributionQuartiles(new BetaDistributionImpl(2,5));
 
817
        long[] counts = new long[4];
 
818
        randomData.reSeed(1000);
 
819
        for (int i = 0; i < 1000; i++) {
 
820
            double value = randomData.nextBeta(2, 5);
 
821
            TestUtils.updateCounts(value, counts, quartiles);
 
822
        }
 
823
        TestUtils.assertChiSquareAccept(expected, counts, 0.001);
 
824
    }
 
825
    
 
826
    public void testNextCauchy() throws Exception {
 
827
        double[] quartiles = TestUtils.getDistributionQuartiles(new CauchyDistributionImpl(1.2, 2.1));
 
828
        long[] counts = new long[4];
 
829
        randomData.reSeed(1000);
 
830
        for (int i = 0; i < 1000; i++) {
 
831
            double value = randomData.nextCauchy(1.2, 2.1);
 
832
            TestUtils.updateCounts(value, counts, quartiles);
 
833
        }
 
834
        TestUtils.assertChiSquareAccept(expected, counts, 0.001);
 
835
    }
 
836
    
 
837
    public void testNextChiSquare() throws Exception {
 
838
        double[] quartiles = TestUtils.getDistributionQuartiles(new ChiSquaredDistributionImpl(12));
 
839
        long[] counts = new long[4];
 
840
        randomData.reSeed(1000);
 
841
        for (int i = 0; i < 1000; i++) {
 
842
            double value = randomData.nextChiSquare(12);
 
843
            TestUtils.updateCounts(value, counts, quartiles);
 
844
        }
 
845
        TestUtils.assertChiSquareAccept(expected, counts, 0.001);
 
846
    }
 
847
    
 
848
    public void testNextF() throws Exception {
 
849
        double[] quartiles = TestUtils.getDistributionQuartiles(new FDistributionImpl(12, 5));
 
850
        long[] counts = new long[4];
 
851
        randomData.reSeed(1000);
 
852
        for (int i = 0; i < 1000; i++) {
 
853
            double value = randomData.nextF(12, 5);
 
854
            TestUtils.updateCounts(value, counts, quartiles);
 
855
        }
 
856
        TestUtils.assertChiSquareAccept(expected, counts, 0.001);
 
857
    }
 
858
    
 
859
    public void testNextGamma() throws Exception {
 
860
        double[] quartiles = TestUtils.getDistributionQuartiles(new GammaDistributionImpl(4, 2));
 
861
        long[] counts = new long[4];
 
862
        randomData.reSeed(1000);
 
863
        for (int i = 0; i < 1000; i++) {
 
864
            double value = randomData.nextGamma(4, 2);
 
865
            TestUtils.updateCounts(value, counts, quartiles);
 
866
        }
 
867
        TestUtils.assertChiSquareAccept(expected, counts, 0.001);
 
868
    }
 
869
    
 
870
    public void testNextT() throws Exception {
 
871
        double[] quartiles = TestUtils.getDistributionQuartiles(new TDistributionImpl(10));
 
872
        long[] counts = new long[4];
 
873
        randomData.reSeed(1000);
 
874
        for (int i = 0; i < 1000; i++) {
 
875
            double value = randomData.nextT(10);
 
876
            TestUtils.updateCounts(value, counts, quartiles);
 
877
        }
 
878
        TestUtils.assertChiSquareAccept(expected, counts, 0.001);
 
879
    }
 
880
    
 
881
    public void testNextWeibull() throws Exception {
 
882
        double[] quartiles = TestUtils.getDistributionQuartiles(new WeibullDistributionImpl(1.2, 2.1));
 
883
        long[] counts = new long[4];
 
884
        randomData.reSeed(1000);
 
885
        for (int i = 0; i < 1000; i++) {
 
886
            double value = randomData.nextWeibull(1.2, 2.1);
 
887
            TestUtils.updateCounts(value, counts, quartiles);
 
888
        }
 
889
        TestUtils.assertChiSquareAccept(expected, counts, 0.001);
 
890
    }
 
891
    
 
892
    public void testNextBinomial() throws Exception {
 
893
        BinomialDistributionTest testInstance = new BinomialDistributionTest("");
 
894
        int[] densityPoints = testInstance.makeDensityTestPoints();
 
895
        double[] densityValues = testInstance.makeDensityTestValues();
 
896
        int sampleSize = 1000;
 
897
        int length = TestUtils.eliminateZeroMassPoints(densityPoints, densityValues);
 
898
        BinomialDistributionImpl distribution = (BinomialDistributionImpl) testInstance.makeDistribution();
 
899
        double[] expectedCounts = new double[length];
 
900
        long[] observedCounts = new long[length];
 
901
        for (int i = 0; i < length; i++) {
 
902
            expectedCounts[i] = sampleSize * densityValues[i];
 
903
        }
 
904
        randomData.reSeed(1000);
 
905
        for (int i = 0; i < sampleSize; i++) {
 
906
          int value = randomData.nextBinomial(distribution.getNumberOfTrials(),
 
907
                  distribution.getProbabilityOfSuccess());
 
908
          for (int j = 0; j < length; j++) {
 
909
              if (value == densityPoints[j]) {
 
910
                  observedCounts[j]++;
 
911
              }
 
912
          }
 
913
        }
 
914
        TestUtils.assertChiSquareAccept(densityPoints, expectedCounts, observedCounts, .001);
 
915
    }
 
916
    
 
917
    public void testNextHypergeometric() throws Exception {
 
918
        HypergeometricDistributionTest testInstance = new HypergeometricDistributionTest("");
 
919
        int[] densityPoints = testInstance.makeDensityTestPoints();
 
920
        double[] densityValues = testInstance.makeDensityTestValues();
 
921
        int sampleSize = 1000;
 
922
        int length = TestUtils.eliminateZeroMassPoints(densityPoints, densityValues);
 
923
        HypergeometricDistributionImpl distribution = (HypergeometricDistributionImpl) testInstance.makeDistribution();
 
924
        double[] expectedCounts = new double[length];
 
925
        long[] observedCounts = new long[length];
 
926
        for (int i = 0; i < length; i++) {
 
927
            expectedCounts[i] = sampleSize * densityValues[i];
 
928
        }
 
929
        randomData.reSeed(1000);
 
930
        for (int i = 0; i < sampleSize; i++) {
 
931
          int value = randomData.nextHypergeometric(distribution.getPopulationSize(),
 
932
                  distribution.getNumberOfSuccesses(), distribution.getSampleSize());
 
933
          for (int j = 0; j < length; j++) {
 
934
              if (value == densityPoints[j]) {
 
935
                  observedCounts[j]++;
 
936
              }
 
937
          }
 
938
        }
 
939
        TestUtils.assertChiSquareAccept(densityPoints, expectedCounts, observedCounts, .001);
 
940
    }
 
941
    
 
942
    public void testNextPascal() throws Exception {
 
943
        PascalDistributionTest testInstance = new PascalDistributionTest("");
 
944
        int[] densityPoints = testInstance.makeDensityTestPoints();
 
945
        double[] densityValues = testInstance.makeDensityTestValues();
 
946
        int sampleSize = 1000;
 
947
        int length = TestUtils.eliminateZeroMassPoints(densityPoints, densityValues);
 
948
        PascalDistributionImpl distribution = (PascalDistributionImpl) testInstance.makeDistribution();
 
949
        double[] expectedCounts = new double[length];
 
950
        long[] observedCounts = new long[length];
 
951
        for (int i = 0; i < length; i++) {
 
952
            expectedCounts[i] = sampleSize * densityValues[i];
 
953
        }
 
954
        randomData.reSeed(1000);
 
955
        for (int i = 0; i < sampleSize; i++) {
 
956
          int value = randomData.nextPascal(distribution.getNumberOfSuccesses(), distribution.getProbabilityOfSuccess());
 
957
          for (int j = 0; j < length; j++) {
 
958
              if (value == densityPoints[j]) {
 
959
                  observedCounts[j]++;
 
960
              }
 
961
          }
 
962
        }
 
963
        TestUtils.assertChiSquareAccept(densityPoints, expectedCounts, observedCounts, .001);
 
964
    }
 
965
    
 
966
    public void testNextZipf() throws Exception {
 
967
        ZipfDistributionTest testInstance = new ZipfDistributionTest("");
 
968
        int[] densityPoints = testInstance.makeDensityTestPoints();
 
969
        double[] densityValues = testInstance.makeDensityTestValues();
 
970
        int sampleSize = 1000;
 
971
        int length = TestUtils.eliminateZeroMassPoints(densityPoints, densityValues);
 
972
        ZipfDistributionImpl distribution = (ZipfDistributionImpl) testInstance.makeDistribution();
 
973
        double[] expectedCounts = new double[length];
 
974
        long[] observedCounts = new long[length];
 
975
        for (int i = 0; i < length; i++) {
 
976
            expectedCounts[i] = sampleSize * densityValues[i];
 
977
        }
 
978
        randomData.reSeed(1000);
 
979
        for (int i = 0; i < sampleSize; i++) {
 
980
          int value = randomData.nextZipf(distribution.getNumberOfElements(), distribution.getExponent());
 
981
          for (int j = 0; j < length; j++) {
 
982
              if (value == densityPoints[j]) {
 
983
                  observedCounts[j]++;
 
984
              }
 
985
          }
 
986
        }
 
987
        TestUtils.assertChiSquareAccept(densityPoints, expectedCounts, observedCounts, .001);
 
988
    }
 
989
    
777
990
}