discrete_distribution_test.cc 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  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. #include "absl/random/discrete_distribution.h"
  15. #include <cmath>
  16. #include <cstddef>
  17. #include <cstdint>
  18. #include <iterator>
  19. #include <numeric>
  20. #include <random>
  21. #include <sstream>
  22. #include <string>
  23. #include <vector>
  24. #include "gmock/gmock.h"
  25. #include "gtest/gtest.h"
  26. #include "absl/base/internal/raw_logging.h"
  27. #include "absl/random/internal/chi_square.h"
  28. #include "absl/random/internal/distribution_test_util.h"
  29. #include "absl/random/internal/pcg_engine.h"
  30. #include "absl/random/internal/sequence_urbg.h"
  31. #include "absl/random/random.h"
  32. #include "absl/strings/str_cat.h"
  33. #include "absl/strings/strip.h"
  34. namespace {
  35. template <typename IntType>
  36. class DiscreteDistributionTypeTest : public ::testing::Test {};
  37. using IntTypes = ::testing::Types<int8_t, uint8_t, int16_t, uint16_t, int32_t,
  38. uint32_t, int64_t, uint64_t>;
  39. TYPED_TEST_SUITE(DiscreteDistributionTypeTest, IntTypes);
  40. TYPED_TEST(DiscreteDistributionTypeTest, ParamSerializeTest) {
  41. using param_type =
  42. typename absl::discrete_distribution<TypeParam>::param_type;
  43. absl::discrete_distribution<TypeParam> empty;
  44. EXPECT_THAT(empty.probabilities(), testing::ElementsAre(1.0));
  45. absl::discrete_distribution<TypeParam> before({1.0, 2.0, 1.0});
  46. // Validate that the probabilities sum to 1.0. We picked values which
  47. // can be represented exactly to avoid floating-point roundoff error.
  48. double s = 0;
  49. for (const auto& x : before.probabilities()) {
  50. s += x;
  51. }
  52. EXPECT_EQ(s, 1.0);
  53. EXPECT_THAT(before.probabilities(), testing::ElementsAre(0.25, 0.5, 0.25));
  54. // Validate the same data via an initializer list.
  55. {
  56. std::vector<double> data({1.0, 2.0, 1.0});
  57. absl::discrete_distribution<TypeParam> via_param{
  58. param_type(std::begin(data), std::end(data))};
  59. EXPECT_EQ(via_param, before);
  60. }
  61. std::stringstream ss;
  62. ss << before;
  63. absl::discrete_distribution<TypeParam> after;
  64. EXPECT_NE(before, after);
  65. ss >> after;
  66. EXPECT_EQ(before, after);
  67. }
  68. TYPED_TEST(DiscreteDistributionTypeTest, Constructor) {
  69. auto fn = [](double x) { return x; };
  70. {
  71. absl::discrete_distribution<int> unary(0, 1.0, 9.0, fn);
  72. EXPECT_THAT(unary.probabilities(), testing::ElementsAre(1.0));
  73. }
  74. {
  75. absl::discrete_distribution<int> unary(2, 1.0, 9.0, fn);
  76. // => fn(1.0 + 0 * 4 + 2) => 3
  77. // => fn(1.0 + 1 * 4 + 2) => 7
  78. EXPECT_THAT(unary.probabilities(), testing::ElementsAre(0.3, 0.7));
  79. }
  80. }
  81. TEST(DiscreteDistributionTest, InitDiscreteDistribution) {
  82. using testing::_;
  83. using testing::Pair;
  84. {
  85. std::vector<double> p({1.0, 2.0, 3.0});
  86. std::vector<std::pair<double, size_t>> q =
  87. absl::random_internal::InitDiscreteDistribution(&p);
  88. EXPECT_THAT(p, testing::ElementsAre(1 / 6.0, 2 / 6.0, 3 / 6.0));
  89. // Each bucket is p=1/3, so bucket 0 will send half it's traffic
  90. // to bucket 2, while the rest will retain all of their traffic.
  91. EXPECT_THAT(q, testing::ElementsAre(Pair(0.5, 2), //
  92. Pair(1.0, _), //
  93. Pair(1.0, _)));
  94. }
  95. {
  96. std::vector<double> p({1.0, 2.0, 3.0, 5.0, 2.0});
  97. std::vector<std::pair<double, size_t>> q =
  98. absl::random_internal::InitDiscreteDistribution(&p);
  99. EXPECT_THAT(p, testing::ElementsAre(1 / 13.0, 2 / 13.0, 3 / 13.0, 5 / 13.0,
  100. 2 / 13.0));
  101. // A more complex bucketing solution: Each bucket has p=0.2
  102. // So buckets 0, 1, 4 will send their alternate traffic elsewhere, which
  103. // happens to be bucket 3.
  104. // However, summing up that alternate traffic gives bucket 3 too much
  105. // traffic, so it will send some traffic to bucket 2.
  106. constexpr double b0 = 1.0 / 13.0 / 0.2;
  107. constexpr double b1 = 2.0 / 13.0 / 0.2;
  108. constexpr double b3 = (5.0 / 13.0 / 0.2) - ((1 - b0) + (1 - b1) + (1 - b1));
  109. EXPECT_THAT(q, testing::ElementsAre(Pair(b0, 3), //
  110. Pair(b1, 3), //
  111. Pair(1.0, _), //
  112. Pair(b3, 2), //
  113. Pair(b1, 3)));
  114. }
  115. }
  116. TEST(DiscreteDistributionTest, ChiSquaredTest50) {
  117. using absl::random_internal::kChiSquared;
  118. constexpr size_t kTrials = 10000;
  119. constexpr int kBuckets = 50; // inclusive, so actally +1
  120. // 1-in-100000 threshold, but remember, there are about 8 tests
  121. // in this file. And the test could fail for other reasons.
  122. // Empirically validated with --runs_per_test=10000.
  123. const int kThreshold =
  124. absl::random_internal::ChiSquareValue(kBuckets, 0.99999);
  125. std::vector<double> weights(kBuckets, 0);
  126. std::iota(std::begin(weights), std::end(weights), 1);
  127. absl::discrete_distribution<int> dist(std::begin(weights), std::end(weights));
  128. // We use a fixed bit generator for distribution accuracy tests. This allows
  129. // these tests to be deterministic, while still testing the qualify of the
  130. // implementation.
  131. absl::random_internal::pcg64_2018_engine rng(0x2B7E151628AED2A6);
  132. std::vector<int32_t> counts(kBuckets, 0);
  133. for (size_t i = 0; i < kTrials; i++) {
  134. auto x = dist(rng);
  135. counts[x]++;
  136. }
  137. // Scale weights.
  138. double sum = 0;
  139. for (double x : weights) {
  140. sum += x;
  141. }
  142. for (double& x : weights) {
  143. x = kTrials * (x / sum);
  144. }
  145. double chi_square =
  146. absl::random_internal::ChiSquare(std::begin(counts), std::end(counts),
  147. std::begin(weights), std::end(weights));
  148. if (chi_square > kThreshold) {
  149. double p_value =
  150. absl::random_internal::ChiSquarePValue(chi_square, kBuckets);
  151. // Chi-squared test failed. Output does not appear to be uniform.
  152. std::string msg;
  153. for (size_t i = 0; i < counts.size(); i++) {
  154. absl::StrAppend(&msg, i, ": ", counts[i], " vs ", weights[i], "\n");
  155. }
  156. absl::StrAppend(&msg, kChiSquared, " p-value ", p_value, "\n");
  157. absl::StrAppend(&msg, "High ", kChiSquared, " value: ", chi_square, " > ",
  158. kThreshold);
  159. ABSL_RAW_LOG(INFO, "%s", msg.c_str());
  160. FAIL() << msg;
  161. }
  162. }
  163. TEST(DiscreteDistributionTest, StabilityTest) {
  164. // absl::discrete_distribution stabilitiy relies on
  165. // absl::uniform_int_distribution and absl::bernoulli_distribution.
  166. absl::random_internal::sequence_urbg urbg(
  167. {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
  168. 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
  169. 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
  170. 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
  171. std::vector<int> output(6);
  172. {
  173. absl::discrete_distribution<int32_t> dist({1.0, 2.0, 3.0, 5.0, 2.0});
  174. EXPECT_EQ(0, dist.min());
  175. EXPECT_EQ(4, dist.max());
  176. for (auto& v : output) {
  177. v = dist(urbg);
  178. }
  179. EXPECT_EQ(12, urbg.invocations());
  180. }
  181. // With 12 calls to urbg, each call into discrete_distribution consumes
  182. // precisely 2 values: one for the uniform call, and a second for the
  183. // bernoulli.
  184. //
  185. // Given the alt mapping: 0=>3, 1=>3, 2=>2, 3=>2, 4=>3, we can
  186. //
  187. // uniform: 443210143131
  188. // bernoulli: b0 000011100101
  189. // bernoulli: b1 001111101101
  190. // bernoulli: b2 111111111111
  191. // bernoulli: b3 001111101111
  192. // bernoulli: b4 001111101101
  193. // ...
  194. EXPECT_THAT(output, testing::ElementsAre(3, 3, 1, 3, 3, 3));
  195. {
  196. urbg.reset();
  197. absl::discrete_distribution<int64_t> dist({1.0, 2.0, 3.0, 5.0, 2.0});
  198. EXPECT_EQ(0, dist.min());
  199. EXPECT_EQ(4, dist.max());
  200. for (auto& v : output) {
  201. v = dist(urbg);
  202. }
  203. EXPECT_EQ(12, urbg.invocations());
  204. }
  205. EXPECT_THAT(output, testing::ElementsAre(3, 3, 0, 3, 0, 4));
  206. }
  207. } // namespace