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    *      https://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  
18  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  
23  package org.hipparchus;
24  
25  import org.hipparchus.complex.Complex;
26  import org.hipparchus.complex.ComplexFormat;
27  import org.hipparchus.complex.FieldComplex;
28  import org.hipparchus.distribution.RealDistribution;
29  import org.hipparchus.distribution.continuous.ChiSquaredDistribution;
30  import org.hipparchus.linear.BlockRealMatrix;
31  import org.hipparchus.linear.FieldMatrix;
32  import org.hipparchus.linear.RealMatrix;
33  import org.hipparchus.linear.RealVector;
34  import org.hipparchus.util.Binary64;
35  import org.hipparchus.util.FastMath;
36  import org.hipparchus.util.Precision;
37  
38  import java.io.ByteArrayInputStream;
39  import java.io.ByteArrayOutputStream;
40  import java.io.IOException;
41  import java.io.ObjectInputStream;
42  import java.io.ObjectOutputStream;
43  import java.text.DecimalFormat;
44  import java.util.ArrayList;
45  import java.util.Arrays;
46  import java.util.HashMap;
47  import java.util.List;
48  import java.util.Map;
49  
50  import static org.junit.jupiter.api.Assertions.assertEquals;
51  import static org.junit.jupiter.api.Assertions.assertNotNull;
52  import static org.junit.jupiter.api.Assertions.assertTrue;
53  import static org.junit.jupiter.api.Assertions.fail;
54  
55  /**
56   */
57  public class UnitTestUtils {
58      /**
59       * Collection of static methods used in math unit tests.
60       */
61      private UnitTestUtils() {
62          super();
63      }
64  
65      /**
66       * Verifies that expected and actual are within delta, or are both NaN or
67       * infinities of the same sign.
68       */
69      public static void customAssertEquals(double expected, double actual, double delta) {
70          assertEquals(expected, actual, delta);
71      }
72  
73      /**
74       * Verifies that expected and actual are within delta, or are both NaN or
75       * infinities of the same sign.
76       */
77      public static void customAssertEquals(String msg, double expected, double actual, double delta) {
78          // check for NaN
79          if(Double.isNaN(expected)){
80              assertTrue(Double.isNaN(actual),
81                  "" + actual + " is not NaN.");
82          } else {
83              assertEquals(expected, actual, delta, msg);
84          }
85      }
86  
87      /**
88       * Verifies that the two arguments are exactly the same, either
89       * both NaN or infinities of same sign, or identical floating point values.
90       */
91      public static void customAssertSame(double expected, double actual) {
92       assertEquals(expected, actual, 0);
93      }
94  
95      /**
96       * Verifies that real and imaginary parts of the two complex arguments
97       * are exactly the same.  Also ensures that NaN / infinite components match.
98       */
99      public static void customAssertSame(Complex expected, Complex actual) {
100         customAssertSame(expected.getRealPart(), actual.getRealPart());
101         customAssertSame(expected.getImaginaryPart(), actual.getImaginaryPart());
102     }
103 
104     /**
105      * Verifies that real and imaginary parts of the two complex arguments
106      * differ by at most delta.  Also ensures that NaN / infinite components match.
107      */
108     public static void customAssertEquals(Complex expected, Complex actual, double delta) {
109         assertEquals(expected.getRealPart(), actual.getRealPart(), delta);
110         assertEquals(expected.getImaginaryPart(), actual.getImaginaryPart(), delta);
111     }
112 
113     /**
114      * Verifies that real and imaginary parts of the two complex arguments
115      * differ by at most delta.  Also ensures that NaN / infinite components match.
116      */
117     public static void customAssertEquals(FieldComplex<Binary64> expected, FieldComplex<Binary64> actual, double delta) {
118         assertEquals(expected.getRealPart().getReal(), actual.getRealPart().getReal(), delta);
119         assertEquals(expected.getImaginaryPart().getReal(), actual.getImaginaryPart().getReal(), delta);
120     }
121 
122     /**
123      * Verifies that real and imaginary parts of the two complex arguments
124      * are exactly the same.  Also ensures that NaN / infinite components match.
125      */
126     public static void customAssertSame(FieldComplex<Binary64> expected, FieldComplex<Binary64> actual) {
127         customAssertSame(expected.getRealPart().getReal(), actual.getRealPart().getReal());
128         customAssertSame(expected.getImaginaryPart().getReal(), actual.getImaginaryPart().getReal());
129     }
130 
131     /**
132      * Verifies that two double arrays have equal entries, up to tolerance
133      */
134     public static void customAssertEquals(double[] expected, double[] observed, double tolerance) {
135         customAssertEquals("Array comparison failure", expected, observed, tolerance);
136     }
137 
138     /**
139      * Serializes an object to a bytes array and then recovers the object from the bytes array.
140      * Returns the deserialized object.
141      *
142      * @param o  object to serialize and recover
143      * @return  the recovered, deserialized object
144      */
145     public static Object serializeAndRecover(Object o) {
146         try {
147             // serialize the Object
148             ByteArrayOutputStream bos = new ByteArrayOutputStream();
149             ObjectOutputStream so = new ObjectOutputStream(bos);
150             so.writeObject(o);
151 
152             // deserialize the Object
153             ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
154             ObjectInputStream si = new ObjectInputStream(bis);
155             return si.readObject();
156         } catch (IOException | ClassNotFoundException ioe) {
157             return null;
158         }
159     }
160 
161     /**
162      * Verifies that serialization preserves equals and hashCode.
163      * Serializes the object, then recovers it and checks equals and hash code.
164      *
165      * @param object  the object to serialize and recover
166      */
167     public static void checkSerializedEquality(Object object) {
168         Object object2 = serializeAndRecover(object);
169         assertEquals(object, object2, "Equals check");
170         assertEquals(object.hashCode(), object2.hashCode(), "HashCode check");
171     }
172 
173     /**
174      * Verifies that the relative error in actual vs. expected is less than or
175      * equal to relativeError.  If expected is infinite or NaN, actual must be
176      * the same (NaN or infinity of the same sign).
177      *
178      * @param expected expected value
179      * @param actual  observed value
180      * @param relativeError  maximum allowable relative error
181      */
182     public static void customAssertRelativelyEquals(double expected, double actual,
183                                                     double relativeError) {
184         customAssertRelativelyEquals(null, expected, actual, relativeError);
185     }
186 
187     /**
188      * Verifies that the relative error in actual vs. expected is less than or
189      * equal to relativeError.  If expected is infinite or NaN, actual must be
190      * the same (NaN or infinity of the same sign).
191      *
192      * @param msg  message to return with failure
193      * @param expected expected value
194      * @param actual  observed value
195      * @param relativeError  maximum allowable relative error
196      */
197     public static void customAssertRelativelyEquals(String msg, double expected,
198                                                     double actual, double relativeError) {
199         if (Double.isNaN(expected)) {
200             assertTrue(Double.isNaN(actual), msg);
201         } else if (Double.isNaN(actual)) {
202             assertTrue(Double.isNaN(expected), msg);
203         } else if (Double.isInfinite(actual) || Double.isInfinite(expected)) {
204             assertEquals(expected, actual, relativeError);
205         } else if (expected == 0.0) {
206             assertEquals(actual, expected, relativeError, msg);
207         } else {
208             double absError = FastMath.abs(expected) * relativeError;
209             assertEquals(expected, actual, absError, msg);
210         }
211     }
212 
213     /**
214      * Fails iff values does not contain a number within epsilon of z.
215      *
216      * @param msg  message to return with failure
217      * @param values complex array to search
218      * @param z  value sought
219      * @param epsilon  tolerance
220      */
221     public static void customAssertContains(String msg, Complex[] values,
222                                             Complex z, double epsilon) {
223         for (Complex value : values) {
224             if (Precision.equals(value.getReal(), z.getReal(), epsilon) &&
225                 Precision.equals(value.getImaginary(), z.getImaginary(), epsilon)) {
226                 return;
227             }
228         }
229         fail(msg + " Unable to find " + (new ComplexFormat()).format(z));
230     }
231 
232     /**
233      * Fails iff values does not contain a number within epsilon of z.
234      *
235      * @param values complex array to search
236      * @param z  value sought
237      * @param epsilon  tolerance
238      */
239     public static void customAssertContains(Complex[] values,
240                                             Complex z, double epsilon) {
241         customAssertContains(null, values, z, epsilon);
242     }
243 
244     /**
245      * Fails iff values does not contain a number within epsilon of x.
246      *
247      * @param msg  message to return with failure
248      * @param values double array to search
249      * @param x value sought
250      * @param epsilon  tolerance
251      */
252     public static void customAssertContains(String msg, double[] values,
253                                             double x, double epsilon) {
254         for (double value : values) {
255             if (Precision.equals(value, x, epsilon)) {
256                 return;
257             }
258         }
259         fail(msg + " Unable to find " + x);
260     }
261 
262     /**
263      * Fails iff values does not contain a number within epsilon of x.
264      *
265      * @param values double array to search
266      * @param x value sought
267      * @param epsilon  tolerance
268      */
269     public static void customAssertContains(double[] values, double x,
270                                             double epsilon) {
271        customAssertContains(null, values, x, epsilon);
272     }
273 
274     /**
275      * Asserts that all entries of the specified vectors are equal to within a
276      * positive {@code delta}.
277      *
278      * @param message the identifying message for the assertion error (can be
279      * {@code null})
280      * @param expected expected value
281      * @param actual actual value
282      * @param delta the maximum difference between the entries of the expected
283      * and actual vectors for which both entries are still considered equal
284      */
285     public static void customAssertEquals(final String message,
286                                           final double[] expected, final RealVector actual, final double delta) {
287         final String msgAndSep = message.equals("") ? "" : message + ", ";
288         assertEquals(expected.length,
289             actual.getDimension(),
290             msgAndSep + "dimension");
291         for (int i = 0; i < expected.length; i++) {
292             assertEquals(expected[i],
293                 actual.getEntry(i), delta, msgAndSep + "entry #" + i);
294         }
295     }
296 
297     /**
298      * Asserts that all entries of the specified vectors are equal to within a
299      * positive {@code delta}.
300      *
301      * @param message the identifying message for the assertion error (can be
302      * {@code null})
303      * @param expected expected value
304      * @param actual actual value
305      * @param delta the maximum difference between the entries of the expected
306      * and actual vectors for which both entries are still considered equal
307      */
308     public static void customAssertEquals(final String message,
309                                           final RealVector expected, final RealVector actual, final double delta) {
310         final String msgAndSep = message.equals("") ? "" : message + ", ";
311         assertEquals(expected.getDimension(),
312             actual.getDimension(),
313             msgAndSep + "dimension");
314         final int dim = expected.getDimension();
315         for (int i = 0; i < dim; i++) {
316             assertEquals(expected.getEntry(i), actual.getEntry(i), delta, msgAndSep + "entry #" + i);
317         }
318     }
319 
320     /** verifies that two matrices are close (1-norm) */
321     public static void customAssertEquals(String msg, RealMatrix expected, RealMatrix observed, double tolerance) {
322 
323         assertNotNull(observed,msg + "\nObserved should not be null");
324 
325         if (expected.getColumnDimension() != observed.getColumnDimension() ||
326                 expected.getRowDimension() != observed.getRowDimension()) {
327             StringBuilder messageBuffer = new StringBuilder(msg);
328             messageBuffer.append("\nObserved has incorrect dimensions.");
329             messageBuffer.append("\nobserved is " + observed.getRowDimension() +
330                     " x " + observed.getColumnDimension());
331             messageBuffer.append("\nexpected " + expected.getRowDimension() +
332                     " x " + expected.getColumnDimension());
333             fail(messageBuffer.toString());
334         }
335 
336         RealMatrix delta = expected.subtract(observed);
337         if (delta.getNorm1() >= tolerance) {
338             StringBuilder messageBuffer = new StringBuilder(msg);
339             messageBuffer.append("\nExpected: " + expected);
340             messageBuffer.append("\nObserved: " + observed);
341             messageBuffer.append("\nexpected - observed: " + delta);
342             fail(messageBuffer.toString());
343         }
344     }
345 
346     /** verifies that two matrices are equal */
347     public static void customAssertEquals(FieldMatrix<? extends FieldElement<?>> expected,
348                                           FieldMatrix<? extends FieldElement<?>> observed) {
349 
350         assertNotNull(observed,"Observed should not be null");
351 
352         if (expected.getColumnDimension() != observed.getColumnDimension() ||
353                 expected.getRowDimension() != observed.getRowDimension()) {
354             StringBuilder messageBuffer = new StringBuilder();
355             messageBuffer.append("Observed has incorrect dimensions.");
356             messageBuffer.append("\nobserved is " + observed.getRowDimension() +
357                     " x " + observed.getColumnDimension());
358             messageBuffer.append("\nexpected " + expected.getRowDimension() +
359                     " x " + expected.getColumnDimension());
360             fail(messageBuffer.toString());
361         }
362 
363         for (int i = 0; i < expected.getRowDimension(); ++i) {
364             for (int j = 0; j < expected.getColumnDimension(); ++j) {
365                 FieldElement<?> eij = expected.getEntry(i, j);
366                 FieldElement<?> oij = observed.getEntry(i, j);
367                 assertEquals(eij, oij);
368             }
369         }
370     }
371 
372     /** verifies that two arrays are close (sup norm) */
373     public static void customAssertEquals(String msg, double[] expected, double[] observed, double tolerance) {
374         StringBuilder out = new StringBuilder(msg);
375         if (expected.length != observed.length) {
376             out.append("\n Arrays not same length. \n");
377             out.append("expected has length ");
378             out.append(expected.length);
379             out.append(" observed length = ");
380             out.append(observed.length);
381             fail(out.toString());
382         }
383         boolean failure = false;
384         for (int i=0; i < expected.length; i++) {
385             if (!Precision.equalsIncludingNaN(expected[i], observed[i], tolerance)) {
386                 failure = true;
387                 out.append("\n Elements at index ");
388                 out.append(i);
389                 out.append(" differ. ");
390                 out.append(" expected = ");
391                 out.append(expected[i]);
392                 out.append(" observed = ");
393                 out.append(observed[i]);
394             }
395         }
396         if (failure) {
397             fail(out.toString());
398         }
399     }
400 
401     /** verifies that two int arrays are equal */
402     public static void customAssertEquals(int[] expected, int[] observed) {
403         StringBuilder out = new StringBuilder();
404         if (expected.length != observed.length) {
405             out.append("\n Arrays not same length. \n");
406             out.append("expected has length ");
407             out.append(expected.length);
408             out.append(" observed length = ");
409             out.append(observed.length);
410             fail(out.toString());
411         }
412         boolean failure = false;
413         for (int i=0; i < expected.length; i++) {
414             if (expected[i] != observed[i]) {
415                 failure = true;
416                 out.append("\n Elements at index ");
417                 out.append(i);
418                 out.append(" differ. ");
419                 out.append(" expected = ");
420                 out.append(expected[i]);
421                 out.append(" observed = ");
422                 out.append(observed[i]);
423             }
424         }
425         if (failure) {
426             fail(out.toString());
427         }
428     }
429 
430     /**
431      * verifies that for i = 0,..., observed.length, observed[i] is within epsilon of one of the values in expected[i]
432      * or observed[i] is NaN and expected[i] contains a NaN.
433      */
434     public static void customAssertContains(double[][] expected, double[] observed, double epsilon) {
435         StringBuilder out = new StringBuilder();
436         if (expected.length != observed.length) {
437             out.append("\n Arrays not same length. \n");
438             out.append("expected has length ");
439             out.append(expected.length);
440             out.append(" observed length = ");
441             out.append(observed.length);
442             fail(out.toString());
443         }
444         boolean failure = false;
445         for (int i = 0; i < expected.length; i++) {
446             boolean found = false;
447             for (int j = 0; j < expected[i].length; j++) {
448                 if (Precision.equalsIncludingNaN(expected[i][j], observed[i], epsilon)) {
449                     found = true;
450                     break;
451                 }
452             }
453             if (!found) {
454                 out.append("\n Observed element at index ");
455                 out.append(i);
456                 out.append(" is not among the expected values. ");
457                 out.append(" expected = " + Arrays.toString(expected[i]));
458                 out.append(" observed = ");
459                 out.append(observed[i]);
460                 failure = true;
461             }
462         }
463         if (failure) {
464             fail(out.toString());
465         }
466     }
467 
468 
469 
470     /** verifies that two int arrays are equal */
471     public static void customAssertEquals(long[] expected, long[] observed) {
472         StringBuilder out = new StringBuilder();
473         if (expected.length != observed.length) {
474             out.append("\n Arrays not same length. \n");
475             out.append("expected has length ");
476             out.append(expected.length);
477             out.append(" observed length = ");
478             out.append(observed.length);
479             fail(out.toString());
480         }
481         boolean failure = false;
482         for (int i=0; i < expected.length; i++) {
483             if (expected[i] != observed[i]) {
484                 failure = true;
485                 out.append("\n Elements at index ");
486                 out.append(i);
487                 out.append(" differ. ");
488                 out.append(" expected = ");
489                 out.append(expected[i]);
490                 out.append(" observed = ");
491                 out.append(observed[i]);
492             }
493         }
494         if (failure) {
495             fail(out.toString());
496         }
497     }
498 
499     /** verifies that two arrays are equal */
500     public static <T extends FieldElement<T>> void customAssertEquals(T[] m, T[] n) {
501         if (m.length != n.length) {
502             fail("vectors not same length");
503         }
504         for (int i = 0; i < m.length; i++) {
505             assertEquals(m[i],n[i]);
506         }
507     }
508 
509     /**
510      * Computes the sum of squared deviations of <values> from <target>
511      * @param values array of deviates
512      * @param target value to compute deviations from
513      *
514      * @return sum of squared deviations
515      */
516     public static double sumSquareDev(double[] values, double target) {
517         double sumsq = 0d;
518         for (int i = 0; i < values.length; i++) {
519             final double dev = values[i] - target;
520             sumsq += (dev * dev);
521         }
522         return sumsq;
523     }
524 
525     /**
526      * Asserts the null hypothesis for a ChiSquare test.  Fails and dumps arguments and test
527      * statistics if the null hypothesis can be rejected with confidence 100 * (1 - alpha)%
528      *
529      * @param valueLabels labels for the values of the discrete distribution under test
530      * @param expected expected counts
531      * @param observed observed counts
532      * @param alpha significance level of the test
533      */
534     public static void customAssertChiSquareAccept(String[] valueLabels, double[] expected, long[] observed, double alpha) {
535 
536         // Fail if we can reject null hypothesis that distributions are the same
537         if (chiSquareTest(expected, observed) <= alpha) {
538             StringBuilder msgBuffer = new StringBuilder();
539             DecimalFormat df = new DecimalFormat("#.##");
540             msgBuffer.append("Chisquare test failed");
541             msgBuffer.append(" p-value = ");
542             msgBuffer.append(chiSquareTest(expected, observed));
543             msgBuffer.append(" chisquare statistic = ");
544             msgBuffer.append(chiSquare(expected, observed));
545             msgBuffer.append(". \n");
546             msgBuffer.append("value\texpected\tobserved\n");
547             for (int i = 0; i < expected.length; i++) {
548                 msgBuffer.append(valueLabels[i]);
549                 msgBuffer.append("\t");
550                 msgBuffer.append(df.format(expected[i]));
551                 msgBuffer.append("\t\t");
552                 msgBuffer.append(observed[i]);
553                 msgBuffer.append("\n");
554             }
555             msgBuffer.append("This test can fail randomly due to sampling error with probability ");
556             msgBuffer.append(alpha);
557             msgBuffer.append(".");
558             fail(msgBuffer.toString());
559         }
560     }
561 
562     /**
563      * Asserts the null hypothesis for a ChiSquare test.  Fails and dumps arguments and test
564      * statistics if the null hypothesis can be rejected with confidence 100 * (1 - alpha)%
565      *
566      * @param values integer values whose observed and expected counts are being compared
567      * @param expected expected counts
568      * @param observed observed counts
569      * @param alpha significance level of the test
570      */
571     public static void customAssertChiSquareAccept(int[] values, double[] expected, long[] observed, double alpha) {
572         String[] labels = new String[values.length];
573         for (int i = 0; i < values.length; i++) {
574             labels[i] = Integer.toString(values[i]);
575         }
576         customAssertChiSquareAccept(labels, expected, observed, alpha);
577     }
578 
579     /**
580      * Asserts the null hypothesis for a ChiSquare test.  Fails and dumps arguments and test
581      * statistics if the null hypothesis can be rejected with confidence 100 * (1 - alpha)%
582      *
583      * @param expected expected counts
584      * @param observed observed counts
585      * @param alpha significance level of the test
586      */
587     public static void customAssertChiSquareAccept(double[] expected, long[] observed, double alpha) {
588         String[] labels = new String[expected.length];
589         for (int i = 0; i < labels.length; i++) {
590             labels[i] = Integer.toString(i + 1);
591         }
592         customAssertChiSquareAccept(labels, expected, observed, alpha);
593     }
594 
595     /**
596      * Asserts the null hypothesis that the sample follows the given distribution, using a G-test
597      *
598      * @param expectedDistribution distribution values are supposed to follow
599      * @param values sample data
600      * @param alpha significance level of the test
601      */
602     public static void customAssertGTest(final RealDistribution expectedDistribution, final double[] values, double alpha) {
603         final int numBins = values.length / 30;
604         final double[] breaks = new double[numBins];
605         for (int b = 0; b < breaks.length; b++) {
606             breaks[b] = expectedDistribution.inverseCumulativeProbability((double) b / numBins);
607         }
608 
609         final long[] observed = new long[numBins];
610         for (final double value : values) {
611             int b = 0;
612             do {
613                 b++;
614             } while (b < numBins && value >= breaks[b]);
615 
616             observed[b - 1]++;
617         }
618 
619         final double[] expected = new double[numBins];
620         Arrays.fill(expected, (double) values.length / numBins);
621 
622         customAssertGTest(expected, observed, alpha);
623     }
624 
625     /**
626      * Asserts the null hypothesis that the observed counts follow the given distribution implied by expected,
627      * using a G-test
628      *
629      * @param expected expected counts
630      * @param observed observed counts
631      * @param alpha significance level of the test
632      */
633     public static void customAssertGTest(final double[] expected, long[] observed, double alpha) {
634         if (gTest(expected, observed) <  alpha) {
635             StringBuilder msgBuffer = new StringBuilder();
636             DecimalFormat df = new DecimalFormat("#.##");
637             msgBuffer.append("G test failed");
638             msgBuffer.append(" p-value = ");
639             msgBuffer.append(gTest(expected, observed));
640             msgBuffer.append(". \n");
641             msgBuffer.append("value\texpected\tobserved\n");
642             for (int i = 0; i < expected.length; i++) {
643                 msgBuffer.append(df.format(expected[i]));
644                 msgBuffer.append("\t\t");
645                 msgBuffer.append(observed[i]);
646                 msgBuffer.append("\n");
647             }
648             msgBuffer.append("This test can fail randomly due to sampling error with probability ");
649             msgBuffer.append(alpha);
650             msgBuffer.append(".");
651             fail(msgBuffer.toString());
652         }
653     }
654 
655     /**
656      * Computes the 25th, 50th and 75th percentiles of the given distribution and returns
657      * these values in an array.
658      */
659     public static double[] getDistributionQuartiles(RealDistribution distribution) {
660         double[] quantiles = new double[3];
661         quantiles[0] = distribution.inverseCumulativeProbability(0.25d);
662         quantiles[1] = distribution.inverseCumulativeProbability(0.5d);
663         quantiles[2] = distribution.inverseCumulativeProbability(0.75d);
664         return quantiles;
665     }
666 
667     /**
668      * Updates observed counts of values in quartiles.
669      * counts[0] ↔ 1st quartile ... counts[3] ↔ top quartile
670      */
671     public static void updateCounts(double value, long[] counts, double[] quartiles) {
672         if (value < quartiles[0]) {
673             counts[0]++;
674         } else if (value > quartiles[2]) {
675             counts[3]++;
676         } else if (value > quartiles[1]) {
677             counts[2]++;
678         } else {
679             counts[1]++;
680         }
681     }
682 
683     /**
684      * Eliminates points with zero mass from densityPoints and densityValues parallel
685      * arrays.  Returns the number of positive mass points and collapses the arrays so
686      * that the first <returned value> elements of the input arrays represent the positive
687      * mass points.
688      */
689     public static int eliminateZeroMassPoints(int[] densityPoints, double[] densityValues) {
690         int positiveMassCount = 0;
691         for (int i = 0; i < densityValues.length; i++) {
692             if (densityValues[i] > 0) {
693                 positiveMassCount++;
694             }
695         }
696         if (positiveMassCount < densityValues.length) {
697             int[] newPoints = new int[positiveMassCount];
698             double[] newValues = new double[positiveMassCount];
699             int j = 0;
700             for (int i = 0; i < densityValues.length; i++) {
701                 if (densityValues[i] > 0) {
702                     newPoints[j] = densityPoints[i];
703                     newValues[j] = densityValues[i];
704                     j++;
705                 }
706             }
707             System.arraycopy(newPoints,0,densityPoints,0,positiveMassCount);
708             System.arraycopy(newValues,0,densityValues,0,positiveMassCount);
709         }
710         return positiveMassCount;
711     }
712 
713     /*************************************************************************************
714      * Stripped-down implementations of some basic statistics borrowed from hipparchus-stat.
715      * NOTE: These implementations are NOT intended for reuse.  They are neither robust,
716      * nor efficient; nor do they handle NaN, infinity or other corner cases in
717      * a predictable way. They DO NOT CHECK PARAMETERS - the assumption is that incorrect
718      * or meaningless results from bad parameters will trigger test failures in unit
719      * tests using these methods.
720      ************************************************************************************/
721 
722     /**
723      * Returns p-value associated with null hypothesis that observed counts follow
724      * expected distribution.  Will normalize inputs if necessary.
725      *
726      * @param expected expected counts
727      * @param observed observed counts
728      * @return p-value of Chi-square test
729      */
730     public static double chiSquareTest(final double[] expected, final long[] observed) {
731             final org.hipparchus.distribution.continuous.ChiSquaredDistribution distribution =
732                 new ChiSquaredDistribution(expected.length - 1.0);
733             return 1.0 - distribution.cumulativeProbability(chiSquare(expected, observed));
734     }
735 
736     /**
737      * Returns chi-square test statistic for expected and observed arrays. Rescales arrays
738      * if necessary.
739      *
740      * @param expected expected counts
741      * @param observed observed counts
742      * @return chi-square statistic
743      */
744     public static double chiSquare(final double[] expected, final long[] observed) {
745             double sumExpected = 0d;
746             double sumObserved = 0d;
747             for (int i = 0; i < observed.length; i++) {
748                 sumExpected += expected[i];
749                 sumObserved += observed[i];
750             }
751             double ratio = 1.0d;
752             boolean rescale = false;
753             if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {
754                 ratio = sumObserved / sumExpected;
755                 rescale = true;
756             }
757             double sumSq = 0.0d;
758             for (int i = 0; i < observed.length; i++) {
759                 if (rescale) {
760                     final double dev = observed[i] - ratio * expected[i];
761                     sumSq += dev * dev / (ratio * expected[i]);
762                 } else {
763                     final double dev = observed[i] - expected[i];
764                     sumSq += dev * dev / expected[i];
765                 }
766             }
767             return sumSq;
768 
769         }
770 
771     /**
772      * Computes G-test statistic for expected, observed counts.
773      * @param expected expected counts
774      * @param observed observed counts
775      * @return G statistic
776      */
777     private static double g(final double[] expected, final long[] observed) {
778         double sumExpected = 0d;
779         double sumObserved = 0d;
780         for (int i = 0; i < observed.length; i++) {
781             sumExpected += expected[i];
782             sumObserved += observed[i];
783         }
784         double ratio = 1d;
785         boolean rescale = false;
786         if (FastMath.abs(sumExpected - sumObserved) > 10E-6) {
787             ratio = sumObserved / sumExpected;
788             rescale = true;
789         }
790         double sum = 0d;
791         for (int i = 0; i < observed.length; i++) {
792             final double dev = rescale ?
793                     FastMath.log(observed[i] / (ratio * expected[i])) :
794                         FastMath.log(observed[i] / expected[i]);
795             sum += (observed[i]) * dev;
796         }
797         return 2d * sum;
798     }
799 
800     /**
801      * Computes p-value for G-test.
802      *
803      * @param expected expected counts
804      * @param observed observed counts
805      * @return p-value
806      */
807     private static double gTest(final double[] expected, final long[] observed) {
808         final ChiSquaredDistribution distribution =
809                 new ChiSquaredDistribution(expected.length - 1.0);
810         return 1.0 - distribution.cumulativeProbability(g(expected, observed));
811     }
812 
813     /**
814      * Computes the mean of the values in the array.
815      *
816      * @param values input values
817      * @return arithmetic mean
818      */
819     public static double mean(final double[] values) {
820         double sum = 0;
821         for (double val : values) {
822             sum += val;
823         }
824         return sum / values.length;
825     }
826 
827     /**
828      * Computes the (bias-adjusted) variance of the values in the input array.
829      *
830      * @param values input values
831      * @return bias-adjusted variance
832      */
833     public static double variance(final double[] values) {
834         final int length = values.length;
835         final double mean = mean(values);
836         double var = Double.NaN;
837         if (length == 1) {
838             var = 0.0;
839         } else if (length > 1) {
840             double accum = 0.0;
841             double dev = 0.0;
842             double accum2 = 0.0;
843             for (int i = 0; i < length; i++) {
844                 dev = values[i] - mean;
845                 accum += dev * dev;
846                 accum2 += dev;
847             }
848             final double len = length;
849             var = (accum - (accum2 * accum2 / len)) / (len - 1.0);
850         }
851         return var;
852     }
853 
854     /**
855      * Computes the standard deviation of the values in the input array.
856      *
857      * @param values input values
858      * @return standard deviation
859      */
860     public static double standardDeviation(final double[] values) {
861         return FastMath.sqrt(variance(values));
862     }
863 
864     /**
865      * Computes the median of the values in the input array.
866      *
867      * @param values input values
868      * @return estimated median
869      */
870     public static double median(final double[] values) {
871         final int len = values.length;
872         final double[] sortedValues = Arrays.copyOf(values, len);
873         Arrays.sort(sortedValues);
874         if (len % 2 == 0) {
875             return ((double)sortedValues[len/2] + (double)sortedValues[len/2 - 1])/2;
876         } else {
877             return (double) sortedValues[len/2];
878         }
879     }
880 
881     /**
882      * Computes the covariance of the two input arrays.
883      *
884      * @param xArray first covariate
885      * @param yArray second covariate
886      * @return covariance
887      */
888     public static double covariance(final double[] xArray, final double[] yArray) {
889         double result = 0d;
890         final int length = xArray.length;
891         final double xMean = mean(xArray);
892         final double yMean = mean(yArray);
893         for (int i = 0; i < length; i++) {
894             final double xDev = xArray[i] - xMean;
895             final double yDev = yArray[i] - yMean;
896             result += (xDev * yDev - result) / (i + 1);
897         }
898         return result * ((double) length / (double)(length - 1));
899     }
900 
901     /**
902      * Computes a covariance matrix from a matrix whose columns represent covariates.
903      *
904      * @param matrix input matrix
905      * @return covariance matrix
906      */
907     public static RealMatrix covarianceMatrix(RealMatrix matrix) {
908         int dimension = matrix.getColumnDimension();
909         final RealMatrix outMatrix = new BlockRealMatrix(dimension, dimension);
910         for (int i = 0; i < dimension; i++) {
911             for (int j = 0; j < i; j++) {
912                 final double cov = covariance(matrix.getColumn(i), matrix.getColumn(j));
913                 outMatrix.setEntry(i, j, cov);
914                 outMatrix.setEntry(j, i, cov);
915             }
916             outMatrix.setEntry(i, i, variance(matrix.getColumn(i)));
917         }
918         return outMatrix;
919     }
920 
921     public static double min(final double[] values) {
922         double min = values[0];
923         for (int i = 1; i < values.length; i++) {
924             if (values[i] < min) {
925                 min = values[i];
926             }
927         }
928         return min;
929     }
930 
931     /**
932      * Computes the maximum of the values in the input array.
933      *
934      * @param values input array
935      * @return the maximum value
936      */
937     public static double max(final double[] values) {
938         double max = values[0];
939         for (int i = 1; i < values.length; i++) {
940             if (values[i] > max) {
941                 max = values[i];
942             }
943         }
944         return max;
945     }
946 
947     /**
948      * Unpacks a list of Doubles into a double[].
949      *
950      * @param values list of Double
951      * @return double array
952      */
953     private static double[] unpack(List<Double> values) {
954         int n = values.size();
955         if (values == null || n == 0) {
956             return new double[] {};
957         }
958         double[] out = new double[n];
959         for (int i = 0; i < n; i++) {
960             out[i] = values.get(i);
961         }
962         return out;
963     }
964 
965     /**
966      * Keeps track of the number of occurrences of distinct T instances
967      * added via {@link #addValue(Object)}.
968      *
969      * @param <T> type of objects being tracked
970      */
971     public static class Frequency<T> {
972         private Map<T, Integer> counts = new HashMap<>();
973         public void addValue(T value) {
974            Integer old = counts.put(value, 0);
975            if (old != null) {
976                counts.put(value, old++);
977            }
978         }
979         public int getCount(T value) {
980            Integer ret = counts.get(value);
981            return ret == null ? 0 : ret;
982         }
983     }
984 
985     /**
986      * Stripped down implementation of StreamingStatistics from o.h.stat.descriptive.
987      * Actually holds all values in memory, so not suitable for very large streams of data.
988      */
989     public static class SimpleStatistics {
990         private final List<Double> values = new ArrayList<>();
991         public void addValue(double value) {
992             values.add(value);
993         }
994         public double getMean() {
995             return mean(unpack(values));
996         }
997         public double getStandardDeviation() {
998             return standardDeviation(unpack(values));
999         }
1000         public double getMin() {
1001             return min(unpack(values));
1002         }
1003         public double getMax() {
1004             return max(unpack(values));
1005         }
1006         public double getMedian() {
1007             return median(unpack(values));
1008         }
1009         public double getVariance() {
1010             return variance(unpack(values));
1011         }
1012         public long getN() {
1013             return values.size();
1014         }
1015     }
1016 
1017     /**
1018      * Stripped-down version of the bivariate regression class with the same name
1019      * in o.h.stat.regression.
1020      * Always estimates the model with an intercept term.
1021      */
1022     public static class SimpleRegression {
1023         private double sumX = 0d;
1024         private double sumXX = 0d;
1025         private double sumY = 0d;
1026         private double sumXY = 0d;
1027         private long n = 0;
1028         private double xbar = 0;
1029         private double ybar = 0;
1030 
1031         public void addData(double x, double y) {
1032             if (n == 0) {
1033                 xbar = x;
1034                 ybar = y;
1035             } else {
1036                 final double fact1 = 1.0 + n;
1037                 final double fact2 = n / (1.0 + n);
1038                 final double dx = x - xbar;
1039                 final double dy = y - ybar;
1040                 sumXX += dx * dx * fact2;
1041                 sumXY += dx * dy * fact2;
1042                 xbar += dx / fact1;
1043                 ybar += dy / fact1;
1044             }
1045             sumX += x;
1046             sumY += y;
1047             n++;
1048         }
1049 
1050         public double getSlope() {
1051             if (n < 2) {
1052                 return Double.NaN; //not enough data
1053             }
1054             if (FastMath.abs(sumXX) < 10 * Double.MIN_VALUE) {
1055                 return Double.NaN; //not enough variation in x
1056             }
1057             return sumXY / sumXX;
1058         }
1059 
1060         public double getIntercept() {
1061             return (sumY - getSlope() * sumX) / n;
1062         }
1063     }
1064 }