single_pass.hpp 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. // (C) Copyright Nick Thompson 2018
  2. // (C) Copyright Matt Borland 2020
  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. #ifndef BOOST_MATH_STATISTICS_UNIVARIATE_STATISTICS_DETAIL_SINGLE_PASS_HPP
  7. #define BOOST_MATH_STATISTICS_UNIVARIATE_STATISTICS_DETAIL_SINGLE_PASS_HPP
  8. #include <boost/assert.hpp>
  9. #include <tuple>
  10. #include <iterator>
  11. #include <atomic>
  12. #include <thread>
  13. #include <type_traits>
  14. #include <future>
  15. #include <cmath>
  16. #include <algorithm>
  17. #include <valarray>
  18. #include <stdexcept>
  19. #include <functional>
  20. #include <vector>
  21. namespace boost { namespace math { namespace statistics { namespace detail {
  22. template<typename ReturnType, typename ForwardIterator>
  23. ReturnType mean_sequential_impl(ForwardIterator first, ForwardIterator last)
  24. {
  25. const std::size_t elements {static_cast<std::size_t>(std::distance(first, last))};
  26. std::valarray<ReturnType> mu {0, 0, 0, 0};
  27. std::valarray<ReturnType> temp {0, 0, 0, 0};
  28. ReturnType i {1};
  29. const ForwardIterator end {std::next(first, elements - (elements % 4))};
  30. ForwardIterator it {first};
  31. while(it != end)
  32. {
  33. const ReturnType inv {ReturnType(1) / i};
  34. temp = {static_cast<ReturnType>(*it++), static_cast<ReturnType>(*it++), static_cast<ReturnType>(*it++), static_cast<ReturnType>(*it++)};
  35. temp -= mu;
  36. mu += (temp *= inv);
  37. i += 1;
  38. }
  39. const ReturnType num1 {ReturnType(elements - (elements % 4))/ReturnType(4)};
  40. const ReturnType num2 {num1 + ReturnType(elements % 4)};
  41. while(it != last)
  42. {
  43. mu[3] += (*it-mu[3])/i;
  44. i += 1;
  45. ++it;
  46. }
  47. return (num1 * std::valarray<ReturnType>(mu[std::slice(0,3,1)]).sum() + num2 * mu[3]) / ReturnType(elements);
  48. }
  49. // Higham, Accuracy and Stability, equation 1.6a and 1.6b:
  50. // Calculates Mean, M2, and variance
  51. template<typename ReturnType, typename ForwardIterator>
  52. ReturnType variance_sequential_impl(ForwardIterator first, ForwardIterator last)
  53. {
  54. using Real = typename std::tuple_element<0, ReturnType>::type;
  55. Real M = *first;
  56. Real Q = 0;
  57. Real k = 2;
  58. Real M2 = 0;
  59. std::size_t n = 1;
  60. for(auto it = std::next(first); it != last; ++it)
  61. {
  62. Real tmp = (*it - M) / k;
  63. Real delta_1 = *it - M;
  64. Q += k*(k-1)*tmp*tmp;
  65. M += tmp;
  66. k += 1;
  67. Real delta_2 = *it - M;
  68. M2 += delta_1 * delta_2;
  69. ++n;
  70. }
  71. return std::make_tuple(M, M2, Q/(k-1), Real(n));
  72. }
  73. // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics
  74. template<typename ReturnType, typename ForwardIterator>
  75. ReturnType first_four_moments_sequential_impl(ForwardIterator first, ForwardIterator last)
  76. {
  77. using Real = typename std::tuple_element<0, ReturnType>::type;
  78. using Size = typename std::tuple_element<4, ReturnType>::type;
  79. Real M1 = *first;
  80. Real M2 = 0;
  81. Real M3 = 0;
  82. Real M4 = 0;
  83. Size n = 2;
  84. for (auto it = std::next(first); it != last; ++it)
  85. {
  86. Real delta21 = *it - M1;
  87. Real tmp = delta21/n;
  88. M4 = M4 + tmp*(tmp*tmp*delta21*((n-1)*(n*n-3*n+3)) + 6*tmp*M2 - 4*M3);
  89. M3 = M3 + tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);
  90. M2 = M2 + tmp*(n-1)*delta21;
  91. M1 = M1 + tmp;
  92. n += 1;
  93. }
  94. return std::make_tuple(M1, M2, M3, M4, n-1);
  95. }
  96. // https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Higher-order_statistics
  97. // EQN 3.1: https://www.osti.gov/servlets/purl/1426900
  98. template<typename ReturnType, typename ForwardIterator>
  99. ReturnType first_four_moments_parallel_impl(ForwardIterator first, ForwardIterator last)
  100. {
  101. using Real = typename std::tuple_element<0, ReturnType>::type;
  102. const auto elements = std::distance(first, last);
  103. const unsigned max_concurrency = std::thread::hardware_concurrency() == 0 ? 2u : std::thread::hardware_concurrency();
  104. unsigned num_threads = 2u;
  105. // Threading is faster for: 10 + 5.13e-3 N/j <= 5.13e-3N => N >= 10^4j/5.13(j-1).
  106. const auto parallel_lower_bound = 10e4*max_concurrency/(5.13*(max_concurrency-1));
  107. const auto parallel_upper_bound = 10e4*2/5.13; // j = 2
  108. // https://lemire.me/blog/2020/01/30/cost-of-a-thread-in-c-under-linux/
  109. if(elements < parallel_lower_bound)
  110. {
  111. return detail::first_four_moments_sequential_impl<ReturnType>(first, last);
  112. }
  113. else if(elements >= parallel_upper_bound)
  114. {
  115. num_threads = max_concurrency;
  116. }
  117. else
  118. {
  119. for(unsigned i = 3; i < max_concurrency; ++i)
  120. {
  121. if(parallel_lower_bound < 10e4*i/(5.13*(i-1)))
  122. {
  123. num_threads = i;
  124. break;
  125. }
  126. }
  127. }
  128. std::vector<std::future<ReturnType>> future_manager;
  129. const auto elements_per_thread = std::ceil(static_cast<double>(elements) / num_threads);
  130. auto it = first;
  131. for(std::size_t i {}; i < num_threads - 1; ++i)
  132. {
  133. future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [it, elements_per_thread]() -> ReturnType
  134. {
  135. return first_four_moments_sequential_impl<ReturnType>(it, std::next(it, elements_per_thread));
  136. }));
  137. it = std::next(it, elements_per_thread);
  138. }
  139. future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [it, last]() -> ReturnType
  140. {
  141. return first_four_moments_sequential_impl<ReturnType>(it, last);
  142. }));
  143. auto temp = future_manager[0].get();
  144. Real M1_a = std::get<0>(temp);
  145. Real M2_a = std::get<1>(temp);
  146. Real M3_a = std::get<2>(temp);
  147. Real M4_a = std::get<3>(temp);
  148. Real range_a = std::get<4>(temp);
  149. for(std::size_t i = 1; i < future_manager.size(); ++i)
  150. {
  151. temp = future_manager[i].get();
  152. Real M1_b = std::get<0>(temp);
  153. Real M2_b = std::get<1>(temp);
  154. Real M3_b = std::get<2>(temp);
  155. Real M4_b = std::get<3>(temp);
  156. Real range_b = std::get<4>(temp);
  157. const Real n_ab = range_a + range_b;
  158. const Real delta = M1_b - M1_a;
  159. M1_a = (range_a * M1_a + range_b * M1_b) / n_ab;
  160. M2_a = M2_a + M2_b + delta * delta * (range_a * range_b / n_ab);
  161. M3_a = M3_a + M3_b + (delta * delta * delta) * range_a * range_b * (range_a - range_b) / (n_ab * n_ab)
  162. + Real(3) * delta * (range_a * M2_b - range_b * M2_a) / n_ab;
  163. M4_a = M4_a + M4_b + (delta * delta * delta * delta) * range_a * range_b * (range_a * range_a - range_a * range_b + range_b * range_b) / (n_ab * n_ab * n_ab)
  164. + Real(6) * delta * delta * (range_a * range_a * M2_b + range_b * range_b * M2_a) / (n_ab * n_ab)
  165. + Real(4) * delta * (range_a * M3_b - range_b * M3_a) / n_ab;
  166. range_a = n_ab;
  167. }
  168. return std::make_tuple(M1_a, M2_a, M3_a, M4_a, elements);
  169. }
  170. // Follows equation 1.5 of:
  171. // https://prod.sandia.gov/techlib-noauth/access-control.cgi/2008/086212.pdf
  172. template<typename ReturnType, typename ForwardIterator>
  173. ReturnType skewness_sequential_impl(ForwardIterator first, ForwardIterator last)
  174. {
  175. using std::sqrt;
  176. BOOST_ASSERT_MSG(first != last, "At least one sample is required to compute skewness.");
  177. ReturnType M1 = *first;
  178. ReturnType M2 = 0;
  179. ReturnType M3 = 0;
  180. ReturnType n = 2;
  181. for (auto it = std::next(first); it != last; ++it)
  182. {
  183. ReturnType delta21 = *it - M1;
  184. ReturnType tmp = delta21/n;
  185. M3 += tmp*((n-1)*(n-2)*delta21*tmp - 3*M2);
  186. M2 += tmp*(n-1)*delta21;
  187. M1 += tmp;
  188. n += 1;
  189. }
  190. ReturnType var = M2/(n-1);
  191. if (var == 0)
  192. {
  193. // The limit is technically undefined, but the interpretation here is clear:
  194. // A constant dataset has no skewness.
  195. return ReturnType(0);
  196. }
  197. ReturnType skew = M3/(M2*sqrt(var));
  198. return skew;
  199. }
  200. template<typename ReturnType, typename ExecutionPolicy, typename RandomAccessIterator>
  201. ReturnType gini_coefficient_parallel_impl(ExecutionPolicy&& exec, RandomAccessIterator first, RandomAccessIterator last)
  202. {
  203. using Real = typename std::iterator_traits<RandomAccessIterator>::value_type;
  204. ReturnType i = 1;
  205. ReturnType num = 0;
  206. ReturnType denom = 0;
  207. std::for_each(exec, first, last, [&i, &num, &denom](const Real& val)
  208. {
  209. num = num + val * i;
  210. denom = denom + val;
  211. i = i + 1;
  212. });
  213. if(denom == 0)
  214. {
  215. return ReturnType(0);
  216. }
  217. return ((2*num)/denom - i)/(i-1);
  218. }
  219. template<typename ReturnType, typename ForwardIterator>
  220. ReturnType gini_coefficient_sequential_impl(ForwardIterator first, ForwardIterator last)
  221. {
  222. ReturnType i = 1;
  223. ReturnType num = 0;
  224. ReturnType denom = 0;
  225. for(auto it = first; it != last; ++it)
  226. {
  227. num += *it*i;
  228. denom += *it;
  229. ++i;
  230. }
  231. // If the l1 norm is zero, all elements are zero, so every element is the same.
  232. if(denom == 0)
  233. {
  234. return ReturnType(0);
  235. }
  236. else
  237. {
  238. return ((2*num)/denom - i)/(i-1);
  239. }
  240. }
  241. template<typename ForwardIterator, typename OutputIterator>
  242. OutputIterator mode_impl(ForwardIterator first, ForwardIterator last, OutputIterator output)
  243. {
  244. using Z = typename std::iterator_traits<ForwardIterator>::value_type;
  245. using Size = typename std::iterator_traits<ForwardIterator>::difference_type;
  246. std::vector<Z> modes {};
  247. modes.reserve(16);
  248. Size max_counter {0};
  249. while(first != last)
  250. {
  251. Size current_count {0};
  252. ForwardIterator end_it {first};
  253. while(end_it != last && *end_it == *first)
  254. {
  255. ++current_count;
  256. ++end_it;
  257. }
  258. if(current_count > max_counter)
  259. {
  260. modes.resize(1);
  261. modes[0] = *first;
  262. max_counter = current_count;
  263. }
  264. else if(current_count == max_counter)
  265. {
  266. modes.emplace_back(*first);
  267. }
  268. first = end_it;
  269. }
  270. return std::move(modes.begin(), modes.end(), output);
  271. }
  272. }}}}
  273. #endif // BOOST_MATH_STATISTICS_UNIVARIATE_STATISTICS_DETAIL_SINGLE_PASS_HPP