bivariate_statistics.hpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469
  1. // (C) Copyright Nick Thompson 2018.
  2. // (C) Copyright Matt Borland 2021.
  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_BIVARIATE_STATISTICS_HPP
  7. #define BOOST_MATH_STATISTICS_BIVARIATE_STATISTICS_HPP
  8. #include <iterator>
  9. #include <tuple>
  10. #include <type_traits>
  11. #include <stdexcept>
  12. #include <future>
  13. #include <thread>
  14. #include <vector>
  15. #include <algorithm>
  16. #include <cmath>
  17. #include <cstddef>
  18. #include <boost/assert.hpp>
  19. // Support compilers with P0024R2 implemented without linking TBB
  20. // https://en.cppreference.com/w/cpp/compiler_support
  21. #ifndef BOOST_NO_CXX17_HDR_EXECUTION
  22. #include <execution>
  23. #define EXEC_COMPATIBLE
  24. #endif
  25. namespace boost{ namespace math{ namespace statistics { namespace detail {
  26. // See Equation III.9 of "Numerically Stable, Single-Pass, Parallel Statistics Algorithms", Bennet et al.
  27. template<typename ReturnType, typename ForwardIterator>
  28. ReturnType means_and_covariance_seq_impl(ForwardIterator u_begin, ForwardIterator u_end, ForwardIterator v_begin, ForwardIterator v_end)
  29. {
  30. using Real = typename std::tuple_element<0, ReturnType>::type;
  31. Real cov = 0;
  32. ForwardIterator u_it = u_begin;
  33. ForwardIterator v_it = v_begin;
  34. Real mu_u = *u_it++;
  35. Real mu_v = *v_it++;
  36. std::size_t i = 1;
  37. while(u_it != u_end && v_it != v_end)
  38. {
  39. Real u_temp = (*u_it++ - mu_u)/(i+1);
  40. Real v_temp = *v_it++ - mu_v;
  41. cov += i*u_temp*v_temp;
  42. mu_u = mu_u + u_temp;
  43. mu_v = mu_v + v_temp/(i+1);
  44. i = i + 1;
  45. }
  46. if(u_it != u_end || v_it != v_end)
  47. {
  48. throw std::domain_error("The size of each sample set must be the same to compute covariance");
  49. }
  50. return std::make_tuple(mu_u, mu_v, cov/i, i);
  51. }
  52. // Numerically stable parallel computation of (co-)variance
  53. // https://dl.acm.org/doi/10.1145/3221269.3223036
  54. template<typename ReturnType, typename ForwardIterator>
  55. ReturnType means_and_covariance_parallel_impl(ForwardIterator u_begin, ForwardIterator u_end, ForwardIterator v_begin, ForwardIterator v_end)
  56. {
  57. using Real = typename std::tuple_element<0, ReturnType>::type;
  58. const auto u_elements = std::distance(u_begin, u_end);
  59. const auto v_elements = std::distance(v_begin, v_end);
  60. if(u_elements != v_elements)
  61. {
  62. throw std::domain_error("The size of each sample set must be the same to compute covariance");
  63. }
  64. const unsigned max_concurrency = std::thread::hardware_concurrency() == 0 ? 2u : std::thread::hardware_concurrency();
  65. unsigned num_threads = 2u;
  66. // 5.16 comes from benchmarking. See boost/math/reporting/performance/bivariate_statistics_performance.cpp
  67. // Threading is faster for: 10 + 5.16e-3 N/j <= 5.16e-3N => N >= 10^4j/5.16(j-1).
  68. const auto parallel_lower_bound = 10e4*max_concurrency/(5.16*(max_concurrency-1));
  69. const auto parallel_upper_bound = 10e4*2/5.16; // j = 2
  70. // https://lemire.me/blog/2020/01/30/cost-of-a-thread-in-c-under-linux/
  71. if(u_elements < parallel_lower_bound)
  72. {
  73. return means_and_covariance_seq_impl<ReturnType>(u_begin, u_end, v_begin, v_end);
  74. }
  75. else if(u_elements >= parallel_upper_bound)
  76. {
  77. num_threads = max_concurrency;
  78. }
  79. else
  80. {
  81. for(unsigned i = 3; i < max_concurrency; ++i)
  82. {
  83. if(parallel_lower_bound < 10e4*i/(5.16*(i-1)))
  84. {
  85. num_threads = i;
  86. break;
  87. }
  88. }
  89. }
  90. std::vector<std::future<ReturnType>> future_manager;
  91. const auto elements_per_thread = std::ceil(static_cast<double>(u_elements)/num_threads);
  92. ForwardIterator u_it = u_begin;
  93. ForwardIterator v_it = v_begin;
  94. for(std::size_t i = 0; i < num_threads - 1; ++i)
  95. {
  96. future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [u_it, v_it, elements_per_thread]() -> ReturnType
  97. {
  98. return means_and_covariance_seq_impl<ReturnType>(u_it, std::next(u_it, elements_per_thread), v_it, std::next(v_it, elements_per_thread));
  99. }));
  100. u_it = std::next(u_it, elements_per_thread);
  101. v_it = std::next(v_it, elements_per_thread);
  102. }
  103. future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [u_it, u_end, v_it, v_end]() -> ReturnType
  104. {
  105. return means_and_covariance_seq_impl<ReturnType>(u_it, u_end, v_it, v_end);
  106. }));
  107. ReturnType temp = future_manager[0].get();
  108. Real mu_u_a = std::get<0>(temp);
  109. Real mu_v_a = std::get<1>(temp);
  110. Real cov_a = std::get<2>(temp);
  111. Real n_a = std::get<3>(temp);
  112. for(std::size_t i = 1; i < future_manager.size(); ++i)
  113. {
  114. temp = future_manager[i].get();
  115. Real mu_u_b = std::get<0>(temp);
  116. Real mu_v_b = std::get<1>(temp);
  117. Real cov_b = std::get<2>(temp);
  118. Real n_b = std::get<3>(temp);
  119. const Real n_ab = n_a + n_b;
  120. const Real delta_u = mu_u_b - mu_u_a;
  121. const Real delta_v = mu_v_b - mu_v_a;
  122. cov_a = cov_a + cov_b + (-delta_u)*(-delta_v)*((n_a*n_b)/n_ab);
  123. mu_u_a = mu_u_a + delta_u*(n_b/n_ab);
  124. mu_v_a = mu_v_a + delta_v*(n_b/n_ab);
  125. n_a = n_ab;
  126. }
  127. return std::make_tuple(mu_u_a, mu_v_a, cov_a, n_a);
  128. }
  129. template<typename ReturnType, typename ForwardIterator>
  130. ReturnType correlation_coefficient_seq_impl(ForwardIterator u_begin, ForwardIterator u_end, ForwardIterator v_begin, ForwardIterator v_end)
  131. {
  132. using Real = typename std::tuple_element<0, ReturnType>::type;
  133. using std::sqrt;
  134. Real cov = 0;
  135. ForwardIterator u_it = u_begin;
  136. ForwardIterator v_it = v_begin;
  137. Real mu_u = *u_it++;
  138. Real mu_v = *v_it++;
  139. Real Qu = 0;
  140. Real Qv = 0;
  141. std::size_t i = 1;
  142. while(u_it != u_end && v_it != v_end)
  143. {
  144. Real u_tmp = *u_it++ - mu_u;
  145. Real v_tmp = *v_it++ - mu_v;
  146. Qu = Qu + (i*u_tmp*u_tmp)/(i+1);
  147. Qv = Qv + (i*v_tmp*v_tmp)/(i+1);
  148. cov += i*u_tmp*v_tmp/(i+1);
  149. mu_u = mu_u + u_tmp/(i+1);
  150. mu_v = mu_v + v_tmp/(i+1);
  151. ++i;
  152. }
  153. // If both datasets are constant, then they are perfectly correlated.
  154. if (Qu == 0 && Qv == 0)
  155. {
  156. return std::make_tuple(mu_u, Qu, mu_v, Qv, cov, Real(1), i);
  157. }
  158. // If one dataset is constant and the other isn't, then they have no correlation:
  159. if (Qu == 0 || Qv == 0)
  160. {
  161. return std::make_tuple(mu_u, Qu, mu_v, Qv, cov, Real(0), i);
  162. }
  163. // Make sure rho in [-1, 1], even in the presence of numerical noise.
  164. Real rho = cov/sqrt(Qu*Qv);
  165. if (rho > 1) {
  166. rho = 1;
  167. }
  168. if (rho < -1) {
  169. rho = -1;
  170. }
  171. return std::make_tuple(mu_u, Qu, mu_v, Qv, cov, rho, i);
  172. }
  173. // Numerically stable parallel computation of (co-)variance:
  174. // https://dl.acm.org/doi/10.1145/3221269.3223036
  175. //
  176. // Parallel computation of variance:
  177. // http://i.stanford.edu/pub/cstr/reports/cs/tr/79/773/CS-TR-79-773.pdf
  178. template<typename ReturnType, typename ForwardIterator>
  179. ReturnType correlation_coefficient_parallel_impl(ForwardIterator u_begin, ForwardIterator u_end, ForwardIterator v_begin, ForwardIterator v_end)
  180. {
  181. using Real = typename std::tuple_element<0, ReturnType>::type;
  182. const auto u_elements = std::distance(u_begin, u_end);
  183. const auto v_elements = std::distance(v_begin, v_end);
  184. if(u_elements != v_elements)
  185. {
  186. throw std::domain_error("The size of each sample set must be the same to compute covariance");
  187. }
  188. const unsigned max_concurrency = std::thread::hardware_concurrency() == 0 ? 2u : std::thread::hardware_concurrency();
  189. unsigned num_threads = 2u;
  190. // 3.25 comes from benchmarking. See boost/math/reporting/performance/bivariate_statistics_performance.cpp
  191. // Threading is faster for: 10 + 3.25e-3 N/j <= 3.25e-3N => N >= 10^4j/3.25(j-1).
  192. const auto parallel_lower_bound = 10e4*max_concurrency/(3.25*(max_concurrency-1));
  193. const auto parallel_upper_bound = 10e4*2/3.25; // j = 2
  194. // https://lemire.me/blog/2020/01/30/cost-of-a-thread-in-c-under-linux/
  195. if(u_elements < parallel_lower_bound)
  196. {
  197. return correlation_coefficient_seq_impl<ReturnType>(u_begin, u_end, v_begin, v_end);
  198. }
  199. else if(u_elements >= parallel_upper_bound)
  200. {
  201. num_threads = max_concurrency;
  202. }
  203. else
  204. {
  205. for(unsigned i = 3; i < max_concurrency; ++i)
  206. {
  207. if(parallel_lower_bound < 10e4*i/(3.25*(i-1)))
  208. {
  209. num_threads = i;
  210. break;
  211. }
  212. }
  213. }
  214. std::vector<std::future<ReturnType>> future_manager;
  215. const auto elements_per_thread = std::ceil(static_cast<double>(u_elements)/num_threads);
  216. ForwardIterator u_it = u_begin;
  217. ForwardIterator v_it = v_begin;
  218. for(std::size_t i = 0; i < num_threads - 1; ++i)
  219. {
  220. future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [u_it, v_it, elements_per_thread]() -> ReturnType
  221. {
  222. return correlation_coefficient_seq_impl<ReturnType>(u_it, std::next(u_it, elements_per_thread), v_it, std::next(v_it, elements_per_thread));
  223. }));
  224. u_it = std::next(u_it, elements_per_thread);
  225. v_it = std::next(v_it, elements_per_thread);
  226. }
  227. future_manager.emplace_back(std::async(std::launch::async | std::launch::deferred, [u_it, u_end, v_it, v_end]() -> ReturnType
  228. {
  229. return correlation_coefficient_seq_impl<ReturnType>(u_it, u_end, v_it, v_end);
  230. }));
  231. ReturnType temp = future_manager[0].get();
  232. Real mu_u_a = std::get<0>(temp);
  233. Real Qu_a = std::get<1>(temp);
  234. Real mu_v_a = std::get<2>(temp);
  235. Real Qv_a = std::get<3>(temp);
  236. Real cov_a = std::get<4>(temp);
  237. Real n_a = std::get<6>(temp);
  238. for(std::size_t i = 1; i < future_manager.size(); ++i)
  239. {
  240. temp = future_manager[i].get();
  241. Real mu_u_b = std::get<0>(temp);
  242. Real Qu_b = std::get<1>(temp);
  243. Real mu_v_b = std::get<2>(temp);
  244. Real Qv_b = std::get<3>(temp);
  245. Real cov_b = std::get<4>(temp);
  246. Real n_b = std::get<6>(temp);
  247. const Real n_ab = n_a + n_b;
  248. const Real delta_u = mu_u_b - mu_u_a;
  249. const Real delta_v = mu_v_b - mu_v_a;
  250. cov_a = cov_a + cov_b + (-delta_u)*(-delta_v)*((n_a*n_b)/n_ab);
  251. mu_u_a = mu_u_a + delta_u*(n_b/n_ab);
  252. mu_v_a = mu_v_a + delta_v*(n_b/n_ab);
  253. Qu_a = Qu_a + Qu_b + delta_u*delta_u*((n_a*n_b)/n_ab);
  254. Qv_b = Qv_a + Qv_b + delta_v*delta_v*((n_a*n_b)/n_ab);
  255. n_a = n_ab;
  256. }
  257. // If both datasets are constant, then they are perfectly correlated.
  258. if (Qu_a == 0 && Qv_a == 0)
  259. {
  260. return std::make_tuple(mu_u_a, Qu_a, mu_v_a, Qv_a, cov_a, Real(1), n_a);
  261. }
  262. // If one dataset is constant and the other isn't, then they have no correlation:
  263. if (Qu_a == 0 || Qv_a == 0)
  264. {
  265. return std::make_tuple(mu_u_a, Qu_a, mu_v_a, Qv_a, cov_a, Real(0), n_a);
  266. }
  267. // Make sure rho in [-1, 1], even in the presence of numerical noise.
  268. Real rho = cov_a/sqrt(Qu_a*Qv_a);
  269. if (rho > 1) {
  270. rho = 1;
  271. }
  272. if (rho < -1) {
  273. rho = -1;
  274. }
  275. return std::make_tuple(mu_u_a, Qu_a, mu_v_a, Qv_a, cov_a, rho, n_a);
  276. }
  277. } // namespace detail
  278. #ifdef EXEC_COMPATIBLE
  279. template<typename ExecutionPolicy, typename Container, typename Real = typename Container::value_type>
  280. inline auto means_and_covariance(ExecutionPolicy&& exec, Container const & u, Container const & v)
  281. {
  282. if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)
  283. {
  284. if constexpr (std::is_integral_v<Real>)
  285. {
  286. using ReturnType = std::tuple<double, double, double, double>;
  287. ReturnType temp = detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));
  288. return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));
  289. }
  290. else
  291. {
  292. using ReturnType = std::tuple<Real, Real, Real, Real>;
  293. ReturnType temp = detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));
  294. return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));
  295. }
  296. }
  297. else
  298. {
  299. if constexpr (std::is_integral_v<Real>)
  300. {
  301. using ReturnType = std::tuple<double, double, double, double>;
  302. ReturnType temp = detail::means_and_covariance_parallel_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));
  303. return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));
  304. }
  305. else
  306. {
  307. using ReturnType = std::tuple<Real, Real, Real, Real>;
  308. ReturnType temp = detail::means_and_covariance_parallel_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));
  309. return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));
  310. }
  311. }
  312. }
  313. template<typename Container>
  314. inline auto means_and_covariance(Container const & u, Container const & v)
  315. {
  316. return means_and_covariance(std::execution::seq, u, v);
  317. }
  318. template<typename ExecutionPolicy, typename Container>
  319. inline auto covariance(ExecutionPolicy&& exec, Container const & u, Container const & v)
  320. {
  321. return std::get<2>(means_and_covariance(exec, u, v));
  322. }
  323. template<typename Container>
  324. inline auto covariance(Container const & u, Container const & v)
  325. {
  326. return covariance(std::execution::seq, u, v);
  327. }
  328. template<typename ExecutionPolicy, typename Container, typename Real = typename Container::value_type>
  329. inline auto correlation_coefficient(ExecutionPolicy&& exec, Container const & u, Container const & v)
  330. {
  331. if constexpr (std::is_same_v<std::remove_reference_t<decltype(exec)>, decltype(std::execution::seq)>)
  332. {
  333. if constexpr (std::is_integral_v<Real>)
  334. {
  335. using ReturnType = std::tuple<double, double, double, double, double, double, double>;
  336. return std::get<5>(detail::correlation_coefficient_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));
  337. }
  338. else
  339. {
  340. using ReturnType = std::tuple<Real, Real, Real, Real, Real, Real, Real>;
  341. return std::get<5>(detail::correlation_coefficient_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));
  342. }
  343. }
  344. else
  345. {
  346. if constexpr (std::is_integral_v<Real>)
  347. {
  348. using ReturnType = std::tuple<double, double, double, double, double, double, double>;
  349. return std::get<5>(detail::correlation_coefficient_parallel_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));
  350. }
  351. else
  352. {
  353. using ReturnType = std::tuple<Real, Real, Real, Real, Real, Real, Real>;
  354. return std::get<5>(detail::correlation_coefficient_parallel_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));
  355. }
  356. }
  357. }
  358. template<typename Container, typename Real = typename Container::value_type>
  359. inline auto correlation_coefficient(Container const & u, Container const & v)
  360. {
  361. return correlation_coefficient(std::execution::seq, u, v);
  362. }
  363. #else // C++11 bindings
  364. template<typename Container, typename Real = typename Container::value_type, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>
  365. inline auto means_and_covariance(Container const & u, Container const & v) -> std::tuple<double, double, double>
  366. {
  367. using ReturnType = std::tuple<double, double, double, double>;
  368. ReturnType temp = detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));
  369. return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));
  370. }
  371. template<typename Container, typename Real = typename Container::value_type, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>
  372. inline auto means_and_covariance(Container const & u, Container const & v) -> std::tuple<Real, Real, Real>
  373. {
  374. using ReturnType = std::tuple<Real, Real, Real, Real>;
  375. ReturnType temp = detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v));
  376. return std::make_tuple(std::get<0>(temp), std::get<1>(temp), std::get<2>(temp));
  377. }
  378. template<typename Container, typename Real = typename Container::value_type, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>
  379. inline double covariance(Container const & u, Container const & v)
  380. {
  381. using ReturnType = std::tuple<double, double, double, double>;
  382. return std::get<2>(detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));
  383. }
  384. template<typename Container, typename Real = typename Container::value_type, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>
  385. inline Real covariance(Container const & u, Container const & v)
  386. {
  387. using ReturnType = std::tuple<Real, Real, Real, Real>;
  388. return std::get<2>(detail::means_and_covariance_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));
  389. }
  390. template<typename Container, typename Real = typename Container::value_type, typename std::enable_if<std::is_integral<Real>::value, bool>::type = true>
  391. inline double correlation_coefficient(Container const & u, Container const & v)
  392. {
  393. using ReturnType = std::tuple<double, double, double, double, double, double, double>;
  394. return std::get<5>(detail::correlation_coefficient_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));
  395. }
  396. template<typename Container, typename Real = typename Container::value_type, typename std::enable_if<!std::is_integral<Real>::value, bool>::type = true>
  397. inline Real correlation_coefficient(Container const & u, Container const & v)
  398. {
  399. using ReturnType = std::tuple<Real, Real, Real, Real, Real, Real, Real>;
  400. return std::get<5>(detail::correlation_coefficient_seq_impl<ReturnType>(std::begin(u), std::end(u), std::begin(v), std::end(v)));
  401. }
  402. #endif
  403. }}} // namespace boost::math::statistics
  404. #endif