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