• 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/zipf_distribution.h"
16 
17 #include <algorithm>
18 #include <cstddef>
19 #include <cstdint>
20 #include <iterator>
21 #include <random>
22 #include <string>
23 #include <utility>
24 #include <vector>
25 
26 #include "gmock/gmock.h"
27 #include "gtest/gtest.h"
28 #include "absl/base/internal/raw_logging.h"
29 #include "absl/random/internal/chi_square.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_replace.h"
35 #include "absl/strings/strip.h"
36 
37 namespace {
38 
39 using ::absl::random_internal::kChiSquared;
40 using ::testing::ElementsAre;
41 
42 template <typename IntType>
43 class ZipfDistributionTypedTest : public ::testing::Test {};
44 
45 using IntTypes = ::testing::Types<int, int8_t, int16_t, int32_t, int64_t,
46                                   uint8_t, uint16_t, uint32_t, uint64_t>;
47 TYPED_TEST_SUITE(ZipfDistributionTypedTest, IntTypes);
48 
TYPED_TEST(ZipfDistributionTypedTest,SerializeTest)49 TYPED_TEST(ZipfDistributionTypedTest, SerializeTest) {
50   using param_type = typename absl::zipf_distribution<TypeParam>::param_type;
51 
52   constexpr int kCount = 1000;
53   absl::InsecureBitGen gen;
54   for (const auto& param : {
55            param_type(),
56            param_type(32),
57            param_type(100, 3, 2),
58            param_type(std::numeric_limits<TypeParam>::max(), 4, 3),
59            param_type(std::numeric_limits<TypeParam>::max() / 2),
60        }) {
61     // Validate parameters.
62     const auto k = param.k();
63     const auto q = param.q();
64     const auto v = param.v();
65 
66     absl::zipf_distribution<TypeParam> before(k, q, v);
67     EXPECT_EQ(before.k(), param.k());
68     EXPECT_EQ(before.q(), param.q());
69     EXPECT_EQ(before.v(), param.v());
70 
71     {
72       absl::zipf_distribution<TypeParam> via_param(param);
73       EXPECT_EQ(via_param, before);
74     }
75 
76     // Validate stream serialization.
77     std::stringstream ss;
78     ss << before;
79     absl::zipf_distribution<TypeParam> after(4, 5.5, 4.4);
80 
81     EXPECT_NE(before.k(), after.k());
82     EXPECT_NE(before.q(), after.q());
83     EXPECT_NE(before.v(), after.v());
84     EXPECT_NE(before.param(), after.param());
85     EXPECT_NE(before, after);
86 
87     ss >> after;
88 
89     EXPECT_EQ(before.k(), after.k());
90     EXPECT_EQ(before.q(), after.q());
91     EXPECT_EQ(before.v(), after.v());
92     EXPECT_EQ(before.param(), after.param());
93     EXPECT_EQ(before, after);
94 
95     // Smoke test.
96     auto sample_min = after.max();
97     auto sample_max = after.min();
98     for (int i = 0; i < kCount; i++) {
99       auto sample = after(gen);
100       EXPECT_GE(sample, after.min());
101       EXPECT_LE(sample, after.max());
102       if (sample > sample_max) sample_max = sample;
103       if (sample < sample_min) sample_min = sample;
104     }
105     ABSL_INTERNAL_LOG(INFO,
106                       absl::StrCat("Range: ", +sample_min, ", ", +sample_max));
107   }
108 }
109 
110 class ZipfModel {
111  public:
ZipfModel(size_t k,double q,double v)112   ZipfModel(size_t k, double q, double v) : k_(k), q_(q), v_(v) {}
113 
mean() const114   double mean() const { return mean_; }
115 
116   // For the other moments of the Zipf distribution, see, for example,
117   // http://mathworld.wolfram.com/ZipfDistribution.html
118 
119   // PMF(k) = (1 / k^s) / H(N,s)
120   // Returns the probability that any single invocation returns k.
PMF(size_t i)121   double PMF(size_t i) { return i >= hnq_.size() ? 0.0 : hnq_[i] / sum_hnq_; }
122 
123   // CDF = H(k, s) / H(N,s)
CDF(size_t i)124   double CDF(size_t i) {
125     if (i >= hnq_.size()) {
126       return 1.0;
127     }
128     auto it = std::begin(hnq_);
129     double h = 0.0;
130     for (const auto end = it; it != end; it++) {
131       h += *it;
132     }
133     return h / sum_hnq_;
134   }
135 
136   // The InverseCDF returns the k values which bound p on the upper and lower
137   // bound. Since there is no closed-form solution, this is implemented as a
138   // bisction of the cdf.
InverseCDF(double p)139   std::pair<size_t, size_t> InverseCDF(double p) {
140     size_t min = 0;
141     size_t max = hnq_.size();
142     while (max > min + 1) {
143       size_t target = (max + min) >> 1;
144       double x = CDF(target);
145       if (x > p) {
146         max = target;
147       } else {
148         min = target;
149       }
150     }
151     return {min, max};
152   }
153 
154   // Compute the probability totals, which are based on the generalized harmonic
155   // number, H(N,s).
156   //   H(N,s) == SUM(k=1..N, 1 / k^s)
157   //
158   // In the limit, H(N,s) == zetac(s) + 1.
159   //
160   // NOTE: The mean of a zipf distribution could be computed here as well.
161   // Mean :=  H(N, s-1) / H(N,s).
162   // Given the parameter v = 1, this gives the following function:
163   // (Hn(100, 1) - Hn(1,1)) / (Hn(100,2) - Hn(1,2)) = 6.5944
164   //
Init()165   void Init() {
166     if (!hnq_.empty()) {
167       return;
168     }
169     hnq_.clear();
170     hnq_.reserve(std::min(k_, size_t{1000}));
171 
172     sum_hnq_ = 0;
173     double qm1 = q_ - 1.0;
174     double sum_hnq_m1 = 0;
175     for (size_t i = 0; i < k_; i++) {
176       // Partial n-th generalized harmonic number
177       const double x = v_ + i;
178 
179       // H(n, q-1)
180       const double hnqm1 =
181           (q_ == 2.0) ? (1.0 / x)
182                       : (q_ == 3.0) ? (1.0 / (x * x)) : std::pow(x, -qm1);
183       sum_hnq_m1 += hnqm1;
184 
185       // H(n, q)
186       const double hnq =
187           (q_ == 2.0) ? (1.0 / (x * x))
188                       : (q_ == 3.0) ? (1.0 / (x * x * x)) : std::pow(x, -q_);
189       sum_hnq_ += hnq;
190       hnq_.push_back(hnq);
191       if (i > 1000 && hnq <= 1e-10) {
192         // The harmonic number is too small.
193         break;
194       }
195     }
196     assert(sum_hnq_ > 0);
197     mean_ = sum_hnq_m1 / sum_hnq_;
198   }
199 
200  private:
201   const size_t k_;
202   const double q_;
203   const double v_;
204 
205   double mean_;
206   std::vector<double> hnq_;
207   double sum_hnq_;
208 };
209 
210 using zipf_u64 = absl::zipf_distribution<uint64_t>;
211 
212 class ZipfTest : public testing::TestWithParam<zipf_u64::param_type>,
213                  public ZipfModel {
214  public:
ZipfTest()215   ZipfTest() : ZipfModel(GetParam().k(), GetParam().q(), GetParam().v()) {}
216 
217   // We use a fixed bit generator for distribution accuracy tests.  This allows
218   // these tests to be deterministic, while still testing the qualify of the
219   // implementation.
220   absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6};
221 };
222 
TEST_P(ZipfTest,ChiSquaredTest)223 TEST_P(ZipfTest, ChiSquaredTest) {
224   const auto& param = GetParam();
225   Init();
226 
227   size_t trials = 10000;
228 
229   // Find the split-points for the buckets.
230   std::vector<size_t> points;
231   std::vector<double> expected;
232   {
233     double last_cdf = 0.0;
234     double min_p = 1.0;
235     for (double p = 0.01; p < 1.0; p += 0.01) {
236       auto x = InverseCDF(p);
237       if (points.empty() || points.back() < x.second) {
238         const double p = CDF(x.second);
239         points.push_back(x.second);
240         double q = p - last_cdf;
241         expected.push_back(q);
242         last_cdf = p;
243         if (q < min_p) {
244           min_p = q;
245         }
246       }
247     }
248     if (last_cdf < 0.999) {
249       points.push_back(std::numeric_limits<size_t>::max());
250       double q = 1.0 - last_cdf;
251       expected.push_back(q);
252       if (q < min_p) {
253         min_p = q;
254       }
255     } else {
256       points.back() = std::numeric_limits<size_t>::max();
257       expected.back() += (1.0 - last_cdf);
258     }
259     // The Chi-Squared score is not completely scale-invariant; it works best
260     // when the small values are in the small digits.
261     trials = static_cast<size_t>(8.0 / min_p);
262   }
263   ASSERT_GT(points.size(), 0);
264 
265   // Generate n variates and fill the counts vector with the count of their
266   // occurrences.
267   std::vector<int64_t> buckets(points.size(), 0);
268   double avg = 0;
269   {
270     zipf_u64 dis(param);
271     for (size_t i = 0; i < trials; i++) {
272       uint64_t x = dis(rng_);
273       ASSERT_LE(x, dis.max());
274       ASSERT_GE(x, dis.min());
275       avg += static_cast<double>(x);
276       auto it = std::upper_bound(std::begin(points), std::end(points),
277                                  static_cast<size_t>(x));
278       buckets[std::distance(std::begin(points), it)]++;
279     }
280     avg = avg / static_cast<double>(trials);
281   }
282 
283   // Validate the output using the Chi-Squared test.
284   for (auto& e : expected) {
285     e *= trials;
286   }
287 
288   // The null-hypothesis is that the distribution is a poisson distribution with
289   // the provided mean (not estimated from the data).
290   const int dof = static_cast<int>(expected.size()) - 1;
291 
292   // NOTE: This test runs about 15x per invocation, so a value of 0.9995 is
293   // approximately correct for a test suite failure rate of 1 in 100.  In
294   // practice we see failures slightly higher than that.
295   const double threshold = absl::random_internal::ChiSquareValue(dof, 0.9999);
296 
297   const double chi_square = absl::random_internal::ChiSquare(
298       std::begin(buckets), std::end(buckets), std::begin(expected),
299       std::end(expected));
300 
301   const double p_actual =
302       absl::random_internal::ChiSquarePValue(chi_square, dof);
303 
304   // Log if the chi_squared value is above the threshold.
305   if (chi_square > threshold) {
306     ABSL_INTERNAL_LOG(INFO, "values");
307     for (size_t i = 0; i < expected.size(); i++) {
308       ABSL_INTERNAL_LOG(INFO, absl::StrCat(points[i], ": ", buckets[i],
309                                            " vs. E=", expected[i]));
310     }
311     ABSL_INTERNAL_LOG(INFO, absl::StrCat("trials ", trials));
312     ABSL_INTERNAL_LOG(INFO,
313                       absl::StrCat("mean ", avg, " vs. expected ", mean()));
314     ABSL_INTERNAL_LOG(INFO, absl::StrCat(kChiSquared, "(data, ", dof, ") = ",
315                                          chi_square, " (", p_actual, ")"));
316     ABSL_INTERNAL_LOG(INFO,
317                       absl::StrCat(kChiSquared, " @ 0.9995 = ", threshold));
318     FAIL() << kChiSquared << " value of " << chi_square
319            << " is above the threshold.";
320   }
321 }
322 
GenParams()323 std::vector<zipf_u64::param_type> GenParams() {
324   using param = zipf_u64::param_type;
325   const auto k = param().k();
326   const auto q = param().q();
327   const auto v = param().v();
328   const uint64_t k2 = 1 << 10;
329   return std::vector<zipf_u64::param_type>{
330       // Default
331       param(k, q, v),
332       // vary K
333       param(4, q, v), param(1 << 4, q, v), param(k2, q, v),
334       // vary V
335       param(k2, q, 0.5), param(k2, q, 1.5), param(k2, q, 2.5), param(k2, q, 10),
336       // vary Q
337       param(k2, 1.5, v), param(k2, 3, v), param(k2, 5, v), param(k2, 10, v),
338       // Vary V & Q
339       param(k2, 1.5, 0.5), param(k2, 3, 1.5), param(k, 10, 10)};
340 }
341 
ParamName(const::testing::TestParamInfo<zipf_u64::param_type> & info)342 std::string ParamName(
343     const ::testing::TestParamInfo<zipf_u64::param_type>& info) {
344   const auto& p = info.param;
345   std::string name = absl::StrCat("k_", p.k(), "__q_", absl::SixDigits(p.q()),
346                                   "__v_", absl::SixDigits(p.v()));
347   return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}});
348 }
349 
350 INSTANTIATE_TEST_SUITE_P(All, ZipfTest, ::testing::ValuesIn(GenParams()),
351                          ParamName);
352 
353 // NOTE: absl::zipf_distribution is not guaranteed to be stable.
TEST(ZipfDistributionTest,StabilityTest)354 TEST(ZipfDistributionTest, StabilityTest) {
355   // absl::zipf_distribution stability relies on
356   // absl::uniform_real_distribution, std::log, std::exp, std::log1p
357   absl::random_internal::sequence_urbg urbg(
358       {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
359        0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
360        0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
361        0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
362 
363   std::vector<int> output(10);
364 
365   {
366     absl::zipf_distribution<int32_t> dist;
367     std::generate(std::begin(output), std::end(output),
368                   [&] { return dist(urbg); });
369     EXPECT_THAT(output, ElementsAre(10031, 0, 0, 3, 6, 0, 7, 47, 0, 0));
370   }
371   urbg.reset();
372   {
373     absl::zipf_distribution<int32_t> dist(std::numeric_limits<int32_t>::max(),
374                                           3.3);
375     std::generate(std::begin(output), std::end(output),
376                   [&] { return dist(urbg); });
377     EXPECT_THAT(output, ElementsAre(44, 0, 0, 0, 0, 1, 0, 1, 3, 0));
378   }
379 }
380 
TEST(ZipfDistributionTest,AlgorithmBounds)381 TEST(ZipfDistributionTest, AlgorithmBounds) {
382   absl::zipf_distribution<int32_t> dist;
383 
384   // Small values from absl::uniform_real_distribution map to larger Zipf
385   // distribution values.
386   const std::pair<uint64_t, int32_t> kInputs[] = {
387       {0xffffffffffffffff, 0x0}, {0x7fffffffffffffff, 0x0},
388       {0x3ffffffffffffffb, 0x1}, {0x1ffffffffffffffd, 0x4},
389       {0xffffffffffffffe, 0x9},  {0x7ffffffffffffff, 0x12},
390       {0x3ffffffffffffff, 0x25}, {0x1ffffffffffffff, 0x4c},
391       {0xffffffffffffff, 0x99},  {0x7fffffffffffff, 0x132},
392       {0x3fffffffffffff, 0x265}, {0x1fffffffffffff, 0x4cc},
393       {0xfffffffffffff, 0x999},  {0x7ffffffffffff, 0x1332},
394       {0x3ffffffffffff, 0x2665}, {0x1ffffffffffff, 0x4ccc},
395       {0xffffffffffff, 0x9998},  {0x7fffffffffff, 0x1332f},
396       {0x3fffffffffff, 0x2665a}, {0x1fffffffffff, 0x4cc9e},
397       {0xfffffffffff, 0x998e0},  {0x7ffffffffff, 0x133051},
398       {0x3ffffffffff, 0x265ae4}, {0x1ffffffffff, 0x4c9ed3},
399       {0xffffffffff, 0x98e223},  {0x7fffffffff, 0x13058c4},
400       {0x3fffffffff, 0x25b178e}, {0x1fffffffff, 0x4a062b2},
401       {0xfffffffff, 0x8ee23b8},  {0x7ffffffff, 0x10b21642},
402       {0x3ffffffff, 0x1d89d89d}, {0x1ffffffff, 0x2fffffff},
403       {0xffffffff, 0x45d1745d},  {0x7fffffff, 0x5a5a5a5a},
404       {0x3fffffff, 0x69ee5846},  {0x1fffffff, 0x73ecade3},
405       {0xfffffff, 0x79a9d260},   {0x7ffffff, 0x7cc0532b},
406       {0x3ffffff, 0x7e5ad146},   {0x1ffffff, 0x7f2c0bec},
407       {0xffffff, 0x7f95adef},    {0x7fffff, 0x7fcac0da},
408       {0x3fffff, 0x7fe55ae2},    {0x1fffff, 0x7ff2ac0e},
409       {0xfffff, 0x7ff955ae},     {0x7ffff, 0x7ffcaac1},
410       {0x3ffff, 0x7ffe555b},     {0x1ffff, 0x7fff2aac},
411       {0xffff, 0x7fff9556},      {0x7fff, 0x7fffcaab},
412       {0x3fff, 0x7fffe555},      {0x1fff, 0x7ffff2ab},
413       {0xfff, 0x7ffff955},       {0x7ff, 0x7ffffcab},
414       {0x3ff, 0x7ffffe55},       {0x1ff, 0x7fffff2b},
415       {0xff, 0x7fffff95},        {0x7f, 0x7fffffcb},
416       {0x3f, 0x7fffffe5},        {0x1f, 0x7ffffff3},
417       {0xf, 0x7ffffff9},         {0x7, 0x7ffffffd},
418       {0x3, 0x7ffffffe},         {0x1, 0x7fffffff},
419   };
420 
421   for (const auto& instance : kInputs) {
422     absl::random_internal::sequence_urbg urbg({instance.first});
423     EXPECT_EQ(instance.second, dist(urbg));
424   }
425 }
426 
427 }  // namespace
428