zipf_distribution.h 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. // Copyright 2017 The Abseil Authors.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // https://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #ifndef Y_ABSL_RANDOM_ZIPF_DISTRIBUTION_H_
  15. #define Y_ABSL_RANDOM_ZIPF_DISTRIBUTION_H_
  16. #include <cassert>
  17. #include <cmath>
  18. #include <istream>
  19. #include <limits>
  20. #include <ostream>
  21. #include <type_traits>
  22. #include "y_absl/random/internal/iostream_state_saver.h"
  23. #include "y_absl/random/internal/traits.h"
  24. #include "y_absl/random/uniform_real_distribution.h"
  25. namespace y_absl {
  26. Y_ABSL_NAMESPACE_BEGIN
  27. // y_absl::zipf_distribution produces random integer-values in the range [0, k],
  28. // distributed according to the unnormalized discrete probability function:
  29. //
  30. // P(x) = (v + x) ^ -q
  31. //
  32. // The parameter `v` must be greater than 0 and the parameter `q` must be
  33. // greater than 1. If either of these parameters take invalid values then the
  34. // behavior is undefined.
  35. //
  36. // IntType is the result_type generated by the generator. It must be of integral
  37. // type; a static_assert ensures this is the case.
  38. //
  39. // The implementation is based on W.Hormann, G.Derflinger:
  40. //
  41. // "Rejection-Inversion to Generate Variates from Monotone Discrete
  42. // Distributions"
  43. //
  44. // http://eeyore.wu-wien.ac.at/papers/96-04-04.wh-der.ps.gz
  45. //
  46. template <typename IntType = int>
  47. class zipf_distribution {
  48. public:
  49. using result_type = IntType;
  50. class param_type {
  51. public:
  52. using distribution_type = zipf_distribution;
  53. // Preconditions: k > 0, v > 0, q > 1
  54. // The precondidtions are validated when NDEBUG is not defined via
  55. // a pair of assert() directives.
  56. // If NDEBUG is defined and either or both of these parameters take invalid
  57. // values, the behavior of the class is undefined.
  58. explicit param_type(result_type k = (std::numeric_limits<IntType>::max)(),
  59. double q = 2.0, double v = 1.0);
  60. result_type k() const { return k_; }
  61. double q() const { return q_; }
  62. double v() const { return v_; }
  63. friend bool operator==(const param_type& a, const param_type& b) {
  64. return a.k_ == b.k_ && a.q_ == b.q_ && a.v_ == b.v_;
  65. }
  66. friend bool operator!=(const param_type& a, const param_type& b) {
  67. return !(a == b);
  68. }
  69. private:
  70. friend class zipf_distribution;
  71. inline double h(double x) const;
  72. inline double hinv(double x) const;
  73. inline double compute_s() const;
  74. inline double pow_negative_q(double x) const;
  75. // Parameters here are exactly the same as the parameters of Algorithm ZRI
  76. // in the paper.
  77. IntType k_;
  78. double q_;
  79. double v_;
  80. double one_minus_q_; // 1-q
  81. double s_;
  82. double one_minus_q_inv_; // 1 / 1-q
  83. double hxm_; // h(k + 0.5)
  84. double hx0_minus_hxm_; // h(x0) - h(k + 0.5)
  85. static_assert(random_internal::IsIntegral<IntType>::value,
  86. "Class-template y_absl::zipf_distribution<> must be "
  87. "parameterized using an integral type.");
  88. };
  89. zipf_distribution()
  90. : zipf_distribution((std::numeric_limits<IntType>::max)()) {}
  91. explicit zipf_distribution(result_type k, double q = 2.0, double v = 1.0)
  92. : param_(k, q, v) {}
  93. explicit zipf_distribution(const param_type& p) : param_(p) {}
  94. void reset() {}
  95. template <typename URBG>
  96. result_type operator()(URBG& g) { // NOLINT(runtime/references)
  97. return (*this)(g, param_);
  98. }
  99. template <typename URBG>
  100. result_type operator()(URBG& g, // NOLINT(runtime/references)
  101. const param_type& p);
  102. result_type k() const { return param_.k(); }
  103. double q() const { return param_.q(); }
  104. double v() const { return param_.v(); }
  105. param_type param() const { return param_; }
  106. void param(const param_type& p) { param_ = p; }
  107. result_type(min)() const { return 0; }
  108. result_type(max)() const { return k(); }
  109. friend bool operator==(const zipf_distribution& a,
  110. const zipf_distribution& b) {
  111. return a.param_ == b.param_;
  112. }
  113. friend bool operator!=(const zipf_distribution& a,
  114. const zipf_distribution& b) {
  115. return a.param_ != b.param_;
  116. }
  117. private:
  118. param_type param_;
  119. };
  120. // --------------------------------------------------------------------------
  121. // Implementation details follow
  122. // --------------------------------------------------------------------------
  123. template <typename IntType>
  124. zipf_distribution<IntType>::param_type::param_type(
  125. typename zipf_distribution<IntType>::result_type k, double q, double v)
  126. : k_(k), q_(q), v_(v), one_minus_q_(1 - q) {
  127. assert(q > 1);
  128. assert(v > 0);
  129. assert(k > 0);
  130. one_minus_q_inv_ = 1 / one_minus_q_;
  131. // Setup for the ZRI algorithm (pg 17 of the paper).
  132. // Compute: h(i max) => h(k + 0.5)
  133. constexpr double kMax = 18446744073709549568.0;
  134. double kd = static_cast<double>(k);
  135. // TODO(y_absl-team): Determine if this check is needed, and if so, add a test
  136. // that fails for k > kMax
  137. if (kd > kMax) {
  138. // Ensure that our maximum value is capped to a value which will
  139. // round-trip back through double.
  140. kd = kMax;
  141. }
  142. hxm_ = h(kd + 0.5);
  143. // Compute: h(0)
  144. const bool use_precomputed = (v == 1.0 && q == 2.0);
  145. const double h0x5 = use_precomputed ? (-1.0 / 1.5) // exp(-log(1.5))
  146. : h(0.5);
  147. const double elogv_q = (v_ == 1.0) ? 1 : pow_negative_q(v_);
  148. // h(0) = h(0.5) - exp(log(v) * -q)
  149. hx0_minus_hxm_ = (h0x5 - elogv_q) - hxm_;
  150. // And s
  151. s_ = use_precomputed ? 0.46153846153846123 : compute_s();
  152. }
  153. template <typename IntType>
  154. double zipf_distribution<IntType>::param_type::h(double x) const {
  155. // std::exp(one_minus_q_ * std::log(v_ + x)) * one_minus_q_inv_;
  156. x += v_;
  157. return (one_minus_q_ == -1.0)
  158. ? (-1.0 / x) // -exp(-log(x))
  159. : (std::exp(std::log(x) * one_minus_q_) * one_minus_q_inv_);
  160. }
  161. template <typename IntType>
  162. double zipf_distribution<IntType>::param_type::hinv(double x) const {
  163. // std::exp(one_minus_q_inv_ * std::log(one_minus_q_ * x)) - v_;
  164. return -v_ + ((one_minus_q_ == -1.0)
  165. ? (-1.0 / x) // exp(-log(-x))
  166. : std::exp(one_minus_q_inv_ * std::log(one_minus_q_ * x)));
  167. }
  168. template <typename IntType>
  169. double zipf_distribution<IntType>::param_type::compute_s() const {
  170. // 1 - hinv(h(1.5) - std::exp(std::log(v_ + 1) * -q_));
  171. return 1.0 - hinv(h(1.5) - pow_negative_q(v_ + 1.0));
  172. }
  173. template <typename IntType>
  174. double zipf_distribution<IntType>::param_type::pow_negative_q(double x) const {
  175. // std::exp(std::log(x) * -q_);
  176. return q_ == 2.0 ? (1.0 / (x * x)) : std::exp(std::log(x) * -q_);
  177. }
  178. template <typename IntType>
  179. template <typename URBG>
  180. typename zipf_distribution<IntType>::result_type
  181. zipf_distribution<IntType>::operator()(
  182. URBG& g, const param_type& p) { // NOLINT(runtime/references)
  183. y_absl::uniform_real_distribution<double> uniform_double;
  184. double k;
  185. for (;;) {
  186. const double v = uniform_double(g);
  187. const double u = p.hxm_ + v * p.hx0_minus_hxm_;
  188. const double x = p.hinv(u);
  189. k = rint(x); // std::floor(x + 0.5);
  190. if (k > static_cast<double>(p.k())) continue; // reject k > max_k
  191. if (k - x <= p.s_) break;
  192. const double h = p.h(k + 0.5);
  193. const double r = p.pow_negative_q(p.v_ + k);
  194. if (u >= h - r) break;
  195. }
  196. IntType ki = static_cast<IntType>(k);
  197. assert(ki <= p.k_);
  198. return ki;
  199. }
  200. template <typename CharT, typename Traits, typename IntType>
  201. std::basic_ostream<CharT, Traits>& operator<<(
  202. std::basic_ostream<CharT, Traits>& os, // NOLINT(runtime/references)
  203. const zipf_distribution<IntType>& x) {
  204. using stream_type =
  205. typename random_internal::stream_format_type<IntType>::type;
  206. auto saver = random_internal::make_ostream_state_saver(os);
  207. os.precision(random_internal::stream_precision_helper<double>::kPrecision);
  208. os << static_cast<stream_type>(x.k()) << os.fill() << x.q() << os.fill()
  209. << x.v();
  210. return os;
  211. }
  212. template <typename CharT, typename Traits, typename IntType>
  213. std::basic_istream<CharT, Traits>& operator>>(
  214. std::basic_istream<CharT, Traits>& is, // NOLINT(runtime/references)
  215. zipf_distribution<IntType>& x) { // NOLINT(runtime/references)
  216. using result_type = typename zipf_distribution<IntType>::result_type;
  217. using param_type = typename zipf_distribution<IntType>::param_type;
  218. using stream_type =
  219. typename random_internal::stream_format_type<IntType>::type;
  220. stream_type k;
  221. double q;
  222. double v;
  223. auto saver = random_internal::make_istream_state_saver(is);
  224. is >> k >> q >> v;
  225. if (!is.fail()) {
  226. x.param(param_type(static_cast<result_type>(k), q, v));
  227. }
  228. return is;
  229. }
  230. Y_ABSL_NAMESPACE_END
  231. } // namespace y_absl
  232. #endif // Y_ABSL_RANDOM_ZIPF_DISTRIBUTION_H_