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