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