weighted_extended_p_square.hpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // weighted_extended_p_square.hpp
  3. //
  4. // Copyright 2005 Daniel Egloff. Distributed under the Boost
  5. // Software License, Version 1.0. (See accompanying file
  6. // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  7. #ifndef BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_EXTENDED_P_SQUARE_HPP_DE_01_01_2006
  8. #define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_EXTENDED_P_SQUARE_HPP_DE_01_01_2006
  9. #include <vector>
  10. #include <functional>
  11. #include <boost/range/begin.hpp>
  12. #include <boost/range/end.hpp>
  13. #include <boost/range/iterator_range.hpp>
  14. #include <boost/iterator/transform_iterator.hpp>
  15. #include <boost/iterator/counting_iterator.hpp>
  16. #include <boost/iterator/permutation_iterator.hpp>
  17. #include <boost/parameter/keyword.hpp>
  18. #include <boost/mpl/placeholders.hpp>
  19. #include <boost/accumulators/framework/accumulator_base.hpp>
  20. #include <boost/accumulators/framework/extractor.hpp>
  21. #include <boost/accumulators/numeric/functional.hpp>
  22. #include <boost/accumulators/framework/parameters/sample.hpp>
  23. #include <boost/accumulators/framework/depends_on.hpp>
  24. #include <boost/accumulators/statistics_fwd.hpp>
  25. #include <boost/accumulators/statistics/count.hpp>
  26. #include <boost/accumulators/statistics/sum.hpp>
  27. #include <boost/accumulators/statistics/times2_iterator.hpp>
  28. #include <boost/accumulators/statistics/extended_p_square.hpp>
  29. #include <boost/serialization/vector.hpp>
  30. namespace boost { namespace accumulators
  31. {
  32. namespace impl
  33. {
  34. ///////////////////////////////////////////////////////////////////////////////
  35. // weighted_extended_p_square_impl
  36. // multiple quantile estimation with weighted samples
  37. /**
  38. @brief Multiple quantile estimation with the extended \f$P^2\f$ algorithm for weighted samples
  39. This version of the extended \f$P^2\f$ algorithm extends the extended \f$P^2\f$ algorithm to
  40. support weighted samples. The extended \f$P^2\f$ algorithm dynamically estimates several
  41. quantiles without storing samples. Assume that \f$m\f$ quantiles
  42. \f$\xi_{p_1}, \ldots, \xi_{p_m}\f$ are to be estimated. Instead of storing the whole sample
  43. cumulative distribution, the algorithm maintains only \f$m+2\f$ principal markers and
  44. \f$m+1\f$ middle markers, whose positions are updated with each sample and whose heights
  45. are adjusted (if necessary) using a piecewise-parablic formula. The heights of the principal
  46. markers are the current estimates of the quantiles and are returned as an iterator range.
  47. For further details, see
  48. K. E. E. Raatikainen, Simultaneous estimation of several quantiles, Simulation, Volume 49,
  49. Number 4 (October), 1986, p. 159-164.
  50. The extended \f$ P^2 \f$ algorithm generalizes the \f$ P^2 \f$ algorithm of
  51. R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and
  52. histograms without storing observations, Communications of the ACM,
  53. Volume 28 (October), Number 10, 1985, p. 1076-1085.
  54. @param extended_p_square_probabilities A vector of quantile probabilities.
  55. */
  56. template<typename Sample, typename Weight>
  57. struct weighted_extended_p_square_impl
  58. : accumulator_base
  59. {
  60. typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;
  61. typedef typename numeric::functional::fdiv<weighted_sample, std::size_t>::result_type float_type;
  62. typedef std::vector<float_type> array_type;
  63. // for boost::result_of
  64. typedef iterator_range<
  65. detail::lvalue_index_iterator<
  66. permutation_iterator<
  67. typename array_type::const_iterator
  68. , detail::times2_iterator
  69. >
  70. >
  71. > result_type;
  72. template<typename Args>
  73. weighted_extended_p_square_impl(Args const &args)
  74. : probabilities(
  75. boost::begin(args[extended_p_square_probabilities])
  76. , boost::end(args[extended_p_square_probabilities])
  77. )
  78. , heights(2 * probabilities.size() + 3)
  79. , actual_positions(heights.size())
  80. , desired_positions(heights.size())
  81. {
  82. }
  83. template<typename Args>
  84. void operator ()(Args const &args)
  85. {
  86. std::size_t cnt = count(args);
  87. std::size_t sample_cell = 1; // k
  88. std::size_t num_quantiles = this->probabilities.size();
  89. // m+2 principal markers and m+1 middle markers
  90. std::size_t num_markers = 2 * num_quantiles + 3;
  91. // first accumulate num_markers samples
  92. if(cnt <= num_markers)
  93. {
  94. this->heights[cnt - 1] = args[sample];
  95. this->actual_positions[cnt - 1] = args[weight];
  96. // complete the initialization of heights (and actual_positions) by sorting
  97. if(cnt == num_markers)
  98. {
  99. // TODO: we need to sort the initial samples (in heights) in ascending order and
  100. // sort their weights (in actual_positions) the same way. The following lines do
  101. // it, but there must be a better and more efficient way of doing this.
  102. typename array_type::iterator it_begin, it_end, it_min;
  103. it_begin = this->heights.begin();
  104. it_end = this->heights.end();
  105. std::size_t pos = 0;
  106. while (it_begin != it_end)
  107. {
  108. it_min = std::min_element(it_begin, it_end);
  109. std::size_t d = std::distance(it_begin, it_min);
  110. std::swap(*it_begin, *it_min);
  111. std::swap(this->actual_positions[pos], this->actual_positions[pos + d]);
  112. ++it_begin;
  113. ++pos;
  114. }
  115. // calculate correct initial actual positions
  116. for (std::size_t i = 1; i < num_markers; ++i)
  117. {
  118. actual_positions[i] += actual_positions[i - 1];
  119. }
  120. }
  121. }
  122. else
  123. {
  124. if(args[sample] < this->heights[0])
  125. {
  126. this->heights[0] = args[sample];
  127. this->actual_positions[0] = args[weight];
  128. sample_cell = 1;
  129. }
  130. else if(args[sample] >= this->heights[num_markers - 1])
  131. {
  132. this->heights[num_markers - 1] = args[sample];
  133. sample_cell = num_markers - 1;
  134. }
  135. else
  136. {
  137. // find cell k = sample_cell such that heights[k-1] <= sample < heights[k]
  138. typedef typename array_type::iterator iterator;
  139. iterator it = std::upper_bound(
  140. this->heights.begin()
  141. , this->heights.end()
  142. , args[sample]
  143. );
  144. sample_cell = std::distance(this->heights.begin(), it);
  145. }
  146. // update actual position of all markers above sample_cell
  147. for(std::size_t i = sample_cell; i < num_markers; ++i)
  148. {
  149. this->actual_positions[i] += args[weight];
  150. }
  151. // compute desired positions
  152. {
  153. this->desired_positions[0] = this->actual_positions[0];
  154. this->desired_positions[num_markers - 1] = sum_of_weights(args);
  155. this->desired_positions[1] = (sum_of_weights(args) - this->actual_positions[0]) * probabilities[0]
  156. / 2. + this->actual_positions[0];
  157. this->desired_positions[num_markers - 2] = (sum_of_weights(args) - this->actual_positions[0])
  158. * (probabilities[num_quantiles - 1] + 1.)
  159. / 2. + this->actual_positions[0];
  160. for (std::size_t i = 0; i < num_quantiles; ++i)
  161. {
  162. this->desired_positions[2 * i + 2] = (sum_of_weights(args) - this->actual_positions[0])
  163. * probabilities[i] + this->actual_positions[0];
  164. }
  165. for (std::size_t i = 1; i < num_quantiles; ++i)
  166. {
  167. this->desired_positions[2 * i + 1] = (sum_of_weights(args) - this->actual_positions[0])
  168. * (probabilities[i - 1] + probabilities[i])
  169. / 2. + this->actual_positions[0];
  170. }
  171. }
  172. // adjust heights and actual_positions of markers 1 to num_markers - 2 if necessary
  173. for (std::size_t i = 1; i <= num_markers - 2; ++i)
  174. {
  175. // offset to desired position
  176. float_type d = this->desired_positions[i] - this->actual_positions[i];
  177. // offset to next position
  178. float_type dp = this->actual_positions[i + 1] - this->actual_positions[i];
  179. // offset to previous position
  180. float_type dm = this->actual_positions[i - 1] - this->actual_positions[i];
  181. // height ds
  182. float_type hp = (this->heights[i + 1] - this->heights[i]) / dp;
  183. float_type hm = (this->heights[i - 1] - this->heights[i]) / dm;
  184. if((d >= 1 && dp > 1) || (d <= -1 && dm < -1))
  185. {
  186. short sign_d = static_cast<short>(d / std::abs(d));
  187. float_type h = this->heights[i] + sign_d / (dp - dm) * ((sign_d - dm)*hp + (dp - sign_d) * hm);
  188. // try adjusting heights[i] using p-squared formula
  189. if(this->heights[i - 1] < h && h < this->heights[i + 1])
  190. {
  191. this->heights[i] = h;
  192. }
  193. else
  194. {
  195. // use linear formula
  196. if(d > 0)
  197. {
  198. this->heights[i] += hp;
  199. }
  200. if(d < 0)
  201. {
  202. this->heights[i] -= hm;
  203. }
  204. }
  205. this->actual_positions[i] += sign_d;
  206. }
  207. }
  208. }
  209. }
  210. result_type result(dont_care) const
  211. {
  212. // for i in [1,probabilities.size()], return heights[i * 2]
  213. detail::times2_iterator idx_begin = detail::make_times2_iterator(1);
  214. detail::times2_iterator idx_end = detail::make_times2_iterator(this->probabilities.size() + 1);
  215. return result_type(
  216. make_permutation_iterator(this->heights.begin(), idx_begin)
  217. , make_permutation_iterator(this->heights.begin(), idx_end)
  218. );
  219. }
  220. // make this accumulator serializeable
  221. // TODO: do we need to split to load/save and verify that the parameters did not change?
  222. template<class Archive>
  223. void serialize(Archive & ar, const unsigned int file_version)
  224. {
  225. ar & probabilities;
  226. ar & heights;
  227. ar & actual_positions;
  228. ar & desired_positions;
  229. }
  230. private:
  231. array_type probabilities; // the quantile probabilities
  232. array_type heights; // q_i
  233. array_type actual_positions; // n_i
  234. array_type desired_positions; // d_i
  235. };
  236. } // namespace impl
  237. ///////////////////////////////////////////////////////////////////////////////
  238. // tag::weighted_extended_p_square
  239. //
  240. namespace tag
  241. {
  242. struct weighted_extended_p_square
  243. : depends_on<count, sum_of_weights>
  244. , extended_p_square_probabilities
  245. {
  246. typedef accumulators::impl::weighted_extended_p_square_impl<mpl::_1, mpl::_2> impl;
  247. };
  248. }
  249. ///////////////////////////////////////////////////////////////////////////////
  250. // extract::weighted_extended_p_square
  251. //
  252. namespace extract
  253. {
  254. extractor<tag::weighted_extended_p_square> const weighted_extended_p_square = {};
  255. BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_extended_p_square)
  256. }
  257. using extract::weighted_extended_p_square;
  258. }} // namespace boost::accumulators
  259. #endif