• 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/log/log.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_SUITE(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     LOG(INFO) << "Range: " << sample_min << ", " << sample_max;
112   }
113 }
114 
115 using log_uniform_i32 = absl::log_uniform_int_distribution<int32_t>;
116 
117 class LogUniformIntChiSquaredTest
118     : public testing::TestWithParam<log_uniform_i32::param_type> {
119  public:
120   // The ChiSquaredTestImpl provides a chi-squared goodness of fit test for
121   // data generated by the log-uniform-int distribution.
122   double ChiSquaredTestImpl();
123 
124   // We use a fixed bit generator for distribution accuracy tests.  This allows
125   // these tests to be deterministic, while still testing the qualify of the
126   // implementation.
127   absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6};
128 };
129 
ChiSquaredTestImpl()130 double LogUniformIntChiSquaredTest::ChiSquaredTestImpl() {
131   using absl::random_internal::kChiSquared;
132 
133   const auto& param = GetParam();
134 
135   // Check the distribution of L=log(log_uniform_int_distribution, base),
136   // expecting that L is roughly uniformly distributed, that is:
137   //
138   //   P[L=0] ~= P[L=1] ~= ... ~= P[L=log(max)]
139   //
140   // For a total of X entries, each bucket should contain some number of samples
141   // in the interval [X/k - a, X/k + a].
142   //
143   // Where `a` is approximately sqrt(X/k). This is validated by bucketing
144   // according to the log function and using a chi-squared test for uniformity.
145 
146   const bool is_2 = (param.base() == 2);
147   const double base_log = 1.0 / std::log(param.base());
148   const auto bucket_index = [base_log, is_2, &param](int32_t x) {
149     uint64_t y = static_cast<uint64_t>(x) - param.min();
150     return (y == 0) ? 0
151                     : is_2 ? static_cast<int>(1 + std::log2(y))
152                            : static_cast<int>(1 + std::log(y) * base_log);
153   };
154   const int max_bucket = bucket_index(param.max());  // inclusive
155   const size_t trials = 15 + (max_bucket + 1) * 10;
156 
157   log_uniform_i32 dist(param);
158 
159   std::vector<int64_t> buckets(max_bucket + 1);
160   for (size_t i = 0; i < trials; ++i) {
161     const auto sample = dist(rng_);
162     // Check the bounds.
163     ABSL_ASSERT(sample <= dist.max());
164     ABSL_ASSERT(sample >= dist.min());
165     // Convert the output of the generator to one of num_bucket buckets.
166     int bucket = bucket_index(sample);
167     ABSL_ASSERT(bucket <= max_bucket);
168     ++buckets[bucket];
169   }
170 
171   // The null-hypothesis is that the distribution is uniform with respect to
172   // log-uniform-int bucketization.
173   const int dof = buckets.size() - 1;
174   const double expected = trials / static_cast<double>(buckets.size());
175 
176   const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98);
177 
178   double chi_square = absl::random_internal::ChiSquareWithExpected(
179       std::begin(buckets), std::end(buckets), expected);
180 
181   const double p = absl::random_internal::ChiSquarePValue(chi_square, dof);
182 
183   if (chi_square > threshold) {
184     LOG(INFO) << "values";
185     for (size_t i = 0; i < buckets.size(); i++) {
186       LOG(INFO) << i << ": " << buckets[i];
187     }
188     LOG(INFO) << "trials=" << trials << "\n"
189               << kChiSquared << "(data, " << dof << ") = " << chi_square << " ("
190               << p << ")\n"
191               << kChiSquared << " @ 0.98 = " << threshold;
192   }
193   return p;
194 }
195 
TEST_P(LogUniformIntChiSquaredTest,MultiTest)196 TEST_P(LogUniformIntChiSquaredTest, MultiTest) {
197   const int kTrials = 5;
198   int failures = 0;
199   for (int i = 0; i < kTrials; i++) {
200     double p_value = ChiSquaredTestImpl();
201     if (p_value < 0.005) {
202       failures++;
203     }
204   }
205 
206   // There is a 0.10% chance of producing at least one failure, so raise the
207   // failure threshold high enough to allow for a flake rate < 10,000.
208   EXPECT_LE(failures, 4);
209 }
210 
211 // Generate the parameters for the test.
GenParams()212 std::vector<log_uniform_i32::param_type> GenParams() {
213   using Param = log_uniform_i32::param_type;
214   using Limits = std::numeric_limits<int32_t>;
215 
216   return std::vector<Param>{
217       Param{0, 1, 2},
218       Param{1, 1, 2},
219       Param{0, 2, 2},
220       Param{0, 3, 2},
221       Param{0, 4, 2},
222       Param{0, 9, 10},
223       Param{0, 10, 10},
224       Param{0, 11, 10},
225       Param{1, 10, 10},
226       Param{0, (1 << 8) - 1, 2},
227       Param{0, (1 << 8), 2},
228       Param{0, (1 << 30) - 1, 2},
229       Param{-1000, 1000, 10},
230       Param{0, Limits::max(), 2},
231       Param{0, Limits::max(), 3},
232       Param{0, Limits::max(), 10},
233       Param{Limits::min(), 0},
234       Param{Limits::min(), Limits::max(), 2},
235   };
236 }
237 
ParamName(const::testing::TestParamInfo<log_uniform_i32::param_type> & info)238 std::string ParamName(
239     const ::testing::TestParamInfo<log_uniform_i32::param_type>& info) {
240   const auto& p = info.param;
241   std::string name =
242       absl::StrCat("min_", p.min(), "__max_", p.max(), "__base_", p.base());
243   return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}});
244 }
245 
246 INSTANTIATE_TEST_SUITE_P(All, LogUniformIntChiSquaredTest,
247                          ::testing::ValuesIn(GenParams()), ParamName);
248 
249 // NOTE: absl::log_uniform_int_distribution is not guaranteed to be stable.
TEST(LogUniformIntDistributionTest,StabilityTest)250 TEST(LogUniformIntDistributionTest, StabilityTest) {
251   using testing::ElementsAre;
252   // absl::uniform_int_distribution stability relies on
253   // absl::random_internal::LeadingSetBit, std::log, std::pow.
254   absl::random_internal::sequence_urbg urbg(
255       {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
256        0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
257        0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
258        0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
259 
260   std::vector<int> output(6);
261 
262   {
263     absl::log_uniform_int_distribution<int32_t> dist(0, 256);
264     std::generate(std::begin(output), std::end(output),
265                   [&] { return dist(urbg); });
266     EXPECT_THAT(output, ElementsAre(256, 66, 4, 6, 57, 103));
267   }
268   urbg.reset();
269   {
270     absl::log_uniform_int_distribution<int32_t> dist(0, 256, 10);
271     std::generate(std::begin(output), std::end(output),
272                   [&] { return dist(urbg); });
273     EXPECT_THAT(output, ElementsAre(8, 4, 0, 0, 0, 69));
274   }
275 }
276 
277 }  // namespace
278