zipf_distribution_test.cc 14 KB

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