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/sequence_urbg.h"
31 #include "absl/random/random.h"
32 #include "absl/strings/str_cat.h"
33 #include "absl/strings/str_format.h"
34 #include "absl/strings/str_replace.h"
35 #include "absl/strings/strip.h"
36
37 namespace {
38
39 template <typename IntType>
40 class LogUniformIntDistributionTypeTest : public ::testing::Test {};
41
42 using IntTypes = ::testing::Types<int8_t, int16_t, int32_t, int64_t, //
43 uint8_t, uint16_t, uint32_t, uint64_t>;
44 TYPED_TEST_CASE(LogUniformIntDistributionTypeTest, IntTypes);
45
TYPED_TEST(LogUniformIntDistributionTypeTest,SerializeTest)46 TYPED_TEST(LogUniformIntDistributionTypeTest, SerializeTest) {
47 using param_type =
48 typename absl::log_uniform_int_distribution<TypeParam>::param_type;
49 using Limits = std::numeric_limits<TypeParam>;
50
51 constexpr int kCount = 1000;
52 absl::InsecureBitGen gen;
53 for (const auto& param : {
54 param_type(0, 1), //
55 param_type(0, 2), //
56 param_type(0, 2, 10), //
57 param_type(9, 32, 4), //
58 param_type(1, 101, 10), //
59 param_type(1, Limits::max() / 2), //
60 param_type(0, Limits::max() - 1), //
61 param_type(0, Limits::max(), 2), //
62 param_type(0, Limits::max(), 10), //
63 param_type(Limits::min(), 0), //
64 param_type(Limits::lowest(), Limits::max()), //
65 param_type(Limits::min(), Limits::max()), //
66 }) {
67 // Validate parameters.
68 const auto min = param.min();
69 const auto max = param.max();
70 const auto base = param.base();
71 absl::log_uniform_int_distribution<TypeParam> before(min, max, base);
72 EXPECT_EQ(before.min(), param.min());
73 EXPECT_EQ(before.max(), param.max());
74 EXPECT_EQ(before.base(), param.base());
75
76 {
77 absl::log_uniform_int_distribution<TypeParam> via_param(param);
78 EXPECT_EQ(via_param, before);
79 }
80
81 // Validate stream serialization.
82 std::stringstream ss;
83 ss << before;
84
85 absl::log_uniform_int_distribution<TypeParam> after(3, 6, 17);
86
87 EXPECT_NE(before.max(), after.max());
88 EXPECT_NE(before.base(), after.base());
89 EXPECT_NE(before.param(), after.param());
90 EXPECT_NE(before, after);
91
92 ss >> after;
93
94 EXPECT_EQ(before.min(), after.min());
95 EXPECT_EQ(before.max(), after.max());
96 EXPECT_EQ(before.base(), after.base());
97 EXPECT_EQ(before.param(), after.param());
98 EXPECT_EQ(before, after);
99
100 // Smoke test.
101 auto sample_min = after.max();
102 auto sample_max = after.min();
103 for (int i = 0; i < kCount; i++) {
104 auto sample = after(gen);
105 EXPECT_GE(sample, after.min());
106 EXPECT_LE(sample, after.max());
107 if (sample > sample_max) sample_max = sample;
108 if (sample < sample_min) sample_min = sample;
109 }
110 ABSL_INTERNAL_LOG(INFO,
111 absl::StrCat("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 absl::InsecureBitGen rng_;
125 };
126
ChiSquaredTestImpl()127 double LogUniformIntChiSquaredTest::ChiSquaredTestImpl() {
128 using absl::random_internal::kChiSquared;
129
130 const auto& param = GetParam();
131
132 // Check the distribution of L=log(log_uniform_int_distribution, base),
133 // expecting that L is roughly uniformly distributed, that is:
134 //
135 // P[L=0] ~= P[L=1] ~= ... ~= P[L=log(max)]
136 //
137 // For a total of X entries, each bucket should contain some number of samples
138 // in the interval [X/k - a, X/k + a].
139 //
140 // Where `a` is approximately sqrt(X/k). This is validated by bucketing
141 // according to the log function and using a chi-squared test for uniformity.
142
143 const bool is_2 = (param.base() == 2);
144 const double base_log = 1.0 / std::log(param.base());
145 const auto bucket_index = [base_log, is_2, ¶m](int32_t x) {
146 uint64_t y = static_cast<uint64_t>(x) - param.min();
147 return (y == 0) ? 0
148 : is_2 ? static_cast<int>(1 + std::log2(y))
149 : static_cast<int>(1 + std::log(y) * base_log);
150 };
151 const int max_bucket = bucket_index(param.max()); // inclusive
152 const size_t trials = 15 + (max_bucket + 1) * 10;
153
154 log_uniform_i32 dist(param);
155
156 std::vector<int64_t> buckets(max_bucket + 1);
157 for (size_t i = 0; i < trials; ++i) {
158 const auto sample = dist(rng_);
159 // Check the bounds.
160 ABSL_ASSERT(sample <= dist.max());
161 ABSL_ASSERT(sample >= dist.min());
162 // Convert the output of the generator to one of num_bucket buckets.
163 int bucket = bucket_index(sample);
164 ABSL_ASSERT(bucket <= max_bucket);
165 ++buckets[bucket];
166 }
167
168 // The null-hypothesis is that the distribution is uniform with respect to
169 // log-uniform-int bucketization.
170 const int dof = buckets.size() - 1;
171 const double expected = trials / static_cast<double>(buckets.size());
172
173 const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98);
174
175 double chi_square = absl::random_internal::ChiSquareWithExpected(
176 std::begin(buckets), std::end(buckets), expected);
177
178 const double p = absl::random_internal::ChiSquarePValue(chi_square, dof);
179
180 if (chi_square > threshold) {
181 ABSL_INTERNAL_LOG(INFO, "values");
182 for (size_t i = 0; i < buckets.size(); i++) {
183 ABSL_INTERNAL_LOG(INFO, absl::StrCat(i, ": ", buckets[i]));
184 }
185 ABSL_INTERNAL_LOG(INFO,
186 absl::StrFormat("trials=%d\n"
187 "%s(data, %d) = %f (%f)\n"
188 "%s @ 0.98 = %f",
189 trials, kChiSquared, dof, chi_square, p,
190 kChiSquared, threshold));
191 }
192 return p;
193 }
194
TEST_P(LogUniformIntChiSquaredTest,MultiTest)195 TEST_P(LogUniformIntChiSquaredTest, MultiTest) {
196 const int kTrials = 5;
197
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