Generator.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. /*
  2. * Copyright (c) 2023, Martin Janiczek <martin@janiczek.cz>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <LibTest/Macros.h>
  8. #include <LibTest/Randomized/RandomRun.h>
  9. #include <AK/Function.h>
  10. #include <AK/Random.h>
  11. #include <AK/String.h>
  12. #include <AK/StringView.h>
  13. #include <math.h>
  14. namespace Test {
  15. namespace Randomized {
  16. // Returns a random double value in range 0..1.
  17. // This is not a generator. It is meant to be used inside RandomnessSource::draw_value().
  18. // Based on: https://dotat.at/@/2023-06-23-random-double.html
  19. inline f64 get_random_probability()
  20. {
  21. return static_cast<f64>(AK::get_random<u64>() >> 11) * 0x1.0p-53;
  22. }
  23. // Generators take random bits from the RandomnessSource and return a value
  24. // back.
  25. //
  26. // Example:
  27. // - Gen::number_u64(5,10) --> 9, 7, 5, 10, 8, ...
  28. namespace Gen {
  29. // An unsigned integer generator.
  30. //
  31. // The minimum value will always be 0.
  32. // The maximum value is given by user in the argument.
  33. //
  34. // Gen::number_u64(10) -> value 5, RandomRun [5]
  35. // -> value 8, RandomRun [8]
  36. // etc.
  37. //
  38. // Shrinks towards 0.
  39. inline u64 number_u64(u64 max)
  40. {
  41. if (max == 0)
  42. return 0;
  43. u64 random = Test::randomness_source().draw_value(max, [&]() {
  44. // `clamp` to guard against integer overflow
  45. u64 exclusive_bound = AK::clamp(max + 1, max, NumericLimits<u64>::max());
  46. return AK::get_random_uniform_64(exclusive_bound);
  47. });
  48. return random;
  49. }
  50. // An unsigned integer generator in a particular range.
  51. //
  52. // Gen::number_u64(3,10) -> value 3, RandomRun [0]
  53. // -> value 8, RandomRun [5]
  54. // -> value 10, RandomRun [7]
  55. // etc.
  56. //
  57. // In case `min == max`, the RandomRun footprint will be smaller: no randomness
  58. // is needed.
  59. //
  60. // Gen::number_u64(3,3) -> value 3, RandomRun [] (always)
  61. //
  62. // Shrinks towards the minimum.
  63. inline u64 number_u64(u64 min, u64 max)
  64. {
  65. VERIFY(max >= min);
  66. return number_u64(max - min) + min;
  67. }
  68. // Randomly (uniformly) selects a value out of the given arguments.
  69. //
  70. // Gen::one_of(20,5,10) --> value 20, RandomRun [0]
  71. // --> value 5, RandomRun [1]
  72. // --> value 10, RandomRun [2]
  73. //
  74. // Shrinks towards the earlier arguments (above, towards 20).
  75. template<typename... Ts>
  76. requires(sizeof...(Ts) > 0)
  77. CommonType<Ts...> one_of(Ts... choices)
  78. {
  79. Vector<CommonType<Ts...>> choices_vec { choices... };
  80. constexpr size_t count = sizeof...(choices);
  81. size_t i = number_u64(count - 1);
  82. return choices_vec[i];
  83. }
  84. template<typename T>
  85. struct Choice {
  86. i32 weight;
  87. T value;
  88. };
  89. // Workaround for clang bug fixed in clang 17
  90. template<typename T>
  91. Choice(i32, T) -> Choice<T>;
  92. // Randomly (uniformly) selects a value out of the given weighted arguments.
  93. //
  94. // Gen::frequency(
  95. // Gen::Choice {5,999},
  96. // Gen::Choice {1,111},
  97. // )
  98. // --> value 999 (5 out of 6 times), RandomRun [0]
  99. // --> value 111 (1 out of 6 times), RandomRun [1]
  100. //
  101. // Shrinks towards the earlier arguments (above, towards 'x').
  102. template<typename... Ts>
  103. requires(sizeof...(Ts) > 0)
  104. CommonType<Ts...> frequency(Choice<Ts>... choices)
  105. {
  106. Vector<Choice<CommonType<Ts...>>> choices_vec { choices... };
  107. u64 sum = 0;
  108. for (auto const& choice : choices_vec) {
  109. VERIFY(choice.weight > 0);
  110. sum += static_cast<u64>(choice.weight);
  111. }
  112. u64 target = number_u64(sum);
  113. size_t i = 0;
  114. for (auto const& choice : choices_vec) {
  115. u64 weight = static_cast<u64>(choice.weight);
  116. if (weight >= target) {
  117. return choice.value;
  118. }
  119. target -= weight;
  120. ++i;
  121. }
  122. return choices_vec[i - 1].value;
  123. }
  124. // An unsigned integer generator in the full u64 range.
  125. //
  126. // Prefers 8bit numbers, then 4bit, 16bit, 32bit and 64bit ones.
  127. // Around 11% of the time it tries edge cases like 0 and various NumericLimits::max().
  128. //
  129. // Gen::number_u64() -> value 3, RandomRun [0,3]
  130. // -> value 8, RandomRun [1,8]
  131. // -> value 100, RandomRun [2,100]
  132. // -> value 5, RandomRun [3,5]
  133. // -> value 255, RandomRun [4,1]
  134. // -> value 65535, RandomRun [4,2]
  135. // etc.
  136. //
  137. // Shrinks towards 0.
  138. inline u64 number_u64()
  139. {
  140. u64 bits = frequency(
  141. // weight, bits
  142. Choice { 4, 4 },
  143. Choice { 8, 8 },
  144. Choice { 2, 16 },
  145. Choice { 1, 32 },
  146. Choice { 1, 64 },
  147. Choice { 2, 0 });
  148. // The special cases go last as they can be the most extreme (large) values.
  149. if (bits == 0) {
  150. // Special cases, eg. max integers for u8, u16, u32, u64.
  151. return one_of(
  152. 0U,
  153. NumericLimits<u8>::max(),
  154. NumericLimits<u16>::max(),
  155. NumericLimits<u32>::max(),
  156. NumericLimits<u64>::max());
  157. }
  158. u64 max = bits == 64
  159. ? NumericLimits<u64>::max()
  160. : ((u64)1 << bits) - 1;
  161. return number_u64(max);
  162. }
  163. // A generator returning `true` with the given `probability` (0..1).
  164. //
  165. // If probability <= 0, doesn't use any randomness and returns false.
  166. // If probability >= 1, doesn't use any randomness and returns true.
  167. //
  168. // In general case:
  169. // Gen::weighted_boolean(0.75)
  170. // -> value false, RandomRun [0]
  171. // -> value true, RandomRun [1]
  172. //
  173. // Shrinks towards false.
  174. inline bool weighted_boolean(f64 probability)
  175. {
  176. if (probability <= 0)
  177. return false;
  178. if (probability >= 1)
  179. return true;
  180. u64 random_int = Test::randomness_source().draw_value(1, [&]() {
  181. f64 drawn_probability = get_random_probability();
  182. return drawn_probability <= probability ? 1 : 0;
  183. });
  184. bool random_bool = random_int == 1;
  185. return random_bool;
  186. }
  187. // A (fair) boolean generator.
  188. //
  189. // Gen::boolean()
  190. // -> value false, RandomRun [0]
  191. // -> value true, RandomRun [1]
  192. //
  193. // Shrinks towards false.
  194. inline bool boolean()
  195. {
  196. return weighted_boolean(0.5);
  197. }
  198. // A vector generator of a random length between the given limits.
  199. //
  200. // Gen::vector(2,3,[]() { return Gen::number_u64(5); })
  201. // -> value [1,5], RandomRun [1,1,1,5,0]
  202. // -> value [1,5,0], RandomRun [1,1,1,5,1,0,0]
  203. // etc.
  204. //
  205. // In case `min == max`, the RandomRun footprint will be smaller, as there will
  206. // be no randomness involved in figuring out the length:
  207. //
  208. // Gen::vector(3,3,[]() { return Gen::number_u64(5); })
  209. // -> value [1,3], RandomRun [1,3]
  210. // -> value [5,2], RandomRun [5,2]
  211. // etc.
  212. //
  213. // Shrinks towards shorter vectors, with simpler elements inside.
  214. template<typename Fn>
  215. inline Vector<InvokeResult<Fn>> vector(size_t min, size_t max, Fn item_gen)
  216. {
  217. VERIFY(max >= min);
  218. size_t size = 0;
  219. Vector<InvokeResult<Fn>> acc;
  220. // Special case: no randomness for the boolean
  221. if (min == max) {
  222. while (size < min) {
  223. acc.append(item_gen());
  224. ++size;
  225. }
  226. return acc;
  227. }
  228. // General case: before each item we "flip a coin" to decide whether to
  229. // generate another one.
  230. //
  231. // This algorithm is used instead of the more intuitive "generate length,
  232. // then generate that many items" algorithm, because it produces RandomRun
  233. // patterns that shrink more easily.
  234. //
  235. // See the Hypothesis paper [1], section 3.3, around the paragraph starting
  236. // with "More commonly".
  237. //
  238. // [1]: https://drops.dagstuhl.de/opus/volltexte/2020/13170/pdf/LIPIcs-ECOOP-2020-13.pdf
  239. while (size < min) {
  240. acc.append(item_gen());
  241. ++size;
  242. }
  243. f64 average = static_cast<f64>(min + max) / 2.0;
  244. VERIFY(average > 0);
  245. // A geometric distribution: https://en.wikipedia.org/wiki/Geometric_distribution#Moments_and_cumulants
  246. // The below derives from the E(X) = 1/p formula.
  247. //
  248. // We need to flip the `p` to `1-p` as our success ("another item!") is
  249. // a "failure" in the geometric distribution's interpretation ("we fail X
  250. // times before succeeding the first time").
  251. //
  252. // That gives us `1 - 1/p`. Then, E(X) also contains the final success, so we
  253. // need to say `1 + average` instead of `average`, as it will mean "our X
  254. // items + the final failure that stops the process".
  255. f64 probability = 1.0 - 1.0 / (1.0 + average);
  256. while (size < max) {
  257. if (weighted_boolean(probability)) {
  258. acc.append(item_gen());
  259. ++size;
  260. } else {
  261. break;
  262. }
  263. }
  264. return acc;
  265. }
  266. // A vector generator of a given length.
  267. //
  268. // Gen::vector_of_length(3,[]() { return Gen::number_u64(5); })
  269. // -> value [1,5,0], RandomRun [1,1,1,5,1,0,0]
  270. // -> value [2,9,3], RandomRun [1,2,1,9,1,3,0]
  271. // etc.
  272. //
  273. // Shrinks towards shorter vectors, with simpler elements inside.
  274. template<typename Fn>
  275. inline Vector<InvokeResult<Fn>> vector(size_t length, Fn item_gen)
  276. {
  277. return vector(length, length, item_gen);
  278. }
  279. // A vector generator of a random length between 0 and 32 elements.
  280. //
  281. // If you need a different length, use vector(max,item_gen) or
  282. // vector(min,max,item_gen).
  283. //
  284. // Gen::vector([]() { return Gen::number_u64(5); })
  285. // -> value [], RandomRun [0]
  286. // -> value [1], RandomRun [1,1,0]
  287. // -> value [1,5], RandomRun [1,1,1,5,0]
  288. // -> value [1,5,0], RandomRun [1,1,1,5,1,0,0]
  289. // -> value [1,5,0,2], RandomRun [1,1,1,5,1,0,1,2,0]
  290. // etc.
  291. //
  292. // Shrinks towards shorter vectors, with simpler elements inside.
  293. template<typename Fn>
  294. inline Vector<InvokeResult<Fn>> vector(Fn item_gen)
  295. {
  296. return vector(0, 32, item_gen);
  297. }
  298. // A double generator in the [0,1) range.
  299. //
  300. // RandomRun footprint: a single number.
  301. //
  302. // Shrinks towards 0.
  303. //
  304. // Based on: https://dotat.at/@/2023-06-23-random-double.html
  305. inline f64 percentage()
  306. {
  307. return static_cast<f64>(number_u64() >> 11) * 0x1.0p-53;
  308. }
  309. // An internal double generator. This one won't make any attempt to shrink nicely.
  310. // Test writers should use number_f64(f64 min, f64 max) instead.
  311. inline f64 number_f64_scaled(f64 min, f64 max)
  312. {
  313. VERIFY(max >= min);
  314. if (min == max)
  315. return min;
  316. f64 p = percentage();
  317. return min * (1.0 - p) + max * p;
  318. }
  319. inline f64 number_f64(f64 min, f64 max)
  320. {
  321. // FIXME: after we figure out how to use frequency() with lambdas,
  322. // do edge cases and nicely shrinking float generators here
  323. return number_f64_scaled(min, max);
  324. }
  325. inline f64 number_f64()
  326. {
  327. // FIXME: this could be much nicer to the user, at the expense of code complexity
  328. // We could follow Hypothesis' lead and remap integers 0..MAXINT to _simple_
  329. // floats rather than small floats. Meaning, we would like to prefer integers
  330. // over floats with decimal digits, positive numbers over negative numbers etc.
  331. // As a result, users would get failures with floats like 0, 1, or 0.5 instead of
  332. // ones like 1.175494e-38.
  333. // Check the doc comment in Hypothesis: https://github.com/HypothesisWorks/hypothesis/blob/master/hypothesis-python/src/hypothesis/internal/conjecture/floats.py
  334. return number_f64(NumericLimits<f64>::lowest(), NumericLimits<f64>::max());
  335. }
  336. // A double generator.
  337. //
  338. // The minimum value will always be NumericLimits<f64>::lowest().
  339. // The maximum value is given by user in the argument.
  340. //
  341. // Prefers positive numbers, then negative numbers, then edge cases.
  342. //
  343. // Shrinks towards 0.
  344. inline f64 number_f64(f64 max)
  345. {
  346. // FIXME: after we figure out how to use frequency() with lambdas,
  347. // do edge cases and nicely shrinking float generators here
  348. return number_f64_scaled(NumericLimits<f64>::lowest(), max);
  349. }
  350. // TODO
  351. inline u32 number_u32(u32 max)
  352. {
  353. if (max == 0)
  354. return 0;
  355. u32 random = Test::randomness_source().draw_value(max, [&]() {
  356. // `clamp` to guard against integer overflow
  357. u32 exclusive_bound = AK::clamp(max + 1, max, NumericLimits<u32>::max());
  358. return AK::get_random_uniform(exclusive_bound);
  359. });
  360. return random;
  361. }
  362. // TODO
  363. inline u32 number_u32(u32 min, u32 max)
  364. {
  365. VERIFY(max >= min);
  366. return number_u32(max - min) + min;
  367. }
  368. // TODO
  369. inline u32 number_u32()
  370. {
  371. u32 bits = frequency(
  372. // weight, bits
  373. Choice { 4, 4 },
  374. Choice { 8, 8 },
  375. Choice { 2, 16 },
  376. Choice { 1, 32 },
  377. Choice { 1, 64 },
  378. Choice { 2, 0 });
  379. // The special cases go last as they can be the most extreme (large) values.
  380. if (bits == 0) {
  381. // Special cases, eg. max integers for u8, u16, u32.
  382. return one_of(
  383. 0U,
  384. NumericLimits<u8>::max(),
  385. NumericLimits<u16>::max(),
  386. NumericLimits<u32>::max());
  387. }
  388. u32 max = bits == 32
  389. ? NumericLimits<u32>::max()
  390. : ((u32)1 << bits) - 1;
  391. return number_u32(max);
  392. }
  393. } // namespace Gen
  394. } // namespace Randomized
  395. } // namespace Test