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