distribution_test_util.cc 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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 "y_absl/random/internal/distribution_test_util.h"
  15. #include <cassert>
  16. #include <cmath>
  17. #include <util/generic/string.h>
  18. #include <vector>
  19. #include "y_absl/base/internal/raw_logging.h"
  20. #include "y_absl/base/macros.h"
  21. #include "y_absl/strings/str_cat.h"
  22. #include "y_absl/strings/str_format.h"
  23. namespace y_absl {
  24. Y_ABSL_NAMESPACE_BEGIN
  25. namespace random_internal {
  26. namespace {
  27. #if defined(__EMSCRIPTEN__)
  28. // Workaround __EMSCRIPTEN__ error: llvm_fma_f64 not found.
  29. inline double fma(double x, double y, double z) { return (x * y) + z; }
  30. #endif
  31. } // namespace
  32. DistributionMoments ComputeDistributionMoments(
  33. y_absl::Span<const double> data_points) {
  34. DistributionMoments result;
  35. // Compute m1
  36. for (double x : data_points) {
  37. result.n++;
  38. result.mean += x;
  39. }
  40. result.mean /= static_cast<double>(result.n);
  41. // Compute m2, m3, m4
  42. for (double x : data_points) {
  43. double v = x - result.mean;
  44. result.variance += v * v;
  45. result.skewness += v * v * v;
  46. result.kurtosis += v * v * v * v;
  47. }
  48. result.variance /= static_cast<double>(result.n - 1);
  49. result.skewness /= static_cast<double>(result.n);
  50. result.skewness /= std::pow(result.variance, 1.5);
  51. result.kurtosis /= static_cast<double>(result.n);
  52. result.kurtosis /= std::pow(result.variance, 2.0);
  53. return result;
  54. // When validating the min/max count, the following confidence intervals may
  55. // be of use:
  56. // 3.291 * stddev = 99.9% CI
  57. // 2.576 * stddev = 99% CI
  58. // 1.96 * stddev = 95% CI
  59. // 1.65 * stddev = 90% CI
  60. }
  61. std::ostream& operator<<(std::ostream& os, const DistributionMoments& moments) {
  62. return os << y_absl::StrFormat("mean=%f, stddev=%f, skewness=%f, kurtosis=%f",
  63. moments.mean, std::sqrt(moments.variance),
  64. moments.skewness, moments.kurtosis);
  65. }
  66. double InverseNormalSurvival(double x) {
  67. // inv_sf(u) = -sqrt(2) * erfinv(2u-1)
  68. static constexpr double kSqrt2 = 1.4142135623730950488;
  69. return -kSqrt2 * y_absl::random_internal::erfinv(2 * x - 1.0);
  70. }
  71. bool Near(y_absl::string_view msg, double actual, double expected, double bound) {
  72. assert(bound > 0.0);
  73. double delta = fabs(expected - actual);
  74. if (delta < bound) {
  75. return true;
  76. }
  77. TString formatted = y_absl::StrCat(
  78. msg, " actual=", actual, " expected=", expected, " err=", delta / bound);
  79. Y_ABSL_RAW_LOG(INFO, "%s", formatted.c_str());
  80. return false;
  81. }
  82. // TODO(y_absl-team): Replace with an "Y_ABSL_HAVE_SPECIAL_MATH" and try
  83. // to use std::beta(). As of this writing P0226R1 is not implemented
  84. // in libc++: http://libcxx.llvm.org/cxx1z_status.html
  85. double beta(double p, double q) {
  86. // Beta(x, y) = Gamma(x) * Gamma(y) / Gamma(x+y)
  87. double lbeta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q);
  88. return std::exp(lbeta);
  89. }
  90. // Approximation to inverse of the Error Function in double precision.
  91. // (http://people.maths.ox.ac.uk/gilesm/files/gems_erfinv.pdf)
  92. double erfinv(double x) {
  93. #if !defined(__EMSCRIPTEN__)
  94. using std::fma;
  95. #endif
  96. double w = 0.0;
  97. double p = 0.0;
  98. w = -std::log((1.0 - x) * (1.0 + x));
  99. if (w < 6.250000) {
  100. w = w - 3.125000;
  101. p = -3.6444120640178196996e-21;
  102. p = fma(p, w, -1.685059138182016589e-19);
  103. p = fma(p, w, 1.2858480715256400167e-18);
  104. p = fma(p, w, 1.115787767802518096e-17);
  105. p = fma(p, w, -1.333171662854620906e-16);
  106. p = fma(p, w, 2.0972767875968561637e-17);
  107. p = fma(p, w, 6.6376381343583238325e-15);
  108. p = fma(p, w, -4.0545662729752068639e-14);
  109. p = fma(p, w, -8.1519341976054721522e-14);
  110. p = fma(p, w, 2.6335093153082322977e-12);
  111. p = fma(p, w, -1.2975133253453532498e-11);
  112. p = fma(p, w, -5.4154120542946279317e-11);
  113. p = fma(p, w, 1.051212273321532285e-09);
  114. p = fma(p, w, -4.1126339803469836976e-09);
  115. p = fma(p, w, -2.9070369957882005086e-08);
  116. p = fma(p, w, 4.2347877827932403518e-07);
  117. p = fma(p, w, -1.3654692000834678645e-06);
  118. p = fma(p, w, -1.3882523362786468719e-05);
  119. p = fma(p, w, 0.0001867342080340571352);
  120. p = fma(p, w, -0.00074070253416626697512);
  121. p = fma(p, w, -0.0060336708714301490533);
  122. p = fma(p, w, 0.24015818242558961693);
  123. p = fma(p, w, 1.6536545626831027356);
  124. } else if (w < 16.000000) {
  125. w = std::sqrt(w) - 3.250000;
  126. p = 2.2137376921775787049e-09;
  127. p = fma(p, w, 9.0756561938885390979e-08);
  128. p = fma(p, w, -2.7517406297064545428e-07);
  129. p = fma(p, w, 1.8239629214389227755e-08);
  130. p = fma(p, w, 1.5027403968909827627e-06);
  131. p = fma(p, w, -4.013867526981545969e-06);
  132. p = fma(p, w, 2.9234449089955446044e-06);
  133. p = fma(p, w, 1.2475304481671778723e-05);
  134. p = fma(p, w, -4.7318229009055733981e-05);
  135. p = fma(p, w, 6.8284851459573175448e-05);
  136. p = fma(p, w, 2.4031110387097893999e-05);
  137. p = fma(p, w, -0.0003550375203628474796);
  138. p = fma(p, w, 0.00095328937973738049703);
  139. p = fma(p, w, -0.0016882755560235047313);
  140. p = fma(p, w, 0.0024914420961078508066);
  141. p = fma(p, w, -0.0037512085075692412107);
  142. p = fma(p, w, 0.005370914553590063617);
  143. p = fma(p, w, 1.0052589676941592334);
  144. p = fma(p, w, 3.0838856104922207635);
  145. } else {
  146. w = std::sqrt(w) - 5.000000;
  147. p = -2.7109920616438573243e-11;
  148. p = fma(p, w, -2.5556418169965252055e-10);
  149. p = fma(p, w, 1.5076572693500548083e-09);
  150. p = fma(p, w, -3.7894654401267369937e-09);
  151. p = fma(p, w, 7.6157012080783393804e-09);
  152. p = fma(p, w, -1.4960026627149240478e-08);
  153. p = fma(p, w, 2.9147953450901080826e-08);
  154. p = fma(p, w, -6.7711997758452339498e-08);
  155. p = fma(p, w, 2.2900482228026654717e-07);
  156. p = fma(p, w, -9.9298272942317002539e-07);
  157. p = fma(p, w, 4.5260625972231537039e-06);
  158. p = fma(p, w, -1.9681778105531670567e-05);
  159. p = fma(p, w, 7.5995277030017761139e-05);
  160. p = fma(p, w, -0.00021503011930044477347);
  161. p = fma(p, w, -0.00013871931833623122026);
  162. p = fma(p, w, 1.0103004648645343977);
  163. p = fma(p, w, 4.8499064014085844221);
  164. }
  165. return p * x;
  166. }
  167. namespace {
  168. // Direct implementation of AS63, BETAIN()
  169. // https://www.jstor.org/stable/2346797?seq=3#page_scan_tab_contents.
  170. //
  171. // BETAIN(x, p, q, beta)
  172. // x: the value of the upper limit x.
  173. // p: the value of the parameter p.
  174. // q: the value of the parameter q.
  175. // beta: the value of ln B(p, q)
  176. //
  177. double BetaIncompleteImpl(const double x, const double p, const double q,
  178. const double beta) {
  179. if (p < (p + q) * x) {
  180. // Incomplete beta function is symmetrical, so return the complement.
  181. return 1. - BetaIncompleteImpl(1.0 - x, q, p, beta);
  182. }
  183. double psq = p + q;
  184. const double kErr = 1e-14;
  185. const double xc = 1. - x;
  186. const double pre =
  187. std::exp(p * std::log(x) + (q - 1.) * std::log(xc) - beta) / p;
  188. double term = 1.;
  189. double ai = 1.;
  190. double result = 1.;
  191. int ns = static_cast<int>(q + xc * psq);
  192. // Use the soper reduction formula.
  193. double rx = (ns == 0) ? x : x / xc;
  194. double temp = q - ai;
  195. for (;;) {
  196. term = term * temp * rx / (p + ai);
  197. result = result + term;
  198. temp = std::fabs(term);
  199. if (temp < kErr && temp < kErr * result) {
  200. return result * pre;
  201. }
  202. ai = ai + 1.;
  203. --ns;
  204. if (ns >= 0) {
  205. temp = q - ai;
  206. if (ns == 0) {
  207. rx = x;
  208. }
  209. } else {
  210. temp = psq;
  211. psq = psq + 1.;
  212. }
  213. }
  214. // NOTE: See also TOMS Algorithm 708.
  215. // http://www.netlib.org/toms/index.html
  216. //
  217. // NOTE: The NWSC library also includes BRATIO / ISUBX (p87)
  218. // https://archive.org/details/DTIC_ADA261511/page/n75
  219. }
  220. // Direct implementation of AS109, XINBTA(p, q, beta, alpha)
  221. // https://www.jstor.org/stable/2346798?read-now=1&seq=4#page_scan_tab_contents
  222. // https://www.jstor.org/stable/2346887?seq=1#page_scan_tab_contents
  223. //
  224. // XINBTA(p, q, beta, alpha)
  225. // p: the value of the parameter p.
  226. // q: the value of the parameter q.
  227. // beta: the value of ln B(p, q)
  228. // alpha: the value of the lower tail area.
  229. //
  230. double BetaIncompleteInvImpl(const double p, const double q, const double beta,
  231. const double alpha) {
  232. if (alpha < 0.5) {
  233. // Inverse Incomplete beta function is symmetrical, return the complement.
  234. return 1. - BetaIncompleteInvImpl(q, p, beta, 1. - alpha);
  235. }
  236. const double kErr = 1e-14;
  237. double value = kErr;
  238. // Compute the initial estimate.
  239. {
  240. double r = std::sqrt(-std::log(alpha * alpha));
  241. double y =
  242. r - fma(r, 0.27061, 2.30753) / fma(r, fma(r, 0.04481, 0.99229), 1.0);
  243. if (p > 1. && q > 1.) {
  244. r = (y * y - 3.) / 6.;
  245. double s = 1. / (p + p - 1.);
  246. double t = 1. / (q + q - 1.);
  247. double h = 2. / s + t;
  248. double w =
  249. y * std::sqrt(h + r) / h - (t - s) * (r + 5. / 6. - t / (3. * h));
  250. value = p / (p + q * std::exp(w + w));
  251. } else {
  252. r = q + q;
  253. double t = 1.0 / (9. * q);
  254. double u = 1.0 - t + y * std::sqrt(t);
  255. t = r * (u * u * u);
  256. if (t <= 0) {
  257. value = 1.0 - std::exp((std::log((1.0 - alpha) * q) + beta) / q);
  258. } else {
  259. t = (4.0 * p + r - 2.0) / t;
  260. if (t <= 1) {
  261. value = std::exp((std::log(alpha * p) + beta) / p);
  262. } else {
  263. value = 1.0 - 2.0 / (t + 1.0);
  264. }
  265. }
  266. }
  267. }
  268. // Solve for x using a modified newton-raphson method using the function
  269. // BetaIncomplete.
  270. {
  271. value = std::max(value, kErr);
  272. value = std::min(value, 1.0 - kErr);
  273. const double r = 1.0 - p;
  274. const double t = 1.0 - q;
  275. double y;
  276. double yprev = 0;
  277. double sq = 1;
  278. double prev = 1;
  279. for (;;) {
  280. if (value < 0 || value > 1.0) {
  281. // Error case; value went infinite.
  282. return std::numeric_limits<double>::infinity();
  283. } else if (value == 0 || value == 1) {
  284. y = value;
  285. } else {
  286. y = BetaIncompleteImpl(value, p, q, beta);
  287. if (!std::isfinite(y)) {
  288. return y;
  289. }
  290. }
  291. y = (y - alpha) *
  292. std::exp(beta + r * std::log(value) + t * std::log(1.0 - value));
  293. if (y * yprev <= 0) {
  294. prev = std::max(sq, std::numeric_limits<double>::min());
  295. }
  296. double g = 1.0;
  297. for (;;) {
  298. const double adj = g * y;
  299. const double adj_sq = adj * adj;
  300. if (adj_sq >= prev) {
  301. g = g / 3.0;
  302. continue;
  303. }
  304. const double tx = value - adj;
  305. if (tx < 0 || tx > 1) {
  306. g = g / 3.0;
  307. continue;
  308. }
  309. if (prev < kErr) {
  310. return value;
  311. }
  312. if (y * y < kErr) {
  313. return value;
  314. }
  315. if (tx == value) {
  316. return value;
  317. }
  318. if (tx == 0 || tx == 1) {
  319. g = g / 3.0;
  320. continue;
  321. }
  322. value = tx;
  323. yprev = y;
  324. break;
  325. }
  326. }
  327. }
  328. // NOTES: See also: Asymptotic inversion of the incomplete beta function.
  329. // https://core.ac.uk/download/pdf/82140723.pdf
  330. //
  331. // NOTE: See the Boost library documentation as well:
  332. // https://www.boost.org/doc/libs/1_52_0/libs/math/doc/sf_and_dist/html/math_toolkit/special/sf_beta/ibeta_function.html
  333. }
  334. } // namespace
  335. double BetaIncomplete(const double x, const double p, const double q) {
  336. // Error cases.
  337. if (p < 0 || q < 0 || x < 0 || x > 1.0) {
  338. return std::numeric_limits<double>::infinity();
  339. }
  340. if (x == 0 || x == 1) {
  341. return x;
  342. }
  343. // ln(Beta(p, q))
  344. double beta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q);
  345. return BetaIncompleteImpl(x, p, q, beta);
  346. }
  347. double BetaIncompleteInv(const double p, const double q, const double alpha) {
  348. // Error cases.
  349. if (p < 0 || q < 0 || alpha < 0 || alpha > 1.0) {
  350. return std::numeric_limits<double>::infinity();
  351. }
  352. if (alpha == 0 || alpha == 1) {
  353. return alpha;
  354. }
  355. // ln(Beta(p, q))
  356. double beta = std::lgamma(p) + std::lgamma(q) - std::lgamma(p + q);
  357. return BetaIncompleteInvImpl(p, q, beta, alpha);
  358. }
  359. // Given `num_trials` trials each with probability `p` of success, the
  360. // probability of no failures is `p^k`. To ensure the probability of a failure
  361. // is no more than `p_fail`, it must be that `p^k == 1 - p_fail`. This function
  362. // computes `p` from that equation.
  363. double RequiredSuccessProbability(const double p_fail, const int num_trials) {
  364. double p = std::exp(std::log(1.0 - p_fail) / static_cast<double>(num_trials));
  365. Y_ABSL_ASSERT(p > 0);
  366. return p;
  367. }
  368. double ZScore(double expected_mean, const DistributionMoments& moments) {
  369. return (moments.mean - expected_mean) /
  370. (std::sqrt(moments.variance) /
  371. std::sqrt(static_cast<double>(moments.n)));
  372. }
  373. double MaxErrorTolerance(double acceptance_probability) {
  374. double one_sided_pvalue = 0.5 * (1.0 - acceptance_probability);
  375. const double max_err = InverseNormalSurvival(one_sided_pvalue);
  376. Y_ABSL_ASSERT(max_err > 0);
  377. return max_err;
  378. }
  379. } // namespace random_internal
  380. Y_ABSL_NAMESPACE_END
  381. } // namespace y_absl