• 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/log_uniform_int_distribution.h"
16 
17 #include <cstddef>
18 #include <cstdint>
19 #include <iterator>
20 #include <random>
21 #include <sstream>
22 #include <string>
23 #include <vector>
24 
25 #include "gmock/gmock.h"
26 #include "gtest/gtest.h"
27 #include "absl/base/internal/raw_logging.h"
28 #include "absl/random/internal/chi_square.h"
29 #include "absl/random/internal/distribution_test_util.h"
30 #include "absl/random/internal/pcg_engine.h"
31 #include "absl/random/internal/sequence_urbg.h"
32 #include "absl/random/random.h"
33 #include "absl/strings/str_cat.h"
34 #include "absl/strings/str_format.h"
35 #include "absl/strings/str_replace.h"
36 #include "absl/strings/strip.h"
37 
38 namespace {
39 
40 template <typename IntType>
41 class LogUniformIntDistributionTypeTest : public ::testing::Test {};
42 
43 using IntTypes = ::testing::Types<int8_t, int16_t, int32_t, int64_t,  //
44                                   uint8_t, uint16_t, uint32_t, uint64_t>;
45 TYPED_TEST_CASE(LogUniformIntDistributionTypeTest, IntTypes);
46 
TYPED_TEST(LogUniformIntDistributionTypeTest,SerializeTest)47 TYPED_TEST(LogUniformIntDistributionTypeTest, SerializeTest) {
48   using param_type =
49       typename absl::log_uniform_int_distribution<TypeParam>::param_type;
50   using Limits = std::numeric_limits<TypeParam>;
51 
52   constexpr int kCount = 1000;
53   absl::InsecureBitGen gen;
54   for (const auto& param : {
55            param_type(0, 1),                             //
56            param_type(0, 2),                             //
57            param_type(0, 2, 10),                         //
58            param_type(9, 32, 4),                         //
59            param_type(1, 101, 10),                       //
60            param_type(1, Limits::max() / 2),             //
61            param_type(0, Limits::max() - 1),             //
62            param_type(0, Limits::max(), 2),              //
63            param_type(0, Limits::max(), 10),             //
64            param_type(Limits::min(), 0),                 //
65            param_type(Limits::lowest(), Limits::max()),  //
66            param_type(Limits::min(), Limits::max()),     //
67        }) {
68     // Validate parameters.
69     const auto min = param.min();
70     const auto max = param.max();
71     const auto base = param.base();
72     absl::log_uniform_int_distribution<TypeParam> before(min, max, base);
73     EXPECT_EQ(before.min(), param.min());
74     EXPECT_EQ(before.max(), param.max());
75     EXPECT_EQ(before.base(), param.base());
76 
77     {
78       absl::log_uniform_int_distribution<TypeParam> via_param(param);
79       EXPECT_EQ(via_param, before);
80     }
81 
82     // Validate stream serialization.
83     std::stringstream ss;
84     ss << before;
85 
86     absl::log_uniform_int_distribution<TypeParam> after(3, 6, 17);
87 
88     EXPECT_NE(before.max(), after.max());
89     EXPECT_NE(before.base(), after.base());
90     EXPECT_NE(before.param(), after.param());
91     EXPECT_NE(before, after);
92 
93     ss >> after;
94 
95     EXPECT_EQ(before.min(), after.min());
96     EXPECT_EQ(before.max(), after.max());
97     EXPECT_EQ(before.base(), after.base());
98     EXPECT_EQ(before.param(), after.param());
99     EXPECT_EQ(before, after);
100 
101     // Smoke test.
102     auto sample_min = after.max();
103     auto sample_max = after.min();
104     for (int i = 0; i < kCount; i++) {
105       auto sample = after(gen);
106       EXPECT_GE(sample, after.min());
107       EXPECT_LE(sample, after.max());
108       if (sample > sample_max) sample_max = sample;
109       if (sample < sample_min) sample_min = sample;
110     }
111     ABSL_INTERNAL_LOG(INFO,
112                       absl::StrCat("Range: ", +sample_min, ", ", +sample_max));
113   }
114 }
115 
116 using log_uniform_i32 = absl::log_uniform_int_distribution<int32_t>;
117 
118 class LogUniformIntChiSquaredTest
119     : public testing::TestWithParam<log_uniform_i32::param_type> {
120  public:
121   // The ChiSquaredTestImpl provides a chi-squared goodness of fit test for
122   // data generated by the log-uniform-int distribution.
123   double ChiSquaredTestImpl();
124 
125   // We use a fixed bit generator for distribution accuracy tests.  This allows
126   // these tests to be deterministic, while still testing the qualify of the
127   // implementation.
128   absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6};
129 };
130 
ChiSquaredTestImpl()131 double LogUniformIntChiSquaredTest::ChiSquaredTestImpl() {
132   using absl::random_internal::kChiSquared;
133 
134   const auto& param = GetParam();
135 
136   // Check the distribution of L=log(log_uniform_int_distribution, base),
137   // expecting that L is roughly uniformly distributed, that is:
138   //
139   //   P[L=0] ~= P[L=1] ~= ... ~= P[L=log(max)]
140   //
141   // For a total of X entries, each bucket should contain some number of samples
142   // in the interval [X/k - a, X/k + a].
143   //
144   // Where `a` is approximately sqrt(X/k). This is validated by bucketing
145   // according to the log function and using a chi-squared test for uniformity.
146 
147   const bool is_2 = (param.base() == 2);
148   const double base_log = 1.0 / std::log(param.base());
149   const auto bucket_index = [base_log, is_2, &param](int32_t x) {
150     uint64_t y = static_cast<uint64_t>(x) - param.min();
151     return (y == 0) ? 0
152                     : is_2 ? static_cast<int>(1 + std::log2(y))
153                            : static_cast<int>(1 + std::log(y) * base_log);
154   };
155   const int max_bucket = bucket_index(param.max());  // inclusive
156   const size_t trials = 15 + (max_bucket + 1) * 10;
157 
158   log_uniform_i32 dist(param);
159 
160   std::vector<int64_t> buckets(max_bucket + 1);
161   for (size_t i = 0; i < trials; ++i) {
162     const auto sample = dist(rng_);
163     // Check the bounds.
164     ABSL_ASSERT(sample <= dist.max());
165     ABSL_ASSERT(sample >= dist.min());
166     // Convert the output of the generator to one of num_bucket buckets.
167     int bucket = bucket_index(sample);
168     ABSL_ASSERT(bucket <= max_bucket);
169     ++buckets[bucket];
170   }
171 
172   // The null-hypothesis is that the distribution is uniform with respect to
173   // log-uniform-int bucketization.
174   const int dof = buckets.size() - 1;
175   const double expected = trials / static_cast<double>(buckets.size());
176 
177   const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98);
178 
179   double chi_square = absl::random_internal::ChiSquareWithExpected(
180       std::begin(buckets), std::end(buckets), expected);
181 
182   const double p = absl::random_internal::ChiSquarePValue(chi_square, dof);
183 
184   if (chi_square > threshold) {
185     ABSL_INTERNAL_LOG(INFO, "values");
186     for (size_t i = 0; i < buckets.size(); i++) {
187       ABSL_INTERNAL_LOG(INFO, absl::StrCat(i, ": ", buckets[i]));
188     }
189     ABSL_INTERNAL_LOG(INFO,
190                       absl::StrFormat("trials=%d\n"
191                                       "%s(data, %d) = %f (%f)\n"
192                                       "%s @ 0.98 = %f",
193                                       trials, kChiSquared, dof, chi_square, p,
194                                       kChiSquared, threshold));
195   }
196   return p;
197 }
198 
TEST_P(LogUniformIntChiSquaredTest,MultiTest)199 TEST_P(LogUniformIntChiSquaredTest, MultiTest) {
200   const int kTrials = 5;
201   int failures = 0;
202   for (int i = 0; i < kTrials; i++) {
203     double p_value = ChiSquaredTestImpl();
204     if (p_value < 0.005) {
205       failures++;
206     }
207   }
208 
209   // There is a 0.10% chance of producing at least one failure, so raise the
210   // failure threshold high enough to allow for a flake rate < 10,000.
211   EXPECT_LE(failures, 4);
212 }
213 
214 // Generate the parameters for the test.
GenParams()215 std::vector<log_uniform_i32::param_type> GenParams() {
216   using Param = log_uniform_i32::param_type;
217   using Limits = std::numeric_limits<int32_t>;
218 
219   return std::vector<Param>{
220       Param{0, 1, 2},
221       Param{1, 1, 2},
222       Param{0, 2, 2},
223       Param{0, 3, 2},
224       Param{0, 4, 2},
225       Param{0, 9, 10},
226       Param{0, 10, 10},
227       Param{0, 11, 10},
228       Param{1, 10, 10},
229       Param{0, (1 << 8) - 1, 2},
230       Param{0, (1 << 8), 2},
231       Param{0, (1 << 30) - 1, 2},
232       Param{-1000, 1000, 10},
233       Param{0, Limits::max(), 2},
234       Param{0, Limits::max(), 3},
235       Param{0, Limits::max(), 10},
236       Param{Limits::min(), 0},
237       Param{Limits::min(), Limits::max(), 2},
238   };
239 }
240 
ParamName(const::testing::TestParamInfo<log_uniform_i32::param_type> & info)241 std::string ParamName(
242     const ::testing::TestParamInfo<log_uniform_i32::param_type>& info) {
243   const auto& p = info.param;
244   std::string name =
245       absl::StrCat("min_", p.min(), "__max_", p.max(), "__base_", p.base());
246   return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}});
247 }
248 
249 INSTANTIATE_TEST_SUITE_P(All, LogUniformIntChiSquaredTest,
250                          ::testing::ValuesIn(GenParams()), ParamName);
251 
252 // NOTE: absl::log_uniform_int_distribution is not guaranteed to be stable.
TEST(LogUniformIntDistributionTest,StabilityTest)253 TEST(LogUniformIntDistributionTest, StabilityTest) {
254   using testing::ElementsAre;
255   // absl::uniform_int_distribution stability relies on
256   // absl::random_internal::LeadingSetBit, std::log, std::pow.
257   absl::random_internal::sequence_urbg urbg(
258       {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
259        0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
260        0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
261        0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
262 
263   std::vector<int> output(6);
264 
265   {
266     absl::log_uniform_int_distribution<int32_t> dist(0, 256);
267     std::generate(std::begin(output), std::end(output),
268                   [&] { return dist(urbg); });
269     EXPECT_THAT(output, ElementsAre(256, 66, 4, 6, 57, 103));
270   }
271   urbg.reset();
272   {
273     absl::log_uniform_int_distribution<int32_t> dist(0, 256, 10);
274     std::generate(std::begin(output), std::end(output),
275                   [&] { return dist(urbg); });
276     EXPECT_THAT(output, ElementsAre(8, 4, 0, 0, 0, 69));
277   }
278 }
279 
280 }  // namespace
281