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