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/gaussian_distribution.h"
16
17 #include <algorithm>
18 #include <cmath>
19 #include <cstddef>
20 #include <ios>
21 #include <iterator>
22 #include <random>
23 #include <string>
24 #include <type_traits>
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/base/macros.h"
31 #include "absl/numeric/internal/representation.h"
32 #include "absl/random/internal/chi_square.h"
33 #include "absl/random/internal/distribution_test_util.h"
34 #include "absl/random/internal/sequence_urbg.h"
35 #include "absl/random/random.h"
36 #include "absl/strings/str_cat.h"
37 #include "absl/strings/str_format.h"
38 #include "absl/strings/str_replace.h"
39 #include "absl/strings/strip.h"
40
41 namespace {
42
43 using absl::random_internal::kChiSquared;
44
45 template <typename RealType>
46 class GaussianDistributionInterfaceTest : public ::testing::Test {};
47
48 // double-double arithmetic is not supported well by either GCC or Clang; see
49 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99048,
50 // https://bugs.llvm.org/show_bug.cgi?id=49131, and
51 // https://bugs.llvm.org/show_bug.cgi?id=49132. Don't bother running these tests
52 // with double doubles until compiler support is better.
53 using RealTypes =
54 std::conditional<absl::numeric_internal::IsDoubleDouble(),
55 ::testing::Types<float, double>,
56 ::testing::Types<float, double, long double>>::type;
57 TYPED_TEST_SUITE(GaussianDistributionInterfaceTest, RealTypes);
58
TYPED_TEST(GaussianDistributionInterfaceTest,SerializeTest)59 TYPED_TEST(GaussianDistributionInterfaceTest, SerializeTest) {
60 using param_type =
61 typename absl::gaussian_distribution<TypeParam>::param_type;
62
63 const TypeParam kParams[] = {
64 // Cases around 1.
65 1, //
66 std::nextafter(TypeParam(1), TypeParam(0)), // 1 - epsilon
67 std::nextafter(TypeParam(1), TypeParam(2)), // 1 + epsilon
68 // Arbitrary values.
69 TypeParam(1e-8), TypeParam(1e-4), TypeParam(2), TypeParam(1e4),
70 TypeParam(1e8), TypeParam(1e20), TypeParam(2.5),
71 // Boundary cases.
72 std::numeric_limits<TypeParam>::infinity(),
73 std::numeric_limits<TypeParam>::max(),
74 std::numeric_limits<TypeParam>::epsilon(),
75 std::nextafter(std::numeric_limits<TypeParam>::min(),
76 TypeParam(1)), // min + epsilon
77 std::numeric_limits<TypeParam>::min(), // smallest normal
78 // There are some errors dealing with denorms on apple platforms.
79 std::numeric_limits<TypeParam>::denorm_min(), // smallest denorm
80 std::numeric_limits<TypeParam>::min() / 2,
81 std::nextafter(std::numeric_limits<TypeParam>::min(),
82 TypeParam(0)), // denorm_max
83 };
84
85 constexpr int kCount = 1000;
86 absl::InsecureBitGen gen;
87
88 // Use a loop to generate the combinations of {+/-x, +/-y}, and assign x, y to
89 // all values in kParams,
90 for (const auto mod : {0, 1, 2, 3}) {
91 for (const auto x : kParams) {
92 if (!std::isfinite(x)) continue;
93 for (const auto y : kParams) {
94 const TypeParam mean = (mod & 0x1) ? -x : x;
95 const TypeParam stddev = (mod & 0x2) ? -y : y;
96 const param_type param(mean, stddev);
97
98 absl::gaussian_distribution<TypeParam> before(mean, stddev);
99 EXPECT_EQ(before.mean(), param.mean());
100 EXPECT_EQ(before.stddev(), param.stddev());
101
102 {
103 absl::gaussian_distribution<TypeParam> via_param(param);
104 EXPECT_EQ(via_param, before);
105 EXPECT_EQ(via_param.param(), before.param());
106 }
107
108 // Smoke test.
109 auto sample_min = before.max();
110 auto sample_max = before.min();
111 for (int i = 0; i < kCount; i++) {
112 auto sample = before(gen);
113 if (sample > sample_max) sample_max = sample;
114 if (sample < sample_min) sample_min = sample;
115 EXPECT_GE(sample, before.min()) << before;
116 EXPECT_LE(sample, before.max()) << before;
117 }
118 if (!std::is_same<TypeParam, long double>::value) {
119 ABSL_INTERNAL_LOG(
120 INFO, absl::StrFormat("Range{%f, %f}: %f, %f", mean, stddev,
121 sample_min, sample_max));
122 }
123
124 std::stringstream ss;
125 ss << before;
126
127 if (!std::isfinite(mean) || !std::isfinite(stddev)) {
128 // Streams do not parse inf/nan.
129 continue;
130 }
131
132 // Validate stream serialization.
133 absl::gaussian_distribution<TypeParam> after(-0.53f, 2.3456f);
134
135 EXPECT_NE(before.mean(), after.mean());
136 EXPECT_NE(before.stddev(), after.stddev());
137 EXPECT_NE(before.param(), after.param());
138 EXPECT_NE(before, after);
139
140 ss >> after;
141
142 EXPECT_EQ(before.mean(), after.mean());
143 EXPECT_EQ(before.stddev(), after.stddev()) //
144 << ss.str() << " " //
145 << (ss.good() ? "good " : "") //
146 << (ss.bad() ? "bad " : "") //
147 << (ss.eof() ? "eof " : "") //
148 << (ss.fail() ? "fail " : "");
149 }
150 }
151 }
152 }
153
154 // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3661.htm
155
156 class GaussianModel {
157 public:
GaussianModel(double mean,double stddev)158 GaussianModel(double mean, double stddev) : mean_(mean), stddev_(stddev) {}
159
mean() const160 double mean() const { return mean_; }
variance() const161 double variance() const { return stddev() * stddev(); }
stddev() const162 double stddev() const { return stddev_; }
skew() const163 double skew() const { return 0; }
kurtosis() const164 double kurtosis() const { return 3.0; }
165
166 // The inverse CDF, or PercentPoint function.
InverseCDF(double p)167 double InverseCDF(double p) {
168 ABSL_ASSERT(p >= 0.0);
169 ABSL_ASSERT(p < 1.0);
170 return mean() + stddev() * -absl::random_internal::InverseNormalSurvival(p);
171 }
172
173 private:
174 const double mean_;
175 const double stddev_;
176 };
177
178 struct Param {
179 double mean;
180 double stddev;
181 double p_fail; // Z-Test probability of failure.
182 int trials; // Z-Test trials.
183 };
184
185 // GaussianDistributionTests implements a z-test for the gaussian
186 // distribution.
187 class GaussianDistributionTests : public testing::TestWithParam<Param>,
188 public GaussianModel {
189 public:
GaussianDistributionTests()190 GaussianDistributionTests()
191 : GaussianModel(GetParam().mean, GetParam().stddev) {}
192
193 // SingleZTest provides a basic z-squared test of the mean vs. expected
194 // mean for data generated by the poisson distribution.
195 template <typename D>
196 bool SingleZTest(const double p, const size_t samples);
197
198 // SingleChiSquaredTest provides a basic chi-squared test of the normal
199 // distribution.
200 template <typename D>
201 double SingleChiSquaredTest();
202
203 // We use a fixed bit generator for distribution accuracy tests. This allows
204 // these tests to be deterministic, while still testing the qualify of the
205 // implementation.
206 absl::random_internal::pcg64_2018_engine rng_{0x2B7E151628AED2A6};
207 };
208
209 template <typename D>
SingleZTest(const double p,const size_t samples)210 bool GaussianDistributionTests::SingleZTest(const double p,
211 const size_t samples) {
212 D dis(mean(), stddev());
213
214 std::vector<double> data;
215 data.reserve(samples);
216 for (size_t i = 0; i < samples; i++) {
217 const double x = dis(rng_);
218 data.push_back(x);
219 }
220
221 const double max_err = absl::random_internal::MaxErrorTolerance(p);
222 const auto m = absl::random_internal::ComputeDistributionMoments(data);
223 const double z = absl::random_internal::ZScore(mean(), m);
224 const bool pass = absl::random_internal::Near("z", z, 0.0, max_err);
225
226 // NOTE: Informational statistical test:
227 //
228 // Compute the Jarque-Bera test statistic given the excess skewness
229 // and kurtosis. The statistic is drawn from a chi-square(2) distribution.
230 // https://en.wikipedia.org/wiki/Jarque%E2%80%93Bera_test
231 //
232 // The null-hypothesis (normal distribution) is rejected when
233 // (p = 0.05 => jb > 5.99)
234 // (p = 0.01 => jb > 9.21)
235 // NOTE: JB has a large type-I error rate, so it will reject the
236 // null-hypothesis even when it is true more often than the z-test.
237 //
238 const double jb =
239 static_cast<double>(m.n) / 6.0 *
240 (std::pow(m.skewness, 2.0) + std::pow(m.kurtosis - 3.0, 2.0) / 4.0);
241
242 if (!pass || jb > 9.21) {
243 ABSL_INTERNAL_LOG(
244 INFO, absl::StrFormat("p=%f max_err=%f\n"
245 " mean=%f vs. %f\n"
246 " stddev=%f vs. %f\n"
247 " skewness=%f vs. %f\n"
248 " kurtosis=%f vs. %f\n"
249 " z=%f vs. 0\n"
250 " jb=%f vs. 9.21",
251 p, max_err, m.mean, mean(), std::sqrt(m.variance),
252 stddev(), m.skewness, skew(), m.kurtosis,
253 kurtosis(), z, jb));
254 }
255 return pass;
256 }
257
258 template <typename D>
SingleChiSquaredTest()259 double GaussianDistributionTests::SingleChiSquaredTest() {
260 const size_t kSamples = 10000;
261 const int kBuckets = 50;
262
263 // The InverseCDF is the percent point function of the
264 // distribution, and can be used to assign buckets
265 // roughly uniformly.
266 std::vector<double> cutoffs;
267 const double kInc = 1.0 / static_cast<double>(kBuckets);
268 for (double p = kInc; p < 1.0; p += kInc) {
269 cutoffs.push_back(InverseCDF(p));
270 }
271 if (cutoffs.back() != std::numeric_limits<double>::infinity()) {
272 cutoffs.push_back(std::numeric_limits<double>::infinity());
273 }
274
275 D dis(mean(), stddev());
276
277 std::vector<int32_t> counts(cutoffs.size(), 0);
278 for (int j = 0; j < kSamples; j++) {
279 const double x = dis(rng_);
280 auto it = std::upper_bound(cutoffs.begin(), cutoffs.end(), x);
281 counts[std::distance(cutoffs.begin(), it)]++;
282 }
283
284 // Null-hypothesis is that the distribution is a gaussian distribution
285 // with the provided mean and stddev (not estimated from the data).
286 const int dof = static_cast<int>(counts.size()) - 1;
287
288 // Our threshold for logging is 1-in-50.
289 const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98);
290
291 const double expected =
292 static_cast<double>(kSamples) / static_cast<double>(counts.size());
293
294 double chi_square = absl::random_internal::ChiSquareWithExpected(
295 std::begin(counts), std::end(counts), expected);
296 double p = absl::random_internal::ChiSquarePValue(chi_square, dof);
297
298 // Log if the chi_square value is above the threshold.
299 if (chi_square > threshold) {
300 for (int i = 0; i < cutoffs.size(); i++) {
301 ABSL_INTERNAL_LOG(
302 INFO, absl::StrFormat("%d : (%f) = %d", i, cutoffs[i], counts[i]));
303 }
304
305 ABSL_INTERNAL_LOG(
306 INFO, absl::StrCat("mean=", mean(), " stddev=", stddev(), "\n", //
307 " expected ", expected, "\n", //
308 kChiSquared, " ", chi_square, " (", p, ")\n", //
309 kChiSquared, " @ 0.98 = ", threshold));
310 }
311 return p;
312 }
313
TEST_P(GaussianDistributionTests,ZTest)314 TEST_P(GaussianDistributionTests, ZTest) {
315 // TODO(absl-team): Run these tests against std::normal_distribution<double>
316 // to validate outcomes are similar.
317 const size_t kSamples = 10000;
318 const auto& param = GetParam();
319 const int expected_failures =
320 std::max(1, static_cast<int>(std::ceil(param.trials * param.p_fail)));
321 const double p = absl::random_internal::RequiredSuccessProbability(
322 param.p_fail, param.trials);
323
324 int failures = 0;
325 for (int i = 0; i < param.trials; i++) {
326 failures +=
327 SingleZTest<absl::gaussian_distribution<double>>(p, kSamples) ? 0 : 1;
328 }
329 EXPECT_LE(failures, expected_failures);
330 }
331
TEST_P(GaussianDistributionTests,ChiSquaredTest)332 TEST_P(GaussianDistributionTests, ChiSquaredTest) {
333 const int kTrials = 20;
334 int failures = 0;
335
336 for (int i = 0; i < kTrials; i++) {
337 double p_value =
338 SingleChiSquaredTest<absl::gaussian_distribution<double>>();
339 if (p_value < 0.0025) { // 1/400
340 failures++;
341 }
342 }
343 // There is a 0.05% chance of producing at least one failure, so raise the
344 // failure threshold high enough to allow for a flake rate of less than one in
345 // 10,000.
346 EXPECT_LE(failures, 4);
347 }
348
GenParams()349 std::vector<Param> GenParams() {
350 return {
351 // Mean around 0.
352 Param{0.0, 1.0, 0.01, 100},
353 Param{0.0, 1e2, 0.01, 100},
354 Param{0.0, 1e4, 0.01, 100},
355 Param{0.0, 1e8, 0.01, 100},
356 Param{0.0, 1e16, 0.01, 100},
357 Param{0.0, 1e-3, 0.01, 100},
358 Param{0.0, 1e-5, 0.01, 100},
359 Param{0.0, 1e-9, 0.01, 100},
360 Param{0.0, 1e-17, 0.01, 100},
361
362 // Mean around 1.
363 Param{1.0, 1.0, 0.01, 100},
364 Param{1.0, 1e2, 0.01, 100},
365 Param{1.0, 1e-2, 0.01, 100},
366
367 // Mean around 100 / -100
368 Param{1e2, 1.0, 0.01, 100},
369 Param{-1e2, 1.0, 0.01, 100},
370 Param{1e2, 1e6, 0.01, 100},
371 Param{-1e2, 1e6, 0.01, 100},
372
373 // More extreme
374 Param{1e4, 1e4, 0.01, 100},
375 Param{1e8, 1e4, 0.01, 100},
376 Param{1e12, 1e4, 0.01, 100},
377 };
378 }
379
ParamName(const::testing::TestParamInfo<Param> & info)380 std::string ParamName(const ::testing::TestParamInfo<Param>& info) {
381 const auto& p = info.param;
382 std::string name = absl::StrCat("mean_", absl::SixDigits(p.mean), "__stddev_",
383 absl::SixDigits(p.stddev));
384 return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}});
385 }
386
387 INSTANTIATE_TEST_SUITE_P(All, GaussianDistributionTests,
388 ::testing::ValuesIn(GenParams()), ParamName);
389
390 // NOTE: absl::gaussian_distribution is not guaranteed to be stable.
TEST(GaussianDistributionTest,StabilityTest)391 TEST(GaussianDistributionTest, StabilityTest) {
392 // absl::gaussian_distribution stability relies on the underlying zignor
393 // data, absl::random_interna::RandU64ToDouble, std::exp, std::log, and
394 // std::abs.
395 absl::random_internal::sequence_urbg urbg(
396 {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
397 0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
398 0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
399 0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
400
401 std::vector<int> output(11);
402
403 {
404 absl::gaussian_distribution<double> dist;
405 std::generate(std::begin(output), std::end(output),
406 [&] { return static_cast<int>(10000000.0 * dist(urbg)); });
407
408 EXPECT_EQ(13, urbg.invocations());
409 EXPECT_THAT(output, //
410 testing::ElementsAre(1494, 25518841, 9991550, 1351856,
411 -20373238, 3456682, 333530, -6804981,
412 -15279580, -16459654, 1494));
413 }
414
415 urbg.reset();
416 {
417 absl::gaussian_distribution<float> dist;
418 std::generate(std::begin(output), std::end(output),
419 [&] { return static_cast<int>(1000000.0f * dist(urbg)); });
420
421 EXPECT_EQ(13, urbg.invocations());
422 EXPECT_THAT(
423 output, //
424 testing::ElementsAre(149, 2551884, 999155, 135185, -2037323, 345668,
425 33353, -680498, -1527958, -1645965, 149));
426 }
427 }
428
429 // This is an implementation-specific test. If any part of the implementation
430 // changes, then it is likely that this test will change as well.
431 // Also, if dependencies of the distribution change, such as RandU64ToDouble,
432 // then this is also likely to change.
TEST(GaussianDistributionTest,AlgorithmBounds)433 TEST(GaussianDistributionTest, AlgorithmBounds) {
434 absl::gaussian_distribution<double> dist;
435
436 // In ~95% of cases, a single value is used to generate the output.
437 // for all inputs where |x| < 0.750461021389 this should be the case.
438 //
439 // The exact constraints are based on the ziggurat tables, and any
440 // changes to the ziggurat tables may require adjusting these bounds.
441 //
442 // for i in range(0, len(X)-1):
443 // print i, X[i+1]/X[i], (X[i+1]/X[i] > 0.984375)
444 //
445 // 0.125 <= |values| <= 0.75
446 const uint64_t kValues[] = {
447 0x1000000000000100ull, 0x2000000000000100ull, 0x3000000000000100ull,
448 0x4000000000000100ull, 0x5000000000000100ull, 0x6000000000000100ull,
449 // negative values
450 0x9000000000000100ull, 0xa000000000000100ull, 0xb000000000000100ull,
451 0xc000000000000100ull, 0xd000000000000100ull, 0xe000000000000100ull};
452
453 // 0.875 <= |values| <= 0.984375
454 const uint64_t kExtraValues[] = {
455 0x7000000000000100ull, 0x7800000000000100ull, //
456 0x7c00000000000100ull, 0x7e00000000000100ull, //
457 // negative values
458 0xf000000000000100ull, 0xf800000000000100ull, //
459 0xfc00000000000100ull, 0xfe00000000000100ull};
460
461 auto make_box = [](uint64_t v, uint64_t box) {
462 return (v & 0xffffffffffffff80ull) | box;
463 };
464
465 // The box is the lower 7 bits of the value. When the box == 0, then
466 // the algorithm uses an escape hatch to select the result for large
467 // outputs.
468 for (uint64_t box = 0; box < 0x7f; box++) {
469 for (const uint64_t v : kValues) {
470 // Extra values are added to the sequence to attempt to avoid
471 // infinite loops from rejection sampling on bugs/errors.
472 absl::random_internal::sequence_urbg urbg(
473 {make_box(v, box), 0x0003eb76f6f7f755ull, 0x5FCEA50FDB2F953Bull});
474
475 auto a = dist(urbg);
476 EXPECT_EQ(1, urbg.invocations()) << box << " " << std::hex << v;
477 if (v & 0x8000000000000000ull) {
478 EXPECT_LT(a, 0.0) << box << " " << std::hex << v;
479 } else {
480 EXPECT_GT(a, 0.0) << box << " " << std::hex << v;
481 }
482 }
483 if (box > 10 && box < 100) {
484 // The center boxes use the fast algorithm for more
485 // than 98.4375% of values.
486 for (const uint64_t v : kExtraValues) {
487 absl::random_internal::sequence_urbg urbg(
488 {make_box(v, box), 0x0003eb76f6f7f755ull, 0x5FCEA50FDB2F953Bull});
489
490 auto a = dist(urbg);
491 EXPECT_EQ(1, urbg.invocations()) << box << " " << std::hex << v;
492 if (v & 0x8000000000000000ull) {
493 EXPECT_LT(a, 0.0) << box << " " << std::hex << v;
494 } else {
495 EXPECT_GT(a, 0.0) << box << " " << std::hex << v;
496 }
497 }
498 }
499 }
500
501 // When the box == 0, the fallback algorithm uses a ratio of uniforms,
502 // which consumes 2 additional values from the urbg.
503 // Fallback also requires that the initial value be > 0.9271586026096681.
504 auto make_fallback = [](uint64_t v) { return (v & 0xffffffffffffff80ull); };
505
506 double tail[2];
507 {
508 // 0.9375
509 absl::random_internal::sequence_urbg urbg(
510 {make_fallback(0x7800000000000000ull), 0x13CCA830EB61BD96ull,
511 0x00000076f6f7f755ull});
512 tail[0] = dist(urbg);
513 EXPECT_EQ(3, urbg.invocations());
514 EXPECT_GT(tail[0], 0);
515 }
516 {
517 // -0.9375
518 absl::random_internal::sequence_urbg urbg(
519 {make_fallback(0xf800000000000000ull), 0x13CCA830EB61BD96ull,
520 0x00000076f6f7f755ull});
521 tail[1] = dist(urbg);
522 EXPECT_EQ(3, urbg.invocations());
523 EXPECT_LT(tail[1], 0);
524 }
525 EXPECT_EQ(tail[0], -tail[1]);
526 EXPECT_EQ(418610, static_cast<int64_t>(tail[0] * 100000.0));
527
528 // When the box != 0, the fallback algorithm computes a wedge function.
529 // Depending on the box, the threshold for varies as high as
530 // 0.991522480228.
531 {
532 // 0.9921875, 0.875
533 absl::random_internal::sequence_urbg urbg(
534 {make_box(0x7f00000000000000ull, 120), 0xe000000000000001ull,
535 0x13CCA830EB61BD96ull});
536 tail[0] = dist(urbg);
537 EXPECT_EQ(2, urbg.invocations());
538 EXPECT_GT(tail[0], 0);
539 }
540 {
541 // -0.9921875, 0.875
542 absl::random_internal::sequence_urbg urbg(
543 {make_box(0xff00000000000000ull, 120), 0xe000000000000001ull,
544 0x13CCA830EB61BD96ull});
545 tail[1] = dist(urbg);
546 EXPECT_EQ(2, urbg.invocations());
547 EXPECT_LT(tail[1], 0);
548 }
549 EXPECT_EQ(tail[0], -tail[1]);
550 EXPECT_EQ(61948, static_cast<int64_t>(tail[0] * 100000.0));
551
552 // Fallback rejected, try again.
553 {
554 // -0.9921875, 0.0625
555 absl::random_internal::sequence_urbg urbg(
556 {make_box(0xff00000000000000ull, 120), 0x1000000000000001,
557 make_box(0x1000000000000100ull, 50), 0x13CCA830EB61BD96ull});
558 dist(urbg);
559 EXPECT_EQ(3, urbg.invocations());
560 }
561 }
562
563 } // namespace
564