weighted_p_square_cumul_dist.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. ///////////////////////////////////////////////////////////////////////////////
  2. // weighted_p_square_cumul_dist.hpp
  3. //
  4. // Copyright 2006 Daniel Egloff, Olivier Gygi. 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_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006
  8. #define BOOST_ACCUMULATORS_STATISTICS_WEIGHTED_P_SQUARE_CUMUL_DIST_HPP_DE_01_01_2006
  9. #include <vector>
  10. #include <functional>
  11. #include <boost/parameter/keyword.hpp>
  12. #include <boost/mpl/placeholders.hpp>
  13. #include <boost/range.hpp>
  14. #include <boost/accumulators/framework/accumulator_base.hpp>
  15. #include <boost/accumulators/framework/extractor.hpp>
  16. #include <boost/accumulators/numeric/functional.hpp>
  17. #include <boost/accumulators/framework/parameters/sample.hpp>
  18. #include <boost/accumulators/statistics_fwd.hpp>
  19. #include <boost/accumulators/statistics/count.hpp>
  20. #include <boost/accumulators/statistics/sum.hpp>
  21. #include <boost/accumulators/statistics/p_square_cumul_dist.hpp> // for named parameter p_square_cumulative_distribution_num_cells
  22. namespace boost { namespace accumulators
  23. {
  24. namespace impl
  25. {
  26. ///////////////////////////////////////////////////////////////////////////////
  27. // weighted_p_square_cumulative_distribution_impl
  28. // cumulative distribution calculation (as histogram)
  29. /**
  30. @brief Histogram calculation of the cumulative distribution with the \f$P^2\f$ algorithm for weighted samples
  31. A histogram of the sample cumulative distribution is computed dynamically without storing samples
  32. based on the \f$ P^2 \f$ algorithm for weighted samples. The returned histogram has a specifiable
  33. amount (num_cells) equiprobable (and not equal-sized) cells.
  34. Note that applying importance sampling results in regions to be more and other regions to be less
  35. accurately estimated than without importance sampling, i.e., with unweighted samples.
  36. For further details, see
  37. R. Jain and I. Chlamtac, The P^2 algorithm for dynamic calculation of quantiles and
  38. histograms without storing observations, Communications of the ACM,
  39. Volume 28 (October), Number 10, 1985, p. 1076-1085.
  40. @param p_square_cumulative_distribution_num_cells
  41. */
  42. template<typename Sample, typename Weight>
  43. struct weighted_p_square_cumulative_distribution_impl
  44. : accumulator_base
  45. {
  46. typedef typename numeric::functional::multiplies<Sample, Weight>::result_type weighted_sample;
  47. typedef typename numeric::functional::fdiv<weighted_sample, std::size_t>::result_type float_type;
  48. typedef std::vector<std::pair<float_type, float_type> > histogram_type;
  49. typedef std::vector<float_type> array_type;
  50. // for boost::result_of
  51. typedef iterator_range<typename histogram_type::iterator> result_type;
  52. template<typename Args>
  53. weighted_p_square_cumulative_distribution_impl(Args const &args)
  54. : num_cells(args[p_square_cumulative_distribution_num_cells])
  55. , heights(num_cells + 1)
  56. , actual_positions(num_cells + 1)
  57. , desired_positions(num_cells + 1)
  58. , histogram(num_cells + 1)
  59. , is_dirty(true)
  60. {
  61. }
  62. template<typename Args>
  63. void operator ()(Args const &args)
  64. {
  65. this->is_dirty = true;
  66. std::size_t cnt = count(args);
  67. std::size_t sample_cell = 1; // k
  68. std::size_t b = this->num_cells;
  69. // accumulate num_cells + 1 first samples
  70. if (cnt <= b + 1)
  71. {
  72. this->heights[cnt - 1] = args[sample];
  73. this->actual_positions[cnt - 1] = args[weight];
  74. // complete the initialization of heights by sorting
  75. if (cnt == b + 1)
  76. {
  77. //std::sort(this->heights.begin(), this->heights.end());
  78. // TODO: we need to sort the initial samples (in heights) in ascending order and
  79. // sort their weights (in actual_positions) the same way. The following lines do
  80. // it, but there must be a better and more efficient way of doing this.
  81. typename array_type::iterator it_begin, it_end, it_min;
  82. it_begin = this->heights.begin();
  83. it_end = this->heights.end();
  84. std::size_t pos = 0;
  85. while (it_begin != it_end)
  86. {
  87. it_min = std::min_element(it_begin, it_end);
  88. std::size_t d = std::distance(it_begin, it_min);
  89. std::swap(*it_begin, *it_min);
  90. std::swap(this->actual_positions[pos], this->actual_positions[pos + d]);
  91. ++it_begin;
  92. ++pos;
  93. }
  94. // calculate correct initial actual positions
  95. for (std::size_t i = 1; i < b; ++i)
  96. {
  97. this->actual_positions[i] += this->actual_positions[i - 1];
  98. }
  99. }
  100. }
  101. else
  102. {
  103. // find cell k such that heights[k-1] <= args[sample] < heights[k] and adjust extreme values
  104. if (args[sample] < this->heights[0])
  105. {
  106. this->heights[0] = args[sample];
  107. this->actual_positions[0] = args[weight];
  108. sample_cell = 1;
  109. }
  110. else if (this->heights[b] <= args[sample])
  111. {
  112. this->heights[b] = args[sample];
  113. sample_cell = b;
  114. }
  115. else
  116. {
  117. typename array_type::iterator it;
  118. it = std::upper_bound(
  119. this->heights.begin()
  120. , this->heights.end()
  121. , args[sample]
  122. );
  123. sample_cell = std::distance(this->heights.begin(), it);
  124. }
  125. // increment positions of markers above sample_cell
  126. for (std::size_t i = sample_cell; i < b + 1; ++i)
  127. {
  128. this->actual_positions[i] += args[weight];
  129. }
  130. // determine desired marker positions
  131. for (std::size_t i = 1; i < b + 1; ++i)
  132. {
  133. this->desired_positions[i] = this->actual_positions[0]
  134. + numeric::fdiv((i-1) * (sum_of_weights(args) - this->actual_positions[0]), b);
  135. }
  136. // adjust heights of markers 2 to num_cells if necessary
  137. for (std::size_t i = 1; i < b; ++i)
  138. {
  139. // offset to desire position
  140. float_type d = this->desired_positions[i] - this->actual_positions[i];
  141. // offset to next position
  142. float_type dp = this->actual_positions[i + 1] - this->actual_positions[i];
  143. // offset to previous position
  144. float_type dm = this->actual_positions[i - 1] - this->actual_positions[i];
  145. // height ds
  146. float_type hp = (this->heights[i + 1] - this->heights[i]) / dp;
  147. float_type hm = (this->heights[i - 1] - this->heights[i]) / dm;
  148. if ( ( d >= 1. && dp > 1. ) || ( d <= -1. && dm < -1. ) )
  149. {
  150. short sign_d = static_cast<short>(d / std::abs(d));
  151. // try adjusting heights[i] using p-squared formula
  152. float_type h = this->heights[i] + sign_d / (dp - dm) * ( (sign_d - dm) * hp + (dp - sign_d) * hm );
  153. if ( this->heights[i - 1] < h && h < this->heights[i + 1] )
  154. {
  155. this->heights[i] = h;
  156. }
  157. else
  158. {
  159. // use linear formula
  160. if (d>0)
  161. {
  162. this->heights[i] += hp;
  163. }
  164. if (d<0)
  165. {
  166. this->heights[i] -= hm;
  167. }
  168. }
  169. this->actual_positions[i] += sign_d;
  170. }
  171. }
  172. }
  173. }
  174. template<typename Args>
  175. result_type result(Args const &args) const
  176. {
  177. if (this->is_dirty)
  178. {
  179. this->is_dirty = false;
  180. // creates a vector of std::pair where each pair i holds
  181. // the values heights[i] (x-axis of histogram) and
  182. // actual_positions[i] / sum_of_weights (y-axis of histogram)
  183. for (std::size_t i = 0; i < this->histogram.size(); ++i)
  184. {
  185. this->histogram[i] = std::make_pair(this->heights[i], numeric::fdiv(this->actual_positions[i], sum_of_weights(args)));
  186. }
  187. }
  188. return make_iterator_range(this->histogram);
  189. }
  190. // make this accumulator serializeable
  191. // TODO split to save/load and check on parameters provided in ctor
  192. template<class Archive>
  193. void serialize(Archive & ar, const unsigned int file_version)
  194. {
  195. ar & num_cells;
  196. ar & heights;
  197. ar & actual_positions;
  198. ar & desired_positions;
  199. ar & histogram;
  200. ar & is_dirty;
  201. }
  202. private:
  203. std::size_t num_cells; // number of cells b
  204. array_type heights; // q_i
  205. array_type actual_positions; // n_i
  206. array_type desired_positions; // n'_i
  207. mutable histogram_type histogram; // histogram
  208. mutable bool is_dirty;
  209. };
  210. } // namespace detail
  211. ///////////////////////////////////////////////////////////////////////////////
  212. // tag::weighted_p_square_cumulative_distribution
  213. //
  214. namespace tag
  215. {
  216. struct weighted_p_square_cumulative_distribution
  217. : depends_on<count, sum_of_weights>
  218. , p_square_cumulative_distribution_num_cells
  219. {
  220. typedef accumulators::impl::weighted_p_square_cumulative_distribution_impl<mpl::_1, mpl::_2> impl;
  221. };
  222. }
  223. ///////////////////////////////////////////////////////////////////////////////
  224. // extract::weighted_p_square_cumulative_distribution
  225. //
  226. namespace extract
  227. {
  228. extractor<tag::weighted_p_square_cumulative_distribution> const weighted_p_square_cumulative_distribution = {};
  229. BOOST_ACCUMULATORS_IGNORE_GLOBAL(weighted_p_square_cumulative_distribution)
  230. }
  231. using extract::weighted_p_square_cumulative_distribution;
  232. }} // namespace boost::accumulators
  233. #endif