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.random;
24
25 import org.hipparchus.distribution.RealDistribution;
26 import org.hipparchus.exception.LocalizedCoreFormats;
27 import org.hipparchus.exception.MathIllegalArgumentException;
28 import org.hipparchus.exception.MathIllegalStateException;
29 import org.hipparchus.exception.MathRuntimeException;
30 import org.hipparchus.fraction.BigFraction;
31 import org.hipparchus.fraction.BigFractionField;
32 import org.hipparchus.linear.Array2DRowFieldMatrix;
33 import org.hipparchus.linear.FieldMatrix;
34 import org.hipparchus.linear.MatrixUtils;
35 import org.hipparchus.linear.RealMatrix;
36 import org.hipparchus.util.FastMath;
37 import org.hipparchus.util.MathUtils;
38
39 import java.math.RoundingMode;
40 import java.util.Arrays;
41
42 /**
43 * This is a stripped-down copy of the class from hipparchus-stat, fir test purposes only.
44 */
45 class KolmogorovSmirnovTest { // NOPMD - this is not a Junit test class, PMD false positive here
46
47 /**
48 * Bound on the number of partial sums
49 */
50 protected static final int MAXIMUM_PARTIAL_SUM_COUNT = 100000;
51
52 /** Convergence criterion for the sums in #pelzGood(double, double, int)} */
53 protected static final double PG_SUM_RELATIVE_ERROR = 1.0e-10;
54
55 /**
56 * Computes the one-sample Kolmogorov-Smirnov test statistic, \(D_n=\sup_x |F_n(x)-F(x)|\) where
57 * \(F\) is the distribution (cdf) function associated with {@code distribution}, \(n\) is the
58 * length of {@code data} and \(F_n\) is the empirical distribution that puts mass \(1/n\) at
59 * each of the values in {@code data}.
60 *
61 * @param distribution reference distribution
62 * @param data sample being evaluated
63 * @return Kolmogorov-Smirnov statistic \(D_n\)
64 * @throws MathIllegalArgumentException if {@code data} does not have length at least 2
65 * @throws org.hipparchus.exception.NullArgumentException if {@code data} is null
66 */
67 public double kolmogorovSmirnovStatistic(RealDistribution distribution, double[] data) {
68 checkArray(data);
69 final int n = data.length;
70 final double nd = n;
71 final double[] dataCopy = new double[n];
72 System.arraycopy(data, 0, dataCopy, 0, n);
73 Arrays.sort(dataCopy);
74 double d = 0d;
75 for (int i = 1; i <= n; i++) {
76 final double yi = distribution.cumulativeProbability(dataCopy[i - 1]);
77 final double currD = FastMath.max(yi - (i - 1) / nd, i / nd - yi);
78 if (currD > d) {
79 d = currD;
80 }
81 }
82 return d;
83 }
84
85 /**
86 * Calculates {@code P(D_n < d)} using the method described in [1] with quick decisions for extreme
87 * values given in [2] (see above).
88 *
89 * @param d statistic
90 * @param n sample size
91 * @return \(P(D_n < d)\)
92 * @throws MathRuntimeException if algorithm fails to convert {@code h} to a
93 * {@link BigFraction} in expressing {@code d} as \((k
94 * - h) / m\) for integer {@code k, m} and \(0 <= h < 1\)
95 */
96 public double cdf(double d, int n)
97 throws MathRuntimeException {
98 return cdf(d, n, false);
99 }
100
101 /**
102 * Calculates {@code P(D_n < d)} using method described in [1] with quick decisions for extreme
103 * values given in [2] (see above).
104 *
105 * @param d statistic
106 * @param n sample size
107 * @param exact whether the probability should be calculated exact using
108 * {@link BigFraction} everywhere at the expense of
109 * very slow execution time, or if {@code double} should be used convenient places to
110 * gain speed. Almost never choose {@code true} in real applications unless you are very
111 * sure; {@code true} is almost solely for verification purposes.
112 * @return \(P(D_n < d)\)
113 * @throws MathRuntimeException if algorithm fails to convert {@code h} to a
114 * {@link BigFraction} in expressing {@code d} as \((k
115 * - h) / m\) for integer {@code k, m} and \(0 \lt;= h < 1\).
116 */
117 public double cdf(double d, int n, boolean exact)
118 throws MathRuntimeException {
119
120 final double ninv = 1 / ((double) n);
121 final double ninvhalf = 0.5 * ninv;
122
123 if (d <= ninvhalf) {
124 return 0;
125 } else if (ninvhalf < d && d <= ninv) {
126 double res = 1;
127 final double f = 2 * d - ninv;
128 // n! f^n = n*f * (n-1)*f * ... * 1*x
129 for (int i = 1; i <= n; ++i) {
130 res *= i * f;
131 }
132 return res;
133 } else if (1 - ninv <= d && d < 1) {
134 return 1 - 2 * Math.pow(1 - d, n);
135 } else if (1 <= d) {
136 return 1;
137 }
138 if (exact) {
139 return exactK(d, n);
140 }
141 if (n <= 140) {
142 return roundedK(d, n);
143 }
144 return pelzGood(d, n);
145 }
146
147 /**
148 * Calculates the exact value of {@code P(D_n < d)} using the method described in [1] (reference
149 * in class javadoc above) and {@link BigFraction} (see
150 * above).
151 *
152 * @param d statistic
153 * @param n sample size
154 * @return the two-sided probability of \(P(D_n < d)\)
155 * @throws MathRuntimeException if algorithm fails to convert {@code h} to a
156 * {@link BigFraction} in expressing {@code d} as \((k
157 * - h) / m\) for integer {@code k, m} and \(0 \le h < 1\).
158 */
159 private double exactK(double d, int n)
160 throws MathRuntimeException {
161
162 final int k = (int) Math.ceil(n * d);
163
164 final FieldMatrix<BigFraction> H = this.createExactH(d, n);
165 final FieldMatrix<BigFraction> Hpower = H.power(n);
166
167 BigFraction pFrac = Hpower.getEntry(k - 1, k - 1);
168
169 for (int i = 1; i <= n; ++i) {
170 pFrac = pFrac.multiply(i).divide(n);
171 }
172
173 /*
174 * BigFraction.doubleValue converts numerator to double and the denominator to double and
175 * divides afterwards. That gives NaN quite easy. This does not (scale is the number of
176 * digits):
177 */
178 return pFrac.bigDecimalValue(20, RoundingMode.HALF_UP).doubleValue();
179 }
180
181 /**
182 * Calculates {@code P(D_n < d)} using method described in [1] and doubles (see above).
183 *
184 * @param d statistic
185 * @param n sample size
186 * @return \(P(D_n < d)\)
187 */
188 private double roundedK(double d, int n) {
189
190 final int k = (int) Math.ceil(n * d);
191 final RealMatrix H = this.createRoundedH(d, n);
192 final RealMatrix Hpower = H.power(n);
193
194 double pFrac = Hpower.getEntry(k - 1, k - 1);
195 for (int i = 1; i <= n; ++i) {
196 pFrac *= ((double) i) / n;
197 }
198
199 return pFrac;
200 }
201
202 /**
203 * Computes the Pelz-Good approximation for \(P(D_n < d)\) as described in [2] in the class javadoc.
204 *
205 * @param d value of d-statistic (x in [2])
206 * @param n sample size
207 * @return \(P(D_n < d)\)
208 */
209 public double pelzGood(double d, int n) {
210 // Change the variable since approximation is for the distribution evaluated at d / sqrt(n)
211 final double sqrtN = FastMath.sqrt(n);
212 final double z = d * sqrtN;
213 final double z2 = d * d * n;
214 final double z4 = z2 * z2;
215 final double z6 = z4 * z2;
216 final double z8 = z4 * z4;
217
218 // Compute K_0(z)
219 double sum = 0;
220 double z2Term = MathUtils.PI_SQUARED / (8 * z2);
221 int k = 1;
222 for (; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) {
223 final double kTerm = 2 * k - 1;
224 final double increment = FastMath.exp(-z2Term * kTerm * kTerm);
225 sum += increment;
226 if (increment <= PG_SUM_RELATIVE_ERROR * sum) {
227 break;
228 }
229 }
230 if (k == MAXIMUM_PARTIAL_SUM_COUNT) {
231 throw new MathIllegalStateException(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, MAXIMUM_PARTIAL_SUM_COUNT);
232 }
233 double ret = sum * FastMath.sqrt(2 * FastMath.PI) / z;
234
235 // K_1(z)
236 // Sum is -inf to inf, but k term is always (k + 1/2) ^ 2, so really have
237 // twice the sum from k = 0 to inf (k = -1 is same as 0, -2 same as 1, ...)
238 final double twoZ2 = 2 * z2;
239 sum = 0;
240 for (k = 0; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) {
241 final double kTerm = k + 0.5;
242 final double kTerm2 = kTerm * kTerm;
243 final double increment = (MathUtils.PI_SQUARED * kTerm2 - z2) * FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2);
244 sum += increment;
245 if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum)) {
246 break;
247 }
248 }
249 if (k == MAXIMUM_PARTIAL_SUM_COUNT) {
250 throw new MathIllegalStateException(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, MAXIMUM_PARTIAL_SUM_COUNT);
251 }
252 final double sqrtHalfPi = FastMath.sqrt(FastMath.PI / 2);
253 // Instead of doubling sum, divide by 3 instead of 6
254 ret += sum * sqrtHalfPi / (3 * z4 * sqrtN);
255
256 // K_2(z)
257 // Same drill as K_1, but with two doubly infinite sums, all k terms are even powers.
258 final double z4Term = 2 * z4;
259 final double z6Term = 6 * z6;
260 z2Term = 5 * z2;
261 final double pi4 = MathUtils.PI_SQUARED * MathUtils.PI_SQUARED;
262 sum = 0;
263 for (k = 0; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) {
264 final double kTerm = k + 0.5;
265 final double kTerm2 = kTerm * kTerm;
266 final double increment = (z6Term + z4Term + MathUtils.PI_SQUARED * (z4Term - z2Term) * kTerm2 +
267 pi4 * (1 - twoZ2) * kTerm2 * kTerm2) * FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2);
268 sum += increment;
269 if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum)) {
270 break;
271 }
272 }
273 if (k == MAXIMUM_PARTIAL_SUM_COUNT) {
274 throw new MathIllegalStateException(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, MAXIMUM_PARTIAL_SUM_COUNT);
275 }
276 double sum2 = 0;
277 for (k = 1; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) {
278 final double kTerm2 = k * k;
279 final double increment = MathUtils.PI_SQUARED * kTerm2 * FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2);
280 sum2 += increment;
281 if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum2)) {
282 break;
283 }
284 }
285 if (k == MAXIMUM_PARTIAL_SUM_COUNT) {
286 throw new MathIllegalStateException(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, MAXIMUM_PARTIAL_SUM_COUNT);
287 }
288 // Again, adjust coefficients instead of doubling sum, sum2
289 ret += (sqrtHalfPi / n) * (sum / (36 * z2 * z2 * z2 * z) - sum2 / (18 * z2 * z));
290
291 // K_3(z) One more time with feeling - two doubly infinite sums, all k powers even.
292 // Multiply coefficient denominators by 2, so omit doubling sums.
293 final double pi6 = pi4 * MathUtils.PI_SQUARED;
294 sum = 0;
295 for (k = 0; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) {
296 final double kTerm = k + 0.5;
297 final double kTerm2 = kTerm * kTerm;
298 final double kTerm4 = kTerm2 * kTerm2;
299 final double kTerm6 = kTerm4 * kTerm2;
300 final double increment = (pi6 * kTerm6 * (5 - 30 * z2) + pi4 * kTerm4 * (-60 * z2 + 212 * z4) +
301 MathUtils.PI_SQUARED * kTerm2 * (135 * z4 - 96 * z6) - 30 * z6 - 90 * z8) *
302 FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2);
303 sum += increment;
304 if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum)) {
305 break;
306 }
307 }
308 if (k == MAXIMUM_PARTIAL_SUM_COUNT) {
309 throw new MathIllegalStateException(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, MAXIMUM_PARTIAL_SUM_COUNT);
310 }
311 sum2 = 0;
312 for (k = 1; k < MAXIMUM_PARTIAL_SUM_COUNT; k++) {
313 final double kTerm2 = k * k;
314 final double kTerm4 = kTerm2 * kTerm2;
315 final double increment = (-pi4 * kTerm4 + 3 * MathUtils.PI_SQUARED * kTerm2 * z2) *
316 FastMath.exp(-MathUtils.PI_SQUARED * kTerm2 / twoZ2);
317 sum2 += increment;
318 if (FastMath.abs(increment) < PG_SUM_RELATIVE_ERROR * FastMath.abs(sum2)) {
319 break;
320 }
321 }
322 if (k == MAXIMUM_PARTIAL_SUM_COUNT) {
323 throw new MathIllegalStateException(LocalizedCoreFormats.MAX_COUNT_EXCEEDED, MAXIMUM_PARTIAL_SUM_COUNT);
324 }
325 return ret + (sqrtHalfPi / (sqrtN * n)) * (sum / (3240 * z6 * z4) + sum2 / (108 * z6));
326
327 }
328
329 /***
330 * Creates {@code H} of size {@code m x m} as described in [1] (see above).
331 *
332 * @param d statistic
333 * @param n sample size
334 * @return H matrix
335 * @throws MathIllegalArgumentException if fractional part is greater than 1
336 * @throws MathIllegalStateException if algorithm fails to convert {@code h} to a
337 * {@link BigFraction} in expressing {@code d} as \((k
338 * - h) / m\) for integer {@code k, m} and \(0 <= h < 1\).
339 */
340 private FieldMatrix<BigFraction> createExactH(double d, int n)
341 throws MathIllegalArgumentException, MathIllegalStateException {
342
343 final int k = (int) Math.ceil(n * d);
344 final int m = 2 * k - 1;
345 final double hDouble = k - n * d;
346 if (hDouble >= 1) {
347 throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE_BOUND_EXCLUDED,
348 hDouble, 1.0);
349 }
350 BigFraction h;
351 try {
352 h = new BigFraction(hDouble, 1.0e-20, 10000);
353 } catch (final MathIllegalStateException e1) {
354 try {
355 h = new BigFraction(hDouble, 1.0e-10, 10000);
356 } catch (final MathIllegalStateException e2) {
357 h = new BigFraction(hDouble, 1.0e-5, 10000);
358 }
359 }
360 final BigFraction[][] Hdata = new BigFraction[m][m];
361
362 /*
363 * Start by filling everything with either 0 or 1.
364 */
365 for (int i = 0; i < m; ++i) {
366 for (int j = 0; j < m; ++j) {
367 if (i - j + 1 < 0) {
368 Hdata[i][j] = BigFraction.ZERO;
369 } else {
370 Hdata[i][j] = BigFraction.ONE;
371 }
372 }
373 }
374
375 /*
376 * Setting up power-array to avoid calculating the same value twice: hPowers[0] = h^1 ...
377 * hPowers[m-1] = h^m
378 */
379 final BigFraction[] hPowers = new BigFraction[m];
380 hPowers[0] = h;
381 for (int i = 1; i < m; ++i) {
382 hPowers[i] = h.multiply(hPowers[i - 1]);
383 }
384
385 /*
386 * First column and last row has special values (each other reversed).
387 */
388 for (int i = 0; i < m; ++i) {
389 Hdata[i][0] = Hdata[i][0].subtract(hPowers[i]);
390 Hdata[m - 1][i] = Hdata[m - 1][i].subtract(hPowers[m - i - 1]);
391 }
392
393 /*
394 * [1] states: "For 1/2 < h < 1 the bottom left element of the matrix should be (1 - 2*h^m +
395 * (2h - 1)^m )/m!" Since 0 <= h < 1, then if h > 1/2 is sufficient to check:
396 */
397 if (h.compareTo(BigFraction.ONE_HALF) == 1) {
398 Hdata[m - 1][0] = Hdata[m - 1][0].add(h.multiply(2).subtract(1).pow(m));
399 }
400
401 /*
402 * Aside from the first column and last row, the (i, j)-th element is 1/(i - j + 1)! if i -
403 * j + 1 >= 0, else 0. 1's and 0's are already put, so only division with (i - j + 1)! is
404 * needed in the elements that have 1's. There is no need to calculate (i - j + 1)! and then
405 * divide - small steps avoid overflows. Note that i - j + 1 > 0 <=> i + 1 > j instead of
406 * j'ing all the way to m. Also note that it is started at g = 2 because dividing by 1 isn't
407 * really necessary.
408 */
409 for (int i = 0; i < m; ++i) {
410 for (int j = 0; j < i + 1; ++j) {
411 if (i - j + 1 > 0) {
412 for (int g = 2; g <= i - j + 1; ++g) {
413 Hdata[i][j] = Hdata[i][j].divide(g);
414 }
415 }
416 }
417 }
418 return new Array2DRowFieldMatrix<>(BigFractionField.getInstance(), Hdata);
419 }
420
421 /***
422 * Creates {@code H} of size {@code m x m} as described in [1] (see above)
423 * using double-precision.
424 *
425 * @param d statistic
426 * @param n sample size
427 * @return H matrix
428 * @throws MathIllegalArgumentException if fractional part is greater than 1
429 */
430 private RealMatrix createRoundedH(double d, int n)
431 throws MathIllegalArgumentException {
432
433 final int k = (int) Math.ceil(n * d);
434 final int m = 2 * k - 1;
435 final double h = k - n * d;
436 if (h >= 1) {
437 throw new MathIllegalArgumentException(LocalizedCoreFormats.NUMBER_TOO_LARGE_BOUND_EXCLUDED,
438 h, 1.0);
439 }
440 final double[][] Hdata = new double[m][m];
441
442 /*
443 * Start by filling everything with either 0 or 1.
444 */
445 for (int i = 0; i < m; ++i) {
446 for (int j = 0; j < m; ++j) {
447 if (i - j + 1 < 0) {
448 Hdata[i][j] = 0;
449 } else {
450 Hdata[i][j] = 1;
451 }
452 }
453 }
454
455 /*
456 * Setting up power-array to avoid calculating the same value twice: hPowers[0] = h^1 ...
457 * hPowers[m-1] = h^m
458 */
459 final double[] hPowers = new double[m];
460 hPowers[0] = h;
461 for (int i = 1; i < m; ++i) {
462 hPowers[i] = h * hPowers[i - 1];
463 }
464
465 /*
466 * First column and last row has special values (each other reversed).
467 */
468 for (int i = 0; i < m; ++i) {
469 Hdata[i][0] = Hdata[i][0] - hPowers[i];
470 Hdata[m - 1][i] -= hPowers[m - i - 1];
471 }
472
473 /*
474 * [1] states: "For 1/2 < h < 1 the bottom left element of the matrix should be (1 - 2*h^m +
475 * (2h - 1)^m )/m!" Since 0 <= h < 1, then if h > 1/2 is sufficient to check:
476 */
477 if (Double.compare(h, 0.5) > 0) {
478 Hdata[m - 1][0] += FastMath.pow(2 * h - 1, m);
479 }
480
481 /*
482 * Aside from the first column and last row, the (i, j)-th element is 1/(i - j + 1)! if i -
483 * j + 1 >= 0, else 0. 1's and 0's are already put, so only division with (i - j + 1)! is
484 * needed in the elements that have 1's. There is no need to calculate (i - j + 1)! and then
485 * divide - small steps avoid overflows. Note that i - j + 1 > 0 <=> i + 1 > j instead of
486 * j'ing all the way to m. Also note that it is started at g = 2 because dividing by 1 isn't
487 * really necessary.
488 */
489 for (int i = 0; i < m; ++i) {
490 for (int j = 0; j < i + 1; ++j) {
491 if (i - j + 1 > 0) {
492 for (int g = 2; g <= i - j + 1; ++g) {
493 Hdata[i][j] /= g;
494 }
495 }
496 }
497 }
498 return MatrixUtils.createRealMatrix(Hdata);
499 }
500
501 /**
502 * Verifies that {@code array} has length at least 2.
503 *
504 * @param array array to test
505 * @throws org.hipparchus.exception.NullArgumentException if array is null
506 * @throws MathIllegalArgumentException if array is too short
507 */
508 private void checkArray(double[] array) {
509 MathUtils.checkNotNull(array);
510 if (array.length < 2) {
511 throw new MathIllegalArgumentException(LocalizedCoreFormats.INSUFFICIENT_OBSERVED_POINTS_IN_SAMPLE,
512 array.length, 2);
513 }
514 }
515
516 }