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 
15 #ifndef ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_
16 #define ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_
17 
18 #include <cassert>
19 #include <cmath>
20 #include <istream>
21 #include <limits>
22 #include <numeric>
23 #include <type_traits>
24 #include <utility>
25 #include <vector>
26 
27 #include "absl/random/bernoulli_distribution.h"
28 #include "absl/random/internal/iostream_state_saver.h"
29 #include "absl/random/uniform_int_distribution.h"
30 
31 namespace absl {
32 ABSL_NAMESPACE_BEGIN
33 
34 // absl::discrete_distribution
35 //
36 // A discrete distribution produces random integers i, where 0 <= i < n
37 // distributed according to the discrete probability function:
38 //
39 //     P(i|p0,...,pn−1)=pi
40 //
41 // This class is an implementation of discrete_distribution (see
42 // [rand.dist.samp.discrete]).
43 //
44 // The algorithm used is Walker's Aliasing algorithm, described in Knuth, Vol 2.
45 // absl::discrete_distribution takes O(N) time to precompute the probabilities
46 // (where N is the number of possible outcomes in the distribution) at
47 // construction, and then takes O(1) time for each variate generation.  Many
48 // other implementations also take O(N) time to construct an ordered sequence of
49 // partial sums, plus O(log N) time per variate to binary search.
50 //
51 template <typename IntType = int>
52 class discrete_distribution {
53  public:
54   using result_type = IntType;
55 
56   class param_type {
57    public:
58     using distribution_type = discrete_distribution;
59 
param_type()60     param_type() { init(); }
61 
62     template <typename InputIterator>
param_type(InputIterator begin,InputIterator end)63     explicit param_type(InputIterator begin, InputIterator end)
64         : p_(begin, end) {
65       init();
66     }
67 
param_type(std::initializer_list<double> weights)68     explicit param_type(std::initializer_list<double> weights) : p_(weights) {
69       init();
70     }
71 
72     template <class UnaryOperation>
param_type(size_t nw,double xmin,double xmax,UnaryOperation fw)73     explicit param_type(size_t nw, double xmin, double xmax,
74                         UnaryOperation fw) {
75       if (nw > 0) {
76         p_.reserve(nw);
77         double delta = (xmax - xmin) / static_cast<double>(nw);
78         assert(delta > 0);
79         double t = delta * 0.5;
80         for (size_t i = 0; i < nw; ++i) {
81           p_.push_back(fw(xmin + i * delta + t));
82         }
83       }
84       init();
85     }
86 
probabilities()87     const std::vector<double>& probabilities() const { return p_; }
n()88     size_t n() const { return p_.size() - 1; }
89 
90     friend bool operator==(const param_type& a, const param_type& b) {
91       return a.probabilities() == b.probabilities();
92     }
93 
94     friend bool operator!=(const param_type& a, const param_type& b) {
95       return !(a == b);
96     }
97 
98    private:
99     friend class discrete_distribution;
100 
101     void init();
102 
103     std::vector<double> p_;                     // normalized probabilities
104     std::vector<std::pair<double, size_t>> q_;  // (acceptance, alternate) pairs
105 
106     static_assert(std::is_integral<result_type>::value,
107                   "Class-template absl::discrete_distribution<> must be "
108                   "parameterized using an integral type.");
109   };
110 
discrete_distribution()111   discrete_distribution() : param_() {}
112 
discrete_distribution(const param_type & p)113   explicit discrete_distribution(const param_type& p) : param_(p) {}
114 
115   template <typename InputIterator>
discrete_distribution(InputIterator begin,InputIterator end)116   explicit discrete_distribution(InputIterator begin, InputIterator end)
117       : param_(begin, end) {}
118 
discrete_distribution(std::initializer_list<double> weights)119   explicit discrete_distribution(std::initializer_list<double> weights)
120       : param_(weights) {}
121 
122   template <class UnaryOperation>
discrete_distribution(size_t nw,double xmin,double xmax,UnaryOperation fw)123   explicit discrete_distribution(size_t nw, double xmin, double xmax,
124                                  UnaryOperation fw)
125       : param_(nw, xmin, xmax, std::move(fw)) {}
126 
reset()127   void reset() {}
128 
129   // generating functions
130   template <typename URBG>
operator()131   result_type operator()(URBG& g) {  // NOLINT(runtime/references)
132     return (*this)(g, param_);
133   }
134 
135   template <typename URBG>
136   result_type operator()(URBG& g,  // NOLINT(runtime/references)
137                          const param_type& p);
138 
param()139   const param_type& param() const { return param_; }
param(const param_type & p)140   void param(const param_type& p) { param_ = p; }
141 
result_type(min)142   result_type(min)() const { return 0; }
result_type(max)143   result_type(max)() const {
144     return static_cast<result_type>(param_.n());
145   }  // inclusive
146 
147   // NOTE [rand.dist.sample.discrete] returns a std::vector<double> not a
148   // const std::vector<double>&.
probabilities()149   const std::vector<double>& probabilities() const {
150     return param_.probabilities();
151   }
152 
153   friend bool operator==(const discrete_distribution& a,
154                          const discrete_distribution& b) {
155     return a.param_ == b.param_;
156   }
157   friend bool operator!=(const discrete_distribution& a,
158                          const discrete_distribution& b) {
159     return a.param_ != b.param_;
160   }
161 
162  private:
163   param_type param_;
164 };
165 
166 // --------------------------------------------------------------------------
167 // Implementation details only below
168 // --------------------------------------------------------------------------
169 
170 namespace random_internal {
171 
172 // Using the vector `*probabilities`, whose values are the weights or
173 // probabilities of an element being selected, constructs the proportional
174 // probabilities used by the discrete distribution.  `*probabilities` will be
175 // scaled, if necessary, so that its entries sum to a value sufficiently close
176 // to 1.0.
177 std::vector<std::pair<double, size_t>> InitDiscreteDistribution(
178     std::vector<double>* probabilities);
179 
180 }  // namespace random_internal
181 
182 template <typename IntType>
init()183 void discrete_distribution<IntType>::param_type::init() {
184   if (p_.empty()) {
185     p_.push_back(1.0);
186     q_.emplace_back(1.0, 0);
187   } else {
188     assert(n() <= (std::numeric_limits<IntType>::max)());
189     q_ = random_internal::InitDiscreteDistribution(&p_);
190   }
191 }
192 
193 template <typename IntType>
194 template <typename URBG>
195 typename discrete_distribution<IntType>::result_type
operator()196 discrete_distribution<IntType>::operator()(
197     URBG& g,  // NOLINT(runtime/references)
198     const param_type& p) {
199   const auto idx = absl::uniform_int_distribution<result_type>(0, p.n())(g);
200   const auto& q = p.q_[idx];
201   const bool selected = absl::bernoulli_distribution(q.first)(g);
202   return selected ? idx : static_cast<result_type>(q.second);
203 }
204 
205 template <typename CharT, typename Traits, typename IntType>
206 std::basic_ostream<CharT, Traits>& operator<<(
207     std::basic_ostream<CharT, Traits>& os,  // NOLINT(runtime/references)
208     const discrete_distribution<IntType>& x) {
209   auto saver = random_internal::make_ostream_state_saver(os);
210   const auto& probabilities = x.param().probabilities();
211   os << probabilities.size();
212 
213   os.precision(random_internal::stream_precision_helper<double>::kPrecision);
214   for (const auto& p : probabilities) {
215     os << os.fill() << p;
216   }
217   return os;
218 }
219 
220 template <typename CharT, typename Traits, typename IntType>
221 std::basic_istream<CharT, Traits>& operator>>(
222     std::basic_istream<CharT, Traits>& is,  // NOLINT(runtime/references)
223     discrete_distribution<IntType>& x) {    // NOLINT(runtime/references)
224   using param_type = typename discrete_distribution<IntType>::param_type;
225   auto saver = random_internal::make_istream_state_saver(is);
226 
227   size_t n;
228   std::vector<double> p;
229 
230   is >> n;
231   if (is.fail()) return is;
232   if (n > 0) {
233     p.reserve(n);
234     for (IntType i = 0; i < n && !is.fail(); ++i) {
235       auto tmp = random_internal::read_floating_point<double>(is);
236       if (is.fail()) return is;
237       p.push_back(tmp);
238     }
239   }
240   x.param(param_type(p.begin(), p.end()));
241   return is;
242 }
243 
244 ABSL_NAMESPACE_END
245 }  // namespace absl
246 
247 #endif  // ABSL_RANDOM_DISCRETE_DISTRIBUTION_H_
248