abseil-cpp/absl/random/exponential_distribution_test.cc
Go to the documentation of this file.
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/exponential_distribution.h"
16 
17 #include <algorithm>
18 #include <cfloat>
19 #include <cmath>
20 #include <cstddef>
21 #include <cstdint>
22 #include <iterator>
23 #include <limits>
24 #include <random>
25 #include <sstream>
26 #include <string>
27 #include <type_traits>
28 #include <vector>
29 
30 #include "gmock/gmock.h"
31 #include "gtest/gtest.h"
32 #include "absl/base/internal/raw_logging.h"
33 #include "absl/base/macros.h"
34 #include "absl/numeric/internal/representation.h"
35 #include "absl/random/internal/chi_square.h"
36 #include "absl/random/internal/distribution_test_util.h"
37 #include "absl/random/internal/pcg_engine.h"
38 #include "absl/random/internal/sequence_urbg.h"
39 #include "absl/random/random.h"
40 #include "absl/strings/str_cat.h"
41 #include "absl/strings/str_format.h"
42 #include "absl/strings/str_replace.h"
43 #include "absl/strings/strip.h"
44 
45 namespace {
46 
48 
49 template <typename RealType>
50 class ExponentialDistributionTypedTest : public ::testing::Test {};
51 
52 // double-double arithmetic is not supported well by either GCC or Clang; see
53 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=99048,
54 // https://bugs.llvm.org/show_bug.cgi?id=49131, and
55 // https://bugs.llvm.org/show_bug.cgi?id=49132. Don't bother running these tests
56 // with double doubles until compiler support is better.
57 using RealTypes =
58  std::conditional<absl::numeric_internal::IsDoubleDouble(),
61 TYPED_TEST_SUITE(ExponentialDistributionTypedTest, RealTypes);
62 
63 TYPED_TEST(ExponentialDistributionTypedTest, SerializeTest) {
64  using param_type =
66 
67  const TypeParam kParams[] = {
68  // Cases around 1.
69  1, //
70  std::nextafter(TypeParam(1), TypeParam(0)), // 1 - epsilon
71  std::nextafter(TypeParam(1), TypeParam(2)), // 1 + epsilon
72  // Typical cases.
73  TypeParam(1e-8), TypeParam(1e-4), TypeParam(1), TypeParam(2),
74  TypeParam(1e4), TypeParam(1e8), TypeParam(1e20), TypeParam(2.5),
75  // Boundary cases.
77  std::numeric_limits<TypeParam>::epsilon(),
78  std::nextafter(std::numeric_limits<TypeParam>::min(),
79  TypeParam(1)), // min + epsilon
80  std::numeric_limits<TypeParam>::min(), // smallest normal
81  // There are some errors dealing with denorms on apple platforms.
82  std::numeric_limits<TypeParam>::denorm_min(), // smallest denorm
84  std::nextafter(std::numeric_limits<TypeParam>::min(),
85  TypeParam(0)), // denorm_max
86  };
87 
88  constexpr int kCount = 1000;
90 
91  for (const TypeParam lambda : kParams) {
92  // Some values may be invalid; skip those.
93  if (!std::isfinite(lambda)) continue;
94  ABSL_ASSERT(lambda > 0);
95 
96  const param_type param(lambda);
97 
99  EXPECT_EQ(before.lambda(), param.lambda());
100 
101  {
103  EXPECT_EQ(via_param, before);
104  EXPECT_EQ(via_param.param(), before.param());
105  }
106 
107  // Smoke test.
108  auto sample_min = before.max();
109  auto sample_max = before.min();
110  for (int i = 0; i < kCount; i++) {
111  auto sample = before(gen);
112  EXPECT_GE(sample, before.min()) << before;
113  EXPECT_LE(sample, before.max()) << before;
114  if (sample > sample_max) sample_max = sample;
115  if (sample < sample_min) sample_min = sample;
116  }
119  absl::StrFormat("Range {%f}: %f, %f, lambda=%f", lambda,
120  sample_min, sample_max, lambda));
121  }
122 
123  std::stringstream ss;
124  ss << before;
125 
126  if (!std::isfinite(lambda)) {
127  // Streams do not deserialize inf/nan correctly.
128  continue;
129  }
130  // Validate stream serialization.
132 
133  EXPECT_NE(before.lambda(), after.lambda());
134  EXPECT_NE(before.param(), after.param());
136 
137  ss >> after;
138 
139  EXPECT_EQ(before.lambda(), after.lambda()) //
140  << ss.str() << " " //
141  << (ss.good() ? "good " : "") //
142  << (ss.bad() ? "bad " : "") //
143  << (ss.eof() ? "eof " : "") //
144  << (ss.fail() ? "fail " : "");
145  }
146 }
147 
148 // http://www.itl.nist.gov/div898/handbook/eda/section3/eda3667.htm
149 
150 class ExponentialModel {
151  public:
152  explicit ExponentialModel(double lambda)
153  : lambda_(lambda), beta_(1.0 / lambda) {}
154 
155  double lambda() const { return lambda_; }
156 
157  double mean() const { return beta_; }
158  double variance() const { return beta_ * beta_; }
159  double stddev() const { return std::sqrt(variance()); }
160  double skew() const { return 2; }
161  double kurtosis() const { return 6.0; }
162 
163  double CDF(double x) { return 1.0 - std::exp(-lambda_ * x); }
164 
165  // The inverse CDF, or PercentPoint function of the distribution
166  double InverseCDF(double p) {
167  ABSL_ASSERT(p >= 0.0);
168  ABSL_ASSERT(p < 1.0);
169  return -beta_ * std::log(1.0 - p);
170  }
171 
172  private:
173  const double lambda_;
174  const double beta_;
175 };
176 
177 struct Param {
178  double lambda;
179  double p_fail;
180  int trials;
181 };
182 
183 class ExponentialDistributionTests : public testing::TestWithParam<Param>,
184  public ExponentialModel {
185  public:
186  ExponentialDistributionTests() : ExponentialModel(GetParam().lambda) {}
187 
188  // SingleZTest provides a basic z-squared test of the mean vs. expected
189  // mean for data generated by the poisson distribution.
190  template <typename D>
191  bool SingleZTest(const double p, const size_t samples);
192 
193  // SingleChiSquaredTest provides a basic chi-squared test of the normal
194  // distribution.
195  template <typename D>
196  double SingleChiSquaredTest();
197 
198  // We use a fixed bit generator for distribution accuracy tests. This allows
199  // these tests to be deterministic, while still testing the qualify of the
200  // implementation.
202 };
203 
204 template <typename D>
205 bool ExponentialDistributionTests::SingleZTest(const double p,
206  const size_t samples) {
207  D dis(lambda());
208 
209  std::vector<double> data;
210  data.reserve(samples);
211  for (size_t i = 0; i < samples; i++) {
212  const double x = dis(rng_);
213  data.push_back(x);
214  }
215 
217  const double max_err = absl::random_internal::MaxErrorTolerance(p);
218  const double z = absl::random_internal::ZScore(mean(), m);
219  const bool pass = absl::random_internal::Near("z", z, 0.0, max_err);
220 
221  if (!pass) {
223  INFO, absl::StrFormat("p=%f max_err=%f\n"
224  " lambda=%f\n"
225  " mean=%f vs. %f\n"
226  " stddev=%f vs. %f\n"
227  " skewness=%f vs. %f\n"
228  " kurtosis=%f vs. %f\n"
229  " z=%f vs. 0",
230  p, max_err, lambda(), m.mean, mean(),
231  std::sqrt(m.variance), stddev(), m.skewness,
232  skew(), m.kurtosis, kurtosis(), z));
233  }
234  return pass;
235 }
236 
237 template <typename D>
238 double ExponentialDistributionTests::SingleChiSquaredTest() {
239  const size_t kSamples = 10000;
240  const int kBuckets = 50;
241 
242  // The InverseCDF is the percent point function of the distribution, and can
243  // be used to assign buckets roughly uniformly.
244  std::vector<double> cutoffs;
245  const double kInc = 1.0 / static_cast<double>(kBuckets);
246  for (double p = kInc; p < 1.0; p += kInc) {
247  cutoffs.push_back(InverseCDF(p));
248  }
249  if (cutoffs.back() != std::numeric_limits<double>::infinity()) {
250  cutoffs.push_back(std::numeric_limits<double>::infinity());
251  }
252 
253  D dis(lambda());
254 
255  std::vector<int32_t> counts(cutoffs.size(), 0);
256  for (int j = 0; j < kSamples; j++) {
257  const double x = dis(rng_);
258  auto it = std::upper_bound(cutoffs.begin(), cutoffs.end(), x);
259  counts[std::distance(cutoffs.begin(), it)]++;
260  }
261 
262  // Null-hypothesis is that the distribution is exponentially distributed
263  // with the provided lambda (not estimated from the data).
264  const int dof = static_cast<int>(counts.size()) - 1;
265 
266  // Our threshold for logging is 1-in-50.
267  const double threshold = absl::random_internal::ChiSquareValue(dof, 0.98);
268 
269  const double expected =
270  static_cast<double>(kSamples) / static_cast<double>(counts.size());
271 
273  std::begin(counts), std::end(counts), expected);
274  double p = absl::random_internal::ChiSquarePValue(chi_square, dof);
275 
276  if (chi_square > threshold) {
277  for (int i = 0; i < cutoffs.size(); i++) {
279  INFO, absl::StrFormat("%d : (%f) = %d", i, cutoffs[i], counts[i]));
280  }
281 
283  absl::StrCat("lambda ", lambda(), "\n", //
284  " expected ", expected, "\n", //
285  kChiSquared, " ", chi_square, " (", p, ")\n",
286  kChiSquared, " @ 0.98 = ", threshold));
287  }
288  return p;
289 }
290 
291 TEST_P(ExponentialDistributionTests, ZTest) {
292  const size_t kSamples = 10000;
293  const auto& param = GetParam();
294  const int expected_failures =
295  std::max(1, static_cast<int>(std::ceil(param.trials * param.p_fail)));
297  param.p_fail, param.trials);
298 
299  int failures = 0;
300  for (int i = 0; i < param.trials; i++) {
301  failures += SingleZTest<absl::exponential_distribution<double>>(p, kSamples)
302  ? 0
303  : 1;
304  }
305  EXPECT_LE(failures, expected_failures);
306 }
307 
308 TEST_P(ExponentialDistributionTests, ChiSquaredTest) {
309  const int kTrials = 20;
310  int failures = 0;
311 
312  for (int i = 0; i < kTrials; i++) {
313  double p_value =
314  SingleChiSquaredTest<absl::exponential_distribution<double>>();
315  if (p_value < 0.005) { // 1/200
316  failures++;
317  }
318  }
319 
320  // There is a 0.10% chance of producing at least one failure, so raise the
321  // failure threshold high enough to allow for a flake rate < 10,000.
322  EXPECT_LE(failures, 4);
323 }
324 
325 std::vector<Param> GenParams() {
326  return {
327  Param{1.0, 0.02, 100},
328  Param{2.5, 0.02, 100},
329  Param{10, 0.02, 100},
330  // large
331  Param{1e4, 0.02, 100},
332  Param{1e9, 0.02, 100},
333  // small
334  Param{0.1, 0.02, 100},
335  Param{1e-3, 0.02, 100},
336  Param{1e-5, 0.02, 100},
337  };
338 }
339 
340 std::string ParamName(const ::testing::TestParamInfo<Param>& info) {
341  const auto& p = info.param;
342  std::string name = absl::StrCat("lambda_", absl::SixDigits(p.lambda));
343  return absl::StrReplaceAll(name, {{"+", "_"}, {"-", "_"}, {".", "_"}});
344 }
345 
346 INSTANTIATE_TEST_SUITE_P(All, ExponentialDistributionTests,
347  ::testing::ValuesIn(GenParams()), ParamName);
348 
349 // NOTE: absl::exponential_distribution is not guaranteed to be stable.
350 TEST(ExponentialDistributionTest, StabilityTest) {
351  // absl::exponential_distribution stability relies on std::log1p and
352  // absl::uniform_real_distribution.
354  {0x0003eb76f6f7f755ull, 0xFFCEA50FDB2F953Bull, 0xC332DDEFBE6C5AA5ull,
355  0x6558218568AB9702ull, 0x2AEF7DAD5B6E2F84ull, 0x1521B62829076170ull,
356  0xECDD4775619F1510ull, 0x13CCA830EB61BD96ull, 0x0334FE1EAA0363CFull,
357  0xB5735C904C70A239ull, 0xD59E9E0BCBAADE14ull, 0xEECC86BC60622CA7ull});
358 
359  std::vector<int> output(14);
360 
361  {
364  [&] { return static_cast<int>(10000.0 * dist(urbg)); });
365 
366  EXPECT_EQ(14, urbg.invocations());
368  testing::ElementsAre(0, 71913, 14375, 5039, 1835, 861, 25936,
369  804, 126, 12337, 17984, 27002, 0, 71913));
370  }
371 
372  urbg.reset();
373  {
376  [&] { return static_cast<int>(10000.0f * dist(urbg)); });
377 
378  EXPECT_EQ(14, urbg.invocations());
380  testing::ElementsAre(0, 71913, 14375, 5039, 1835, 861, 25936,
381  804, 126, 12337, 17984, 27002, 0, 71913));
382  }
383 }
384 
385 TEST(ExponentialDistributionTest, AlgorithmBounds) {
386  // Relies on absl::uniform_real_distribution, so some of these comments
387  // reference that.
388 
389 #if (defined(__i386__) || defined(_M_IX86)) && FLT_EVAL_METHOD != 0
390  // We're using an x87-compatible FPU, and intermediate operations can be
391  // performed with 80-bit floats. This produces slightly different results from
392  // what we expect below.
393  GTEST_SKIP()
394  << "Skipping the test because we detected x87 floating-point semantics";
395 #endif
396 
398 
399  {
400  // This returns the smallest value >0 from absl::uniform_real_distribution.
401  absl::random_internal::sequence_urbg urbg({0x0000000000000001ull});
402  double a = dist(urbg);
403  EXPECT_EQ(a, 5.42101086242752217004e-20);
404  }
405 
406  {
407  // This returns a value very near 0.5 from absl::uniform_real_distribution.
408  absl::random_internal::sequence_urbg urbg({0x7fffffffffffffefull});
409  double a = dist(urbg);
410  EXPECT_EQ(a, 0.693147180559945175204);
411  }
412 
413  {
414  // This returns the largest value <1 from absl::uniform_real_distribution.
415  // WolframAlpha: ~39.1439465808987766283058547296341915292187253
416  absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFeFull});
417  double a = dist(urbg);
418  EXPECT_EQ(a, 36.7368005696771007251);
419  }
420  {
421  // This *ALSO* returns the largest value <1.
422  absl::random_internal::sequence_urbg urbg({0xFFFFFFFFFFFFFFFFull});
423  double a = dist(urbg);
424  EXPECT_EQ(a, 36.7368005696771007251);
425  }
426 }
427 
428 } // namespace
regen-readme.it
it
Definition: regen-readme.py:15
absl::str_format_internal::LengthMod::j
@ j
absl::StrCat
std::string StrCat(const AlphaNum &a, const AlphaNum &b)
Definition: abseil-cpp/absl/strings/str_cat.cc:98
absl::StrFormat
ABSL_MUST_USE_RESULT std::string StrFormat(const FormatSpec< Args... > &format, const Args &... args)
Definition: abseil-cpp/absl/strings/str_format.h:338
absl::random_internal::RequiredSuccessProbability
double RequiredSuccessProbability(const double p_fail, const int num_trials)
Definition: abseil-cpp/absl/random/internal/distribution_test_util.cc:397
begin
char * begin
Definition: abseil-cpp/absl/strings/internal/str_format/float_conversion.cc:1007
EXPECT_THAT
#define EXPECT_THAT(value, matcher)
absl::exponential_distribution
Definition: abseil-cpp/absl/random/exponential_distribution.h:36
testing::internal::string
::std::string string
Definition: bloaty/third_party/protobuf/third_party/googletest/googletest/include/gtest/internal/gtest-port.h:881
grpc_core::testing::Param
struct grpc_core::testing::Param Param
setup.name
name
Definition: setup.py:542
absl::random_internal::ZScore
double ZScore(double expected_mean, const DistributionMoments &moments)
Definition: abseil-cpp/absl/random/internal/distribution_test_util.cc:403
GTEST_SKIP
#define GTEST_SKIP()
Definition: perf_counters_gtest.cc:10
a
int a
Definition: abseil-cpp/absl/container/internal/hash_policy_traits_test.cc:88
EXPECT_LE
#define EXPECT_LE(val1, val2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2030
xds_manager.p
p
Definition: xds_manager.py:60
z
Uncopyable z
Definition: bloaty/third_party/googletest/googlemock/test/gmock-matchers_test.cc:3612
absl::random_internal::sequence_urbg
Definition: abseil-cpp/absl/random/internal/sequence_urbg.h:33
absl::random_internal::ChiSquareWithExpected
double ChiSquareWithExpected(Iterator begin, Iterator end, double expected)
Definition: abseil-cpp/absl/random/internal/chi_square.h:40
failures
std::atomic< uint64_t > failures
Definition: outlier_detection.cc:233
testing::Test
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:402
testing::TestWithParam
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:1883
absl::random_internal::ComputeDistributionMoments
DistributionMoments ComputeDistributionMoments(absl::Span< const double > data_points)
Definition: abseil-cpp/absl/random/internal/distribution_test_util.cc:39
EXPECT_EQ
#define EXPECT_EQ(a, b)
Definition: iomgr/time_averaged_stats_test.cc:27
testing::ElementsAre
internal::ElementsAreMatcher< ::testing::tuple<> > ElementsAre()
Definition: cares/cares/test/gmock-1.8.0/gmock/gmock.h:13040
before
IntBeforeRegisterTypedTestSuiteP before
Definition: googletest/googletest/test/gtest-typed-test_test.cc:376
testing::internal::ProxyTypeList
Definition: googletest/googletest/include/gtest/internal/gtest-type-util.h:155
absl::FormatConversionChar::e
@ e
autogen_x86imm.f
f
Definition: autogen_x86imm.py:9
end
char * end
Definition: abseil-cpp/absl/strings/internal/str_format/float_conversion.cc:1008
TEST
#define TEST(name, init_size,...)
Definition: arena_test.cc:75
max
int max
Definition: bloaty/third_party/zlib/examples/enough.c:170
gmock_output_test.output
output
Definition: bloaty/third_party/googletest/googlemock/test/gmock_output_test.py:175
TEST_P
#define TEST_P(test_suite_name, test_name)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest-param-test.h:414
python_utils.jobset.INFO
INFO
Definition: jobset.py:111
EXPECT_NE
#define EXPECT_NE(val1, val2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2028
TYPED_TEST
#define TYPED_TEST(CaseName, TestName)
Definition: googletest/googletest/include/gtest/gtest-typed-test.h:197
absl::random_internal::ChiSquarePValue
double ChiSquarePValue(double chi_square, int dof)
Definition: abseil-cpp/absl/random/internal/chi_square.cc:157
x
int x
Definition: bloaty/third_party/googletest/googlemock/test/gmock-matchers_test.cc:3610
data
char data[kBufferLength]
Definition: abseil-cpp/absl/strings/internal/str_format/float_conversion.cc:1006
absl::exponential_distribution::param_type
Definition: abseil-cpp/absl/random/exponential_distribution.h:40
gen
OPENSSL_EXPORT GENERAL_NAME * gen
Definition: x509v3.h:495
min
#define min(a, b)
Definition: qsort.h:83
absl::SixDigits
strings_internal::AlphaNumBuffer< numbers_internal::kSixDigitsToBufferSize > SixDigits(double d)
Definition: abseil-cpp/absl/strings/str_cat.h:405
after
IntAfterTypedTestSuiteP after
Definition: googletest/googletest/test/gtest-typed-test_test.cc:375
value
const char * value
Definition: hpack_parser_table.cc:165
abseil.generate
def generate(args)
Definition: abseil-cpp/absl/abseil.podspec.gen.py:200
rng_
std::mt19937 rng_
Definition: rls.cc:607
absl::random_internal::pcg_engine
Definition: abseil-cpp/absl/random/internal/pcg_engine.h:41
ABSL_ASSERT
#define ABSL_ASSERT(expr)
Definition: abseil-cpp/absl/base/macros.h:97
TYPED_TEST_SUITE
#define TYPED_TEST_SUITE(CaseName, Types,...)
Definition: googletest/googletest/include/gtest/gtest-typed-test.h:191
absl::random_internal::NonsecureURBGBase
Definition: abseil-cpp/absl/random/internal/nonsecure_base.h:96
absl::random_internal::MaxErrorTolerance
double MaxErrorTolerance(double acceptance_probability)
Definition: abseil-cpp/absl/random/internal/distribution_test_util.cc:409
absl::StrReplaceAll
std::string StrReplaceAll(absl::string_view s, strings_internal::FixedMapping replacements)
Definition: abseil-cpp/absl/strings/str_replace.cc:71
absl::random_internal::ChiSquareValue
double ChiSquareValue(int dof, double p)
Definition: abseil-cpp/absl/random/internal/chi_square.cc:106
log
bool log
Definition: abseil-cpp/absl/synchronization/mutex.cc:310
EXPECT_GE
#define EXPECT_GE(val1, val2)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest.h:2034
absl::numeric_internal::IsDoubleDouble
constexpr bool IsDoubleDouble()
Definition: abseil-cpp/absl/numeric/internal/representation.h:28
asyncio_get_stats.type
type
Definition: asyncio_get_stats.py:37
testing::ValuesIn
internal::ParamGenerator< typename std::iterator_traits< ForwardIterator >::value_type > ValuesIn(ForwardIterator begin, ForwardIterator end)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest-param-test.h:297
isfinite
#define isfinite
Definition: bloaty/third_party/protobuf/conformance/third_party/jsoncpp/jsoncpp.cpp:4014
absl::random_internal::kChiSquared
constexpr const char kChiSquared[]
Definition: abseil-cpp/absl/random/internal/chi_square.h:35
regress.m
m
Definition: regress/regress.py:25
ABSL_INTERNAL_LOG
#define ABSL_INTERNAL_LOG(severity, message)
Definition: abseil-cpp/absl/base/internal/raw_logging.h:75
absl::random_internal::Near
bool Near(absl::string_view msg, double actual, double expected, double bound)
Definition: abseil-cpp/absl/random/internal/distribution_test_util.cc:86
i
uint64_t i
Definition: abseil-cpp/absl/container/btree_benchmark.cc:230
INSTANTIATE_TEST_SUITE_P
#define INSTANTIATE_TEST_SUITE_P(prefix, test_suite_name,...)
Definition: bloaty/third_party/googletest/googletest/include/gtest/gtest-param-test.h:460


grpc
Author(s):
autogenerated on Fri May 16 2025 02:58:20