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