anderson_darling.hpp 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. /*
  2. * Copyright Nick Thompson, 2019
  3. * Use, modification and distribution are subject to the
  4. * Boost Software License, Version 1.0. (See accompanying file
  5. * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. */
  7. #ifndef BOOST_MATH_STATISTICS_ANDERSON_DARLING_HPP
  8. #define BOOST_MATH_STATISTICS_ANDERSON_DARLING_HPP
  9. #include <cmath>
  10. #include <algorithm>
  11. #include <boost/math/statistics/univariate_statistics.hpp>
  12. #include <boost/math/special_functions/erf.hpp>
  13. namespace boost { namespace math { namespace statistics {
  14. template<class RandomAccessContainer>
  15. auto anderson_darling_normality_statistic(RandomAccessContainer const & v,
  16. typename RandomAccessContainer::value_type mu = std::numeric_limits<typename RandomAccessContainer::value_type>::quiet_NaN(),
  17. typename RandomAccessContainer::value_type sd = std::numeric_limits<typename RandomAccessContainer::value_type>::quiet_NaN())
  18. {
  19. using Real = typename RandomAccessContainer::value_type;
  20. using std::log;
  21. using std::sqrt;
  22. using boost::math::erfc;
  23. if (std::isnan(mu)) {
  24. mu = boost::math::statistics::mean(v);
  25. }
  26. if (std::isnan(sd)) {
  27. sd = sqrt(boost::math::statistics::sample_variance(v));
  28. }
  29. typedef boost::math::policies::policy<
  30. boost::math::policies::promote_float<false>,
  31. boost::math::policies::promote_double<false> >
  32. no_promote_policy;
  33. // This is where Knuth's literate programming could really come in handy!
  34. // I need some LaTeX. The idea is that before any observation, the ecdf is identically zero.
  35. // So we need to compute:
  36. // \int_{-\infty}^{v_0} \frac{F(x)F'(x)}{1- F(x)} \, \mathrm{d}x, where F(x) := \frac{1}{2}[1+\erf(\frac{x-\mu}{\sigma \sqrt{2}})]
  37. // Astonishingly, there is an analytic evaluation to this integral, as you can validate with the following Mathematica command:
  38. // Integrate[(1/2 (1 + Erf[(x - mu)/Sqrt[2*sigma^2]])*Exp[-(x - mu)^2/(2*sigma^2)]*1/Sqrt[2*\[Pi]*sigma^2])/(1 - 1/2 (1 + Erf[(x - mu)/Sqrt[2*sigma^2]])),
  39. // {x, -Infinity, x0}, Assumptions -> {x0 \[Element] Reals && mu \[Element] Reals && sigma > 0}]
  40. // This gives (for s = x-mu/sqrt(2sigma^2))
  41. // -1/2 + erf(s) + log(2/(1+erf(s)))
  42. Real inv_var_scale = 1/(sd*sqrt(Real(2)));
  43. Real s0 = (v[0] - mu)*inv_var_scale;
  44. Real erfcs0 = erfc(s0, no_promote_policy());
  45. // Note that if erfcs0 == 0, then left_tail = inf (numerically), and hence the entire integral is numerically infinite:
  46. if (erfcs0 <= 0) {
  47. return std::numeric_limits<Real>::infinity();
  48. }
  49. // Note that we're going to add erfcs0/2 when we compute the integral over [x_0, x_1], so drop it here:
  50. Real left_tail = -1 + log(Real(2));
  51. // For the right tail, the ecdf is identically 1.
  52. // Hence we need the integral:
  53. // \int_{v_{n-1}}^{\infty} \frac{(1-F(x))F'(x)}{F(x)} \, \mathrm{d}x
  54. // This also has an analytic evaluation! It can be found via the following Mathematica command:
  55. // Integrate[(E^(-(z^2/2)) *(1 - 1/2 (1 + Erf[z/Sqrt[2]])))/(Sqrt[2 \[Pi]] (1/2 (1 + Erf[z/Sqrt[2]]))),
  56. // {z, zn, \[Infinity]}, Assumptions -> {zn \[Element] Reals && mu \[Element] Reals}]
  57. // This gives (for sf = xf-mu/sqrt(2sigma^2))
  58. // -1/2 + erf(sf)/2 + 2log(2/(1+erf(sf)))
  59. Real sf = (v[v.size()-1] - mu)*inv_var_scale;
  60. //Real erfcsf = erfc<Real>(sf, no_promote_policy());
  61. // This is the actual value of the tail integral. However, the -erfcsf/2 cancels from the integral over [v_{n-2}, v_{n-1}]:
  62. //Real right_tail = -erfcsf/2 + log(Real(2)) - log(2-erfcsf);
  63. // Use erfc(-x) = 2 - erfc(x)
  64. Real erfcmsf = erfc<Real>(-sf, no_promote_policy());
  65. // Again if this is precisely zero then the integral is numerically infinite:
  66. if (erfcmsf == 0) {
  67. return std::numeric_limits<Real>::infinity();
  68. }
  69. Real right_tail = log(2/erfcmsf);
  70. // Now we need each integral:
  71. // \int_{v_i}^{v_{i+1}} \frac{(i+1/n - F(x))^2F'(x)}{F(x)(1-F(x))} \, \mathrm{d}x
  72. // Again we get an analytical evaluation via the following Mathematica command:
  73. // Integrate[((E^(-(z^2/2))/Sqrt[2 \[Pi]])*(k1 - F[z])^2)/(F[z]*(1 - F[z])),
  74. // {z, z1, z2}, Assumptions -> {z1 \[Element] Reals && z2 \[Element] Reals &&k1 \[Element] Reals}] // FullSimplify
  75. Real integrals = 0;
  76. int64_t N = v.size();
  77. for (int64_t i = 0; i < N - 1; ++i) {
  78. if (v[i] > v[i+1]) {
  79. throw std::domain_error("Input data must be sorted in increasing order v[0] <= v[1] <= . . . <= v[n-1]");
  80. }
  81. Real k = (i+1)/Real(N);
  82. Real s1 = (v[i+1]-mu)*inv_var_scale;
  83. Real erfcs1 = erfc<Real>(s1, no_promote_policy());
  84. Real term = k*(k*log(erfcs0*(-2 + erfcs1)/(erfcs1*(-2 + erfcs0))) + 2*log(erfcs1/erfcs0));
  85. integrals += term;
  86. s0 = s1;
  87. erfcs0 = erfcs1;
  88. }
  89. integrals -= log(erfcs0);
  90. return v.size()*(left_tail + right_tail + integrals);
  91. }
  92. }}}
  93. #endif