blob: 5a8afde5ad4eaa19dc282232415140a6b06f7bf8 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// 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"
Austin Schuhb4691e92020-12-31 12:37:18 -080035#include "absl/random/internal/pcg_engine.h"
Austin Schuh36244a12019-09-21 17:52:38 -070036#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
43namespace {
44
45using absl::random_internal::kChiSquared;
46
47template <typename RealType>
48class ExponentialDistributionTypedTest : public ::testing::Test {};
49
50using RealTypes = ::testing::Types<float, double, long double>;
51TYPED_TEST_CASE(ExponentialDistributionTypedTest, RealTypes);
52
53TYPED_TEST(ExponentialDistributionTypedTest, SerializeTest) {
54 using param_type =
55 typename absl::exponential_distribution<TypeParam>::param_type;
56
57 const TypeParam kParams[] = {
58 // Cases around 1.
59 1, //
60 std::nextafter(TypeParam(1), TypeParam(0)), // 1 - epsilon
61 std::nextafter(TypeParam(1), TypeParam(2)), // 1 + epsilon
62 // Typical cases.
63 TypeParam(1e-8), TypeParam(1e-4), TypeParam(1), TypeParam(2),
64 TypeParam(1e4), TypeParam(1e8), TypeParam(1e20), TypeParam(2.5),
65 // Boundary cases.
66 std::numeric_limits<TypeParam>::max(),
67 std::numeric_limits<TypeParam>::epsilon(),
68 std::nextafter(std::numeric_limits<TypeParam>::min(),
69 TypeParam(1)), // min + epsilon
70 std::numeric_limits<TypeParam>::min(), // smallest normal
71 // There are some errors dealing with denorms on apple platforms.
72 std::numeric_limits<TypeParam>::denorm_min(), // smallest denorm
73 std::numeric_limits<TypeParam>::min() / 2, // denorm
74 std::nextafter(std::numeric_limits<TypeParam>::min(),
75 TypeParam(0)), // denorm_max
76 };
77
78 constexpr int kCount = 1000;
79 absl::InsecureBitGen gen;
80
81 for (const TypeParam lambda : kParams) {
82 // Some values may be invalid; skip those.
83 if (!std::isfinite(lambda)) continue;
84 ABSL_ASSERT(lambda > 0);
85
86 const param_type param(lambda);
87
88 absl::exponential_distribution<TypeParam> before(lambda);
89 EXPECT_EQ(before.lambda(), param.lambda());
90
91 {
92 absl::exponential_distribution<TypeParam> via_param(param);
93 EXPECT_EQ(via_param, before);
94 EXPECT_EQ(via_param.param(), before.param());
95 }
96
97 // Smoke test.
98 auto sample_min = before.max();
99 auto sample_max = before.min();
100 for (int i = 0; i < kCount; i++) {
101 auto sample = before(gen);
102 EXPECT_GE(sample, before.min()) << before;
103 EXPECT_LE(sample, before.max()) << before;
104 if (sample > sample_max) sample_max = sample;
105 if (sample < sample_min) sample_min = sample;
106 }
107 if (!std::is_same<TypeParam, long double>::value) {
108 ABSL_INTERNAL_LOG(INFO,
109 absl::StrFormat("Range {%f}: %f, %f, lambda=%f", lambda,
110 sample_min, sample_max, lambda));
111 }
112
113 std::stringstream ss;
114 ss << before;
115
116 if (!std::isfinite(lambda)) {
117 // Streams do not deserialize inf/nan correctly.
118 continue;
119 }
120 // Validate stream serialization.
121 absl::exponential_distribution<TypeParam> after(34.56f);
122
123 EXPECT_NE(before.lambda(), after.lambda());
124 EXPECT_NE(before.param(), after.param());
125 EXPECT_NE(before, after);
126
127 ss >> after;
128
129#if defined(__powerpc64__) || defined(__PPC64__) || defined(__powerpc__) || \
130 defined(__ppc__) || defined(__PPC__)
131 if (std::is_same<TypeParam, long double>::value) {
132 // Roundtripping floating point values requires sufficient precision to
133 // reconstruct the exact value. It turns out that long double has some
134 // errors doing this on ppc, particularly for values
135 // near {1.0 +/- epsilon}.
136 if (lambda <= std::numeric_limits<double>::max() &&
137 lambda >= std::numeric_limits<double>::lowest()) {
138 EXPECT_EQ(static_cast<double>(before.lambda()),
139 static_cast<double>(after.lambda()))
140 << ss.str();
141 }
142 continue;
143 }
144#endif
145
146 EXPECT_EQ(before.lambda(), after.lambda()) //
147 << ss.str() << " " //
148 << (ss.good() ? "good " : "") //
149 << (ss.bad() ? "bad " : "") //
150 << (ss.eof() ? "eof " : "") //
151 << (ss.fail() ? "fail " : "");
152 }
153}
154
155// http://www.itl.nist.gov/div898/handbook/eda/section3/eda3667.htm
156
157class ExponentialModel {
158 public:
159 explicit ExponentialModel(double lambda)
160 : lambda_(lambda), beta_(1.0 / lambda) {}
161
162 double lambda() const { return lambda_; }
163
164 double mean() const { return beta_; }
165 double variance() const { return beta_ * beta_; }
166 double stddev() const { return std::sqrt(variance()); }
167 double skew() const { return 2; }
168 double kurtosis() const { return 6.0; }
169
170 double CDF(double x) { return 1.0 - std::exp(-lambda_ * x); }
171
172 // The inverse CDF, or PercentPoint function of the distribution
173 double InverseCDF(double p) {
174 ABSL_ASSERT(p >= 0.0);
175 ABSL_ASSERT(p < 1.0);
176 return -beta_ * std::log(1.0 - p);
177 }
178
179 private:
180 const double lambda_;
181 const double beta_;
182};
183
184struct Param {
185 double lambda;
186 double p_fail;
187 int trials;
188};
189
190class ExponentialDistributionTests : public testing::TestWithParam<Param>,
191 public ExponentialModel {
192 public:
193 ExponentialDistributionTests() : ExponentialModel(GetParam().lambda) {}
194
195 // SingleZTest provides a basic z-squared test of the mean vs. expected
196 // mean for data generated by the poisson distribution.
197 template <typename D>
198 bool SingleZTest(const double p, const size_t samples);
199
200 // SingleChiSquaredTest provides a basic chi-squared test of the normal
201 // distribution.
202 template <typename D>
203 double SingleChiSquaredTest();
204
Austin Schuhb4691e92020-12-31 12:37:18 -0800205 // We use a fixed bit generator for distribution accuracy tests. This allows
206 // these tests to be deterministic, while still testing the qualify of the
207 // implementation.
208 absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6};
Austin Schuh36244a12019-09-21 17:52:38 -0700209};
210
211template <typename D>
212bool 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
244template <typename D>
245double 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
298TEST_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
315TEST_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
332std::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
347std::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
353INSTANTIATE_TEST_CASE_P(All, ExponentialDistributionTests,
354 ::testing::ValuesIn(GenParams()), ParamName);
355
356// NOTE: absl::exponential_distribution is not guaranteed to be stable.
357TEST(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
392TEST(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