1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
60
61 private UnitTestUtils() {
62 super();
63 }
64
65
66
67
68
69 public static void customAssertEquals(double expected, double actual, double delta) {
70 assertEquals(expected, actual, delta);
71 }
72
73
74
75
76
77 public static void customAssertEquals(String msg, double expected, double actual, double delta) {
78
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
89
90
91 public static void customAssertSame(double expected, double actual) {
92 assertEquals(expected, actual, 0);
93 }
94
95
96
97
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
106
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
115
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
124
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
133
134 public static void customAssertEquals(double[] expected, double[] observed, double tolerance) {
135 customAssertEquals("Array comparison failure", expected, observed, tolerance);
136 }
137
138
139
140
141
142
143
144
145 public static Object serializeAndRecover(Object o) {
146 try {
147
148 ByteArrayOutputStream bos = new ByteArrayOutputStream();
149 ObjectOutputStream so = new ObjectOutputStream(bos);
150 so.writeObject(o);
151
152
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
163
164
165
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
175
176
177
178
179
180
181
182 public static void customAssertRelativelyEquals(double expected, double actual,
183 double relativeError) {
184 customAssertRelativelyEquals(null, expected, actual, relativeError);
185 }
186
187
188
189
190
191
192
193
194
195
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
215
216
217
218
219
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
234
235
236
237
238
239 public static void customAssertContains(Complex[] values,
240 Complex z, double epsilon) {
241 customAssertContains(null, values, z, epsilon);
242 }
243
244
245
246
247
248
249
250
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
264
265
266
267
268
269 public static void customAssertContains(double[] values, double x,
270 double epsilon) {
271 customAssertContains(null, values, x, epsilon);
272 }
273
274
275
276
277
278
279
280
281
282
283
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
299
300
301
302
303
304
305
306
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
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
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
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
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
432
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
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
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
511
512
513
514
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
527
528
529
530
531
532
533
534 public static void customAssertChiSquareAccept(String[] valueLabels, double[] expected, long[] observed, double alpha) {
535
536
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
564
565
566
567
568
569
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
581
582
583
584
585
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
597
598
599
600
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
627
628
629
630
631
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
657
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
669
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
685
686
687
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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
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
738
739
740
741
742
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
773
774
775
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
802
803
804
805
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
815
816
817
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
829
830
831
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
856
857
858
859
860 public static double standardDeviation(final double[] values) {
861 return FastMath.sqrt(variance(values));
862 }
863
864
865
866
867
868
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
883
884
885
886
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
903
904
905
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
933
934
935
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
949
950
951
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
967
968
969
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
987
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
1019
1020
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;
1053 }
1054 if (FastMath.abs(sumXX) < 10 * Double.MIN_VALUE) {
1055 return Double.NaN;
1056 }
1057 return sumXY / sumXX;
1058 }
1059
1060 public double getIntercept() {
1061 return (sumY - getSlope() * sumX) / n;
1062 }
1063 }
1064 }