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_POISSON_DISTRIBUTION_H_
16 #define ABSL_RANDOM_POISSON_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/fast_uniform_bits.h"
26 #include "absl/random/internal/fastmath.h"
27 #include "absl/random/internal/generate_real.h"
28 #include "absl/random/internal/iostream_state_saver.h"
29 
30 namespace absl {
31 ABSL_NAMESPACE_BEGIN
32 
33 // absl::poisson_distribution:
34 // Generates discrete variates conforming to a Poisson distribution.
35 //   p(n) = (mean^n / n!) exp(-mean)
36 //
37 // Depending on the parameter, the distribution selects one of the following
38 // algorithms:
39 // * The standard algorithm, attributed to Knuth, extended using a split method
40 // for larger values
41 // * The "Ratio of Uniforms as a convenient method for sampling from classical
42 // discrete distributions", Stadlober, 1989.
43 // http://www.sciencedirect.com/science/article/pii/0377042790903495
44 //
45 // NOTE: param_type.mean() is a double, which permits values larger than
46 // poisson_distribution<IntType>::max(), however this should be avoided and
47 // the distribution results are limited to the max() value.
48 //
49 // The goals of this implementation are to provide good performance while still
50 // beig thread-safe: This limits the implementation to not using lgamma provided
51 // by <math.h>.
52 //
53 template <typename IntType = int>
54 class poisson_distribution {
55  public:
56   using result_type = IntType;
57 
58   class param_type {
59    public:
60     using distribution_type = poisson_distribution;
61     explicit param_type(double mean = 1.0);
62 
mean()63     double mean() const { return mean_; }
64 
65     friend bool operator==(const param_type& a, const param_type& b) {
66       return a.mean_ == b.mean_;
67     }
68 
69     friend bool operator!=(const param_type& a, const param_type& b) {
70       return !(a == b);
71     }
72 
73    private:
74     friend class poisson_distribution;
75 
76     double mean_;
77     double emu_;  // e ^ -mean_
78     double lmu_;  // ln(mean_)
79     double s_;
80     double log_k_;
81     int split_;
82 
83     static_assert(std::is_integral<IntType>::value,
84                   "Class-template absl::poisson_distribution<> must be "
85                   "parameterized using an integral type.");
86   };
87 
poisson_distribution()88   poisson_distribution() : poisson_distribution(1.0) {}
89 
poisson_distribution(double mean)90   explicit poisson_distribution(double mean) : param_(mean) {}
91 
poisson_distribution(const param_type & p)92   explicit poisson_distribution(const param_type& p) : param_(p) {}
93 
reset()94   void reset() {}
95 
96   // generating functions
97   template <typename URBG>
operator()98   result_type operator()(URBG& g) {  // NOLINT(runtime/references)
99     return (*this)(g, param_);
100   }
101 
102   template <typename URBG>
103   result_type operator()(URBG& g,  // NOLINT(runtime/references)
104                          const param_type& p);
105 
param()106   param_type param() const { return param_; }
param(const param_type & p)107   void param(const param_type& p) { param_ = p; }
108 
result_type(min)109   result_type(min)() const { return 0; }
result_type(max)110   result_type(max)() const { return (std::numeric_limits<result_type>::max)(); }
111 
mean()112   double mean() const { return param_.mean(); }
113 
114   friend bool operator==(const poisson_distribution& a,
115                          const poisson_distribution& b) {
116     return a.param_ == b.param_;
117   }
118   friend bool operator!=(const poisson_distribution& a,
119                          const poisson_distribution& b) {
120     return a.param_ != b.param_;
121   }
122 
123  private:
124   param_type param_;
125   random_internal::FastUniformBits<uint64_t> fast_u64_;
126 };
127 
128 // -----------------------------------------------------------------------------
129 // Implementation details follow
130 // -----------------------------------------------------------------------------
131 
132 template <typename IntType>
param_type(double mean)133 poisson_distribution<IntType>::param_type::param_type(double mean)
134     : mean_(mean), split_(0) {
135   assert(mean >= 0);
136   assert(mean <= (std::numeric_limits<result_type>::max)());
137   // As a defensive measure, avoid large values of the mean.  The rejection
138   // algorithm used does not support very large values well.  It my be worth
139   // changing algorithms to better deal with these cases.
140   assert(mean <= 1e10);
141   if (mean_ < 10) {
142     // For small lambda, use the knuth method.
143     split_ = 1;
144     emu_ = std::exp(-mean_);
145   } else if (mean_ <= 50) {
146     // Use split-knuth method.
147     split_ = 1 + static_cast<int>(mean_ / 10.0);
148     emu_ = std::exp(-mean_ / static_cast<double>(split_));
149   } else {
150     // Use ratio of uniforms method.
151     constexpr double k2E = 0.7357588823428846;
152     constexpr double kSA = 0.4494580810294493;
153 
154     lmu_ = std::log(mean_);
155     double a = mean_ + 0.5;
156     s_ = kSA + std::sqrt(k2E * a);
157     const double mode = std::ceil(mean_) - 1;
158     log_k_ = lmu_ * mode - absl::random_internal::StirlingLogFactorial(mode);
159   }
160 }
161 
162 template <typename IntType>
163 template <typename URBG>
164 typename poisson_distribution<IntType>::result_type
operator()165 poisson_distribution<IntType>::operator()(
166     URBG& g,  // NOLINT(runtime/references)
167     const param_type& p) {
168   using random_internal::GeneratePositiveTag;
169   using random_internal::GenerateRealFromBits;
170   using random_internal::GenerateSignedTag;
171 
172   if (p.split_ != 0) {
173     // Use Knuth's algorithm with range splitting to avoid floating-point
174     // errors. Knuth's algorithm is: Ui is a sequence of uniform variates on
175     // (0,1); return the number of variates required for product(Ui) <
176     // exp(-lambda).
177     //
178     // The expected number of variates required for Knuth's method can be
179     // computed as follows:
180     // The expected value of U is 0.5, so solving for 0.5^n < exp(-lambda) gives
181     // the expected number of uniform variates
182     // required for a given lambda, which is:
183     //  lambda = [2, 5,  9, 10, 11, 12, 13, 14, 15, 16, 17]
184     //  n      = [3, 8, 13, 15, 16, 18, 19, 21, 22, 24, 25]
185     //
186     result_type n = 0;
187     for (int split = p.split_; split > 0; --split) {
188       double r = 1.0;
189       do {
190         r *= GenerateRealFromBits<double, GeneratePositiveTag, true>(
191             fast_u64_(g));  // U(-1, 0)
192         ++n;
193       } while (r > p.emu_);
194       --n;
195     }
196     return n;
197   }
198 
199   // Use ratio of uniforms method.
200   //
201   // Let u ~ Uniform(0, 1), v ~ Uniform(-1, 1),
202   //     a = lambda + 1/2,
203   //     s = 1.5 - sqrt(3/e) + sqrt(2(lambda + 1/2)/e),
204   //     x = s * v/u + a.
205   // P(floor(x) = k | u^2 < f(floor(x))/k), where
206   // f(m) = lambda^m exp(-lambda)/ m!, for 0 <= m, and f(m) = 0 otherwise,
207   // and k = max(f).
208   const double a = p.mean_ + 0.5;
209   for (;;) {
210     const double u = GenerateRealFromBits<double, GeneratePositiveTag, false>(
211         fast_u64_(g));  // U(0, 1)
212     const double v = GenerateRealFromBits<double, GenerateSignedTag, false>(
213         fast_u64_(g));  // U(-1, 1)
214 
215     const double x = std::floor(p.s_ * v / u + a);
216     if (x < 0) continue;  // f(negative) = 0
217     const double rhs = x * p.lmu_;
218     // clang-format off
219     double s = (x <= 1.0) ? 0.0
220              : (x == 2.0) ? 0.693147180559945
221              : absl::random_internal::StirlingLogFactorial(x);
222     // clang-format on
223     const double lhs = 2.0 * std::log(u) + p.log_k_ + s;
224     if (lhs < rhs) {
225       return x > (max)() ? (max)()
226                          : static_cast<result_type>(x);  // f(x)/k >= u^2
227     }
228   }
229 }
230 
231 template <typename CharT, typename Traits, typename IntType>
232 std::basic_ostream<CharT, Traits>& operator<<(
233     std::basic_ostream<CharT, Traits>& os,  // NOLINT(runtime/references)
234     const poisson_distribution<IntType>& x) {
235   auto saver = random_internal::make_ostream_state_saver(os);
236   os.precision(random_internal::stream_precision_helper<double>::kPrecision);
237   os << x.mean();
238   return os;
239 }
240 
241 template <typename CharT, typename Traits, typename IntType>
242 std::basic_istream<CharT, Traits>& operator>>(
243     std::basic_istream<CharT, Traits>& is,  // NOLINT(runtime/references)
244     poisson_distribution<IntType>& x) {     // NOLINT(runtime/references)
245   using param_type = typename poisson_distribution<IntType>::param_type;
246 
247   auto saver = random_internal::make_istream_state_saver(is);
248   double mean = random_internal::read_floating_point<double>(is);
249   if (!is.fail()) {
250     x.param(param_type(mean));
251   }
252   return is;
253 }
254 
255 ABSL_NAMESPACE_END
256 }  // namespace absl
257 
258 #endif  // ABSL_RANDOM_POISSON_DISTRIBUTION_H_
259