blob: 6d007006ef48f40505a6d458b43d9c3f6206e4e3 [file] [log] [blame]
Austin Schuh36244a12019-09-21 17:52:38 -07001// 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"
Austin Schuhb4691e92020-12-31 12:37:18 -080032#include "absl/random/internal/pcg_engine.h"
Austin Schuh36244a12019-09-21 17:52:38 -070033#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
38namespace {
39
40template <typename IntType>
41class DiscreteDistributionTypeTest : public ::testing::Test {};
42
43using IntTypes = ::testing::Types<int8_t, uint8_t, int16_t, uint16_t, int32_t,
44 uint32_t, int64_t, uint64_t>;
45TYPED_TEST_SUITE(DiscreteDistributionTypeTest, IntTypes);
46
47TYPED_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
86TYPED_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
101TEST(DiscreteDistributionTest, InitDiscreteDistribution) {
102 using testing::Pair;
103
104 {
105 std::vector<double> p({1.0, 2.0, 3.0});
106 std::vector<std::pair<double, size_t>> q =
107 absl::random_internal::InitDiscreteDistribution(&p);
108
109 EXPECT_THAT(p, testing::ElementsAre(1 / 6.0, 2 / 6.0, 3 / 6.0));
110
111 // Each bucket is p=1/3, so bucket 0 will send half it's traffic
112 // to bucket 2, while the rest will retain all of their traffic.
113 EXPECT_THAT(q, testing::ElementsAre(Pair(0.5, 2), //
114 Pair(1.0, 1), //
115 Pair(1.0, 2)));
116 }
117
118 {
119 std::vector<double> p({1.0, 2.0, 3.0, 5.0, 2.0});
120
121 std::vector<std::pair<double, size_t>> q =
122 absl::random_internal::InitDiscreteDistribution(&p);
123
124 EXPECT_THAT(p, testing::ElementsAre(1 / 13.0, 2 / 13.0, 3 / 13.0, 5 / 13.0,
125 2 / 13.0));
126
127 // A more complex bucketing solution: Each bucket has p=0.2
128 // So buckets 0, 1, 4 will send their alternate traffic elsewhere, which
129 // happens to be bucket 3.
130 // However, summing up that alternate traffic gives bucket 3 too much
131 // traffic, so it will send some traffic to bucket 2.
132 constexpr double b0 = 1.0 / 13.0 / 0.2;
133 constexpr double b1 = 2.0 / 13.0 / 0.2;
134 constexpr double b3 = (5.0 / 13.0 / 0.2) - ((1 - b0) + (1 - b1) + (1 - b1));
135
136 EXPECT_THAT(q, testing::ElementsAre(Pair(b0, 3), //
137 Pair(b1, 3), //
138 Pair(1.0, 2), //
139 Pair(b3, 2), //
140 Pair(b1, 3)));
141 }
142}
143
144TEST(DiscreteDistributionTest, ChiSquaredTest50) {
145 using absl::random_internal::kChiSquared;
146
147 constexpr size_t kTrials = 10000;
148 constexpr int kBuckets = 50; // inclusive, so actally +1
149
150 // 1-in-100000 threshold, but remember, there are about 8 tests
151 // in this file. And the test could fail for other reasons.
152 // Empirically validated with --runs_per_test=10000.
153 const int kThreshold =
154 absl::random_internal::ChiSquareValue(kBuckets, 0.99999);
155
156 std::vector<double> weights(kBuckets, 0);
157 std::iota(std::begin(weights), std::end(weights), 1);
158 absl::discrete_distribution<int> dist(std::begin(weights), std::end(weights));
159
Austin Schuhb4691e92020-12-31 12:37:18 -0800160 // We use a fixed bit generator for distribution accuracy tests. This allows
161 // these tests to be deterministic, while still testing the qualify of the
162 // implementation.
163 absl::random_internal::pcg64_2018_engine rng(0x2B7E151628AED2A6);
Austin Schuh36244a12019-09-21 17:52:38 -0700164
165 std::vector<int32_t> counts(kBuckets, 0);
166 for (size_t i = 0; i < kTrials; i++) {
167 auto x = dist(rng);
168 counts[x]++;
169 }
170
171 // Scale weights.
172 double sum = 0;
173 for (double x : weights) {
174 sum += x;
175 }
176 for (double& x : weights) {
177 x = kTrials * (x / sum);
178 }
179
180 double chi_square =
181 absl::random_internal::ChiSquare(std::begin(counts), std::end(counts),
182 std::begin(weights), std::end(weights));
183
184 if (chi_square > kThreshold) {
185 double p_value =
186 absl::random_internal::ChiSquarePValue(chi_square, kBuckets);
187
188 // Chi-squared test failed. Output does not appear to be uniform.
189 std::string msg;
190 for (size_t i = 0; i < counts.size(); i++) {
191 absl::StrAppend(&msg, i, ": ", counts[i], " vs ", weights[i], "\n");
192 }
193 absl::StrAppend(&msg, kChiSquared, " p-value ", p_value, "\n");
194 absl::StrAppend(&msg, "High ", kChiSquared, " value: ", chi_square, " > ",
195 kThreshold);
196 ABSL_RAW_LOG(INFO, "%s", msg.c_str());
197 FAIL() << msg;
198 }
199}
200
201TEST(DiscreteDistributionTest, StabilityTest) {
202 // absl::discrete_distribution stabilitiy relies on
203 // absl::uniform_int_distribution and absl::bernoulli_distribution.
204 absl::random_internal::sequence_urbg urbg(
205 {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
206 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
207 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
208 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
209
210 std::vector<int> output(6);
211
212 {
213 absl::discrete_distribution<int32_t> dist({1.0, 2.0, 3.0, 5.0, 2.0});
214 EXPECT_EQ(0, dist.min());
215 EXPECT_EQ(4, dist.max());
216 for (auto& v : output) {
217 v = dist(urbg);
218 }
219 EXPECT_EQ(12, urbg.invocations());
220 }
221
222 // With 12 calls to urbg, each call into discrete_distribution consumes
223 // precisely 2 values: one for the uniform call, and a second for the
224 // bernoulli.
225 //
226 // Given the alt mapping: 0=>3, 1=>3, 2=>2, 3=>2, 4=>3, we can
227 //
228 // uniform: 443210143131
229 // bernoulli: b0 000011100101
230 // bernoulli: b1 001111101101
231 // bernoulli: b2 111111111111
232 // bernoulli: b3 001111101111
233 // bernoulli: b4 001111101101
234 // ...
235 EXPECT_THAT(output, testing::ElementsAre(3, 3, 1, 3, 3, 3));
236
237 {
238 urbg.reset();
239 absl::discrete_distribution<int64_t> dist({1.0, 2.0, 3.0, 5.0, 2.0});
240 EXPECT_EQ(0, dist.min());
241 EXPECT_EQ(4, dist.max());
242 for (auto& v : output) {
243 v = dist(urbg);
244 }
245 EXPECT_EQ(12, urbg.invocations());
246 }
247 EXPECT_THAT(output, testing::ElementsAre(3, 3, 0, 3, 0, 4));
248}
249
250} // namespace