bivariate_statistics.hpp 18 KB

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