• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "absl/random/exponential_distribution.h"
16 
17 #include <algorithm>
18 #include <cmath>
19 #include <cstddef>
20 #include <cstdint>
21 #include <iterator>
22 #include <limits>
23 #include <random>
24 #include <sstream>
25 #include <string>
26 #include <type_traits>
27 #include <vector>
28 
29 #include "gmock/gmock.h"
30 #include "gtest/gtest.h"
31 #include "absl/base/internal/raw_logging.h"
32 #include "absl/base/macros.h"
33 #include "absl/random/internal/chi_square.h"
34 #include "absl/random/internal/distribution_test_util.h"
35 #include "absl/random/internal/pcg_engine.h"
36 #include "absl/random/internal/sequence_urbg.h"
37 #include "absl/random/random.h"
38 #include "absl/strings/str_cat.h"
39 #include "absl/strings/str_format.h"
40 #include "absl/strings/str_replace.h"
41 #include "absl/strings/strip.h"
42 
43 namespace {
44 
45 using absl::random_internal::kChiSquared;
46 
47 template <typename RealType>
48 class ExponentialDistributionTypedTest : public ::testing::Test {};
49 
50 #if defined(__EMSCRIPTEN__)
51 using RealTypes = ::testing::Types<float, double>;
52 #else
53 using RealTypes = ::testing::Types<float, double, long double>;
54 #endif  // defined(__EMSCRIPTEN__)
55 TYPED_TEST_CASE(ExponentialDistributionTypedTest, RealTypes);
56 
TYPED_TEST(ExponentialDistributionTypedTest,SerializeTest)57 TYPED_TEST(ExponentialDistributionTypedTest, SerializeTest) {
58   using param_type =
59       typename absl::exponential_distribution<TypeParam>::param_type;
60 
61   const TypeParam kParams[] = {
62       // Cases around 1.
63       1,                                           //
64       std::nextafter(TypeParam(1), TypeParam(0)),  // 1 - epsilon
65       std::nextafter(TypeParam(1), TypeParam(2)),  // 1 + epsilon
66       // Typical cases.
67       TypeParam(1e-8), TypeParam(1e-4), TypeParam(1), TypeParam(2),
68       TypeParam(1e4), TypeParam(1e8), TypeParam(1e20), TypeParam(2.5),
69       // Boundary cases.
70       std::numeric_limits<TypeParam>::max(),
71       std::numeric_limits<TypeParam>::epsilon(),
72       std::nextafter(std::numeric_limits<TypeParam>::min(),
73                      TypeParam(1)),           // min + epsilon
74       std::numeric_limits<TypeParam>::min(),  // smallest normal
75       // There are some errors dealing with denorms on apple platforms.
76       std::numeric_limits<TypeParam>::denorm_min(),  // smallest denorm
77       std::numeric_limits<TypeParam>::min() / 2,     // denorm
78       std::nextafter(std::numeric_limits<TypeParam>::min(),
79                      TypeParam(0)),  // denorm_max
80   };
81 
82   constexpr int kCount = 1000;
83   absl::InsecureBitGen gen;
84 
85   for (const TypeParam lambda : kParams) {
86     // Some values may be invalid; skip those.
87     if (!std::isfinite(lambda)) continue;
88     ABSL_ASSERT(lambda > 0);
89 
90     const param_type param(lambda);
91 
92     absl::exponential_distribution<TypeParam> before(lambda);
93     EXPECT_EQ(before.lambda(), param.lambda());
94 
95     {
96       absl::exponential_distribution<TypeParam> via_param(param);
97       EXPECT_EQ(via_param, before);
98       EXPECT_EQ(via_param.param(), before.param());
99     }
100 
101     // Smoke test.
102     auto sample_min = before.max();
103     auto sample_max = before.min();
104     for (int i = 0; i < kCount; i++) {
105       auto sample = before(gen);
106       EXPECT_GE(sample, before.min()) << before;
107       EXPECT_LE(sample, before.max()) << before;
108       if (sample > sample_max) sample_max = sample;
109       if (sample < sample_min) sample_min = sample;
110     }
111     if (!std::is_same<TypeParam, long double>::value) {
112       ABSL_INTERNAL_LOG(INFO,
113                         absl::StrFormat("Range {%f}: %f, %f, lambda=%f", lambda,
114                                         sample_min, sample_max, lambda));
115     }
116 
117     std::stringstream ss;
118     ss << before;
119 
120     if (!std::isfinite(lambda)) {
121       // Streams do not deserialize inf/nan correctly.
122       continue;
123     }
124     // Validate stream serialization.
125     absl::exponential_distribution<TypeParam> after(34.56f);
126 
127     EXPECT_NE(before.lambda(), after.lambda());
128     EXPECT_NE(before.param(), after.param());
129     EXPECT_NE(before, after);
130 
131     ss >> after;
132 
133 #if defined(__powerpc64__) || defined(__PPC64__) || defined(__powerpc__) || \
134     defined(__ppc__) || defined(__PPC__)
135     if (std::is_same<TypeParam, long double>::value) {
136       // Roundtripping floating point values requires sufficient precision to
137       // reconstruct the exact value. It turns out that long double has some
138       // errors doing this on ppc, particularly for values
139       // near {1.0 +/- epsilon}.
140       if (lambda <= std::numeric_limits<double>::max() &&
141           lambda >= std::numeric_limits<double>::lowest()) {
142         EXPECT_EQ(static_cast<double>(before.lambda()),
143                   static_cast<double>(after.lambda()))
144             << ss.str();
145       }
146       continue;
147     }
148 #endif
149 
150     EXPECT_EQ(before.lambda(), after.lambda())  //
151         << ss.str() << " "                      //
152         << (ss.good() ? "good " : "")           //
153         << (ss.bad() ? "bad " : "")             //
154         << (ss.eof() ? "eof " : "")             //
155         << (ss.fail() ? "fail " : "");
156   }
157 }
158 
159 // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3667.htm
160 
161 class ExponentialModel {
162  public:
ExponentialModel(double lambda)163   explicit ExponentialModel(double lambda)
164       : lambda_(lambda), beta_(1.0 / lambda) {}
165 
lambda() const166   double lambda() const { return lambda_; }
167 
mean() const168   double mean() const { return beta_; }
variance() const169   double variance() const { return beta_ * beta_; }
stddev() const170   double stddev() const { return std::sqrt(variance()); }
skew() const171   double skew() const { return 2; }
kurtosis() const172   double kurtosis() const { return 6.0; }
173 
CDF(double x)174   double CDF(double x) { return 1.0 - std::exp(-lambda_ * x); }
175 
176   // The inverse CDF, or PercentPoint function of the distribution
InverseCDF(double p)177   double InverseCDF(double p) {
178     ABSL_ASSERT(p >= 0.0);
179     ABSL_ASSERT(p < 1.0);
180     return -beta_ * std::log(1.0 - p);
181   }
182 
183  private:
184   const double lambda_;
185   const double beta_;
186 };
187 
188 struct Param {
189   double lambda;
190   double p_fail;
191   int trials;
192 };
193 
194 class ExponentialDistributionTests : public testing::TestWithParam<Param>,
195                                      public ExponentialModel {
196  public:
ExponentialDistributionTests()197   ExponentialDistributionTests() : ExponentialModel(GetParam().lambda) {}
198 
199   // SingleZTest provides a basic z-squared test of the mean vs. expected
200   // mean for data generated by the poisson distribution.
201   template <typename D>
202   bool SingleZTest(const double p, const size_t samples);
203 
204   // SingleChiSquaredTest provides a basic chi-squared test of the normal
205   // distribution.
206   template <typename D>
207   double SingleChiSquaredTest();
208 
209   // We use a fixed bit generator for distribution accuracy tests.  This allows
210   // these tests to be deterministic, while still testing the qualify of the
211   // implementation.
212   absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6};
213 };
214 
215 template <typename D>
SingleZTest(const double p,const size_t samples)216 bool ExponentialDistributionTests::SingleZTest(const double p,
217                                                const size_t samples) {
218   D dis(lambda());
219 
220   std::vector<double> data;
221   data.reserve(samples);
222   for (size_t i = 0; i < samples; i++) {
223     const double x = dis(rng_);
224     data.push_back(x);
225   }
226 
227   const auto m = absl::random_internal::ComputeDistributionMoments(data);
228   const double max_err = absl::random_internal::MaxErrorTolerance(p);
229   const double z = absl::random_internal::ZScore(mean(), m);
230   const bool pass = absl::random_internal::Near("z", z, 0.0, max_err);
231 
232   if (!pass) {
233     ABSL_INTERNAL_LOG(
234         INFO, absl::StrFormat("p=%f max_err=%f\n"
235                               " lambda=%f\n"
236                               " mean=%f vs. %f\n"
237                               " stddev=%f vs. %f\n"
238                               " skewness=%f vs. %f\n"
239                               " kurtosis=%f vs. %f\n"
240                               " z=%f vs. 0",
241                               p, max_err, lambda(), m.mean, mean(),
242                               std::sqrt(m.variance), stddev(), m.skewness,
243                               skew(), m.kurtosis, kurtosis(), z));
244   }
245   return pass;
246 }
247 
248 template <typename D>
SingleChiSquaredTest()249 double ExponentialDistributionTests::SingleChiSquaredTest() {
250   const size_t kSamples = 10000;
251   const int kBuckets = 50;
252 
253   // The InverseCDF is the percent point function of the distribution, and can
254   // be used to assign buckets roughly uniformly.
255   std::vector<double> cutoffs;
256   const double kInc = 1.0 / static_cast<double>(kBuckets);
257   for (double p = kInc; p < 1.0; p += kInc) {
258     cutoffs.push_back(InverseCDF(p));
259   }
260   if (cutoffs.back() != std::numeric_limits<double>::infinity()) {
261     cutoffs.push_back(std::numeric_limits<double>::infinity());
262   }
263 
264   D dis(lambda());
265 
266   std::vector<int32_t> counts(cutoffs.size(), 0);
267   for (int j = 0; j < kSamples; j++) {
268     const double x = dis(rng_);
269     auto it = std::upper_bound(cutoffs.begin(), cutoffs.end(), x);
270     counts[std::distance(cutoffs.begin(), it)]++;
271   }
272 
273   // Null-hypothesis is that the distribution is exponentially distributed
274   // with the provided lambda (not estimated from the data).
275   const int dof = static_cast<int>(counts.size()) - 1;
276 
277   // Our threshold for logging is 1-in-50.
278   const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98);
279 
280   const double expected =
281       static_cast<double>(kSamples) / static_cast<double>(counts.size());
282 
283   double chi_square = absl::random_internal::ChiSquareWithExpected(
284       std::begin(counts), std::end(counts), expected);
285   double p = absl::random_internal::ChiSquarePValue(chi_square, dof);
286 
287   if (chi_square > threshold) {
288     for (int i = 0; i < cutoffs.size(); i++) {
289       ABSL_INTERNAL_LOG(
290           INFO, absl::StrFormat("%d : (%f) = %d", i, cutoffs[i], counts[i]));
291     }
292 
293     ABSL_INTERNAL_LOG(INFO,
294                       absl::StrCat("lambda ", lambda(), "\n",     //
295                                    " expected ", expected, "\n",  //
296                                    kChiSquared, " ", chi_square, " (", p, ")\n",
297                                    kChiSquared, " @ 0.98 = ", threshold));
298   }
299   return p;
300 }
301 
TEST_P(ExponentialDistributionTests,ZTest)302 TEST_P(ExponentialDistributionTests, ZTest) {
303   const size_t kSamples = 10000;
304   const auto& param = GetParam();
305   const int expected_failures =
306       std::max(1, static_cast<int>(std::ceil(param.trials * param.p_fail)));
307   const double p = absl::random_internal::RequiredSuccessProbability(
308       param.p_fail, param.trials);
309 
310   int failures = 0;
311   for (int i = 0; i < param.trials; i++) {
312     failures += SingleZTest<absl::exponential_distribution<double>>(p, kSamples)
313                     ? 0
314                     : 1;
315   }
316   EXPECT_LE(failures, expected_failures);
317 }
318 
TEST_P(ExponentialDistributionTests,ChiSquaredTest)319 TEST_P(ExponentialDistributionTests, ChiSquaredTest) {
320   const int kTrials = 20;
321   int failures = 0;
322 
323   for (int i = 0; i < kTrials; i++) {
324     double p_value =
325         SingleChiSquaredTest<absl::exponential_distribution<double>>();
326     if (p_value < 0.005) {  // 1/200
327       failures++;
328     }
329   }
330 
331   // There is a 0.10% chance of producing at least one failure, so raise the
332   // failure threshold high enough to allow for a flake rate < 10,000.
333   EXPECT_LE(failures, 4);
334 }
335 
GenParams()336 std::vector<Param> GenParams() {
337   return {
338       Param{1.0, 0.02, 100},
339       Param{2.5, 0.02, 100},
340       Param{10, 0.02, 100},
341       // large
342       Param{1e4, 0.02, 100},
343       Param{1e9, 0.02, 100},
344       // small
345       Param{0.1, 0.02, 100},
346       Param{1e-3, 0.02, 100},
347       Param{1e-5, 0.02, 100},
348   };
349 }
350 
ParamName(const::testing::TestParamInfo<Param> & info)351 std::string ParamName(const ::testing::TestParamInfo<Param>& info) {
352   const auto& p = info.param;
353   std::string name = absl::StrCat("lambda_", absl::SixDigits(p.lambda));
354   return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}});
355 }
356 
357 INSTANTIATE_TEST_CASE_P(All, ExponentialDistributionTests,
358                         ::testing::ValuesIn(GenParams()), ParamName);
359 
360 // NOTE: absl::exponential_distribution is not guaranteed to be stable.
TEST(ExponentialDistributionTest,StabilityTest)361 TEST(ExponentialDistributionTest, StabilityTest) {
362   // absl::exponential_distribution stability relies on std::log1p and
363   // absl::uniform_real_distribution.
364   absl::random_internal::sequence_urbg urbg(
365       {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
366        0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
367        0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
368        0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
369 
370   std::vector<int> output(14);
371 
372   {
373     absl::exponential_distribution<double> dist;
374     std::generate(std::begin(output), std::end(output),
375                   [&] { return static_cast<int>(10000.0 * dist(urbg)); });
376 
377     EXPECT_EQ(14, urbg.invocations());
378     EXPECT_THAT(output,
379                 testing::ElementsAre(0, 71913, 14375, 5039, 1835, 861, 25936,
380                                      804, 126, 12337, 17984, 27002, 0, 71913));
381   }
382 
383   urbg.reset();
384   {
385     absl::exponential_distribution<float> dist;
386     std::generate(std::begin(output), std::end(output),
387                   [&] { return static_cast<int>(10000.0f * dist(urbg)); });
388 
389     EXPECT_EQ(14, urbg.invocations());
390     EXPECT_THAT(output,
391                 testing::ElementsAre(0, 71913, 14375, 5039, 1835, 861, 25936,
392                                      804, 126, 12337, 17984, 27002, 0, 71913));
393   }
394 }
395 
TEST(ExponentialDistributionTest,AlgorithmBounds)396 TEST(ExponentialDistributionTest, AlgorithmBounds) {
397   // Relies on absl::uniform_real_distribution, so some of these comments
398   // reference that.
399   absl::exponential_distribution<double> dist;
400 
401   {
402     // This returns the smallest value >0 from absl::uniform_real_distribution.
403     absl::random_internal::sequence_urbg urbg({0x0000000000000001ull});
404     double a = dist(urbg);
405     EXPECT_EQ(a, 5.42101086242752217004e-20);
406   }
407 
408   {
409     // This returns a value very near 0.5 from absl::uniform_real_distribution.
410     absl::random_internal::sequence_urbg urbg({0x7fffffffffffffefull});
411     double a = dist(urbg);
412     EXPECT_EQ(a, 0.693147180559945175204);
413   }
414 
415   {
416     // This returns the largest value <1 from absl::uniform_real_distribution.
417     // WolframAlpha: ~39.1439465808987766283058547296341915292187253
418     absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFeFull});
419     double a = dist(urbg);
420     EXPECT_EQ(a, 36.7368005696771007251);
421   }
422   {
423     // This *ALSO* returns the largest value <1.
424     absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFFFull});
425     double a = dist(urbg);
426     EXPECT_EQ(a, 36.7368005696771007251);
427   }
428 }
429 
430 }  // namespace
431