Generator.h 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  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 <AK/Tuple.h>
  14. namespace Test {
  15. namespace Randomized {
  16. // Returns a random double value in range 0..1.
  17. inline double get_random_probability()
  18. {
  19. static constexpr u32 max_u32 = NumericLimits<u32>::max();
  20. u32 random_u32 = AK::get_random_uniform(max_u32);
  21. return static_cast<double>(random_u32) / static_cast<double>(max_u32);
  22. }
  23. // Generators take random bits from the RandomnessSource and return a value
  24. // back.
  25. //
  26. // Example:
  27. // - Gen::u32(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::unsigned_int(10) -> value 5, RandomRun [5]
  35. // -> value 8, RandomRun [8]
  36. // etc.
  37. //
  38. // Shrinks towards 0.
  39. inline u32 unsigned_int(u32 max)
  40. {
  41. u32 random = Test::randomness_source().draw_value(max, [&]() {
  42. return AK::get_random_uniform(max + 1);
  43. });
  44. return random;
  45. }
  46. // An unsigned integer generator in a particular range.
  47. //
  48. // Gen::unsigned_int(3,10) -> value 3, RandomRun [0]
  49. // -> value 8, RandomRun [5]
  50. // -> value 10, RandomRun [7]
  51. // etc.
  52. //
  53. // In case `min == max`, the RandomRun footprint will be smaller, as we'll
  54. // switch to a `constant` and won't need any randomness to generate that
  55. // value:
  56. //
  57. // Gen::unsigned_int(3,3) -> value 3, RandomRun [] (always)
  58. //
  59. // Shrinks towards the smaller argument.
  60. inline u32 unsigned_int(u32 min, u32 max)
  61. {
  62. VERIFY(max >= min);
  63. if (min == max) {
  64. return min;
  65. }
  66. return unsigned_int(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 = unsigned_int(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. u32 sum = 0;
  108. for (auto const& choice : choices_vec) {
  109. VERIFY(choice.weight > 0);
  110. sum += static_cast<u32>(choice.weight);
  111. }
  112. u32 target = unsigned_int(sum);
  113. size_t i = 0;
  114. for (auto const& choice : choices_vec) {
  115. u32 weight = static_cast<u32>(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 u32 range.
  125. //
  126. // 8/17 (47%) of the time it will bias towards 8bit numbers,
  127. // 4/17 (23%) towards 4bit numbers,
  128. // 2/17 (12%) towards 16bit numbers,
  129. // 1/17 (6%) towards 32bit numbers,
  130. // 2/17 (12%) towards edge cases like 0 and NumericLimits::max() of various unsigned int types.
  131. //
  132. // Gen::unsigned_int() -> value 3, RandomRun [0,3]
  133. // -> value 8, RandomRun [1,8]
  134. // -> value 100, RandomRun [2,100]
  135. // -> value 5, RandomRun [3,5]
  136. // -> value 255, RandomRun [4,1]
  137. // -> value 65535, RandomRun [4,2]
  138. // etc.
  139. //
  140. // Shrinks towards 0.
  141. inline u32 unsigned_int()
  142. {
  143. u32 bits = frequency(
  144. // weight, bits
  145. Choice { 4, 4 },
  146. Choice { 8, 8 },
  147. Choice { 2, 16 },
  148. Choice { 1, 32 },
  149. Choice { 2, 0 });
  150. // The special cases go last as they can be the most extreme (large) values.
  151. if (bits == 0) {
  152. // Special cases, eg. max integers for u8, u16, u32.
  153. return one_of(
  154. 0U,
  155. NumericLimits<u8>::max(),
  156. NumericLimits<u16>::max(),
  157. NumericLimits<u32>::max());
  158. }
  159. u32 max = (bits == 32)
  160. ? NumericLimits<u32>::max()
  161. : ((u64)1 << bits) - 1;
  162. return unsigned_int(max);
  163. }
  164. // A generator returning `true` with the given `probability` (0..1).
  165. //
  166. // If probability <= 0, doesn't use any randomness and returns false.
  167. // If probability >= 1, doesn't use any randomness and returns true.
  168. //
  169. // In general case:
  170. // Gen::weighted_boolean(0.75)
  171. // -> value false, RandomRun [0]
  172. // -> value true, RandomRun [1]
  173. //
  174. // Shrinks towards false.
  175. inline bool weighted_boolean(double probability)
  176. {
  177. if (probability <= 0)
  178. return false;
  179. if (probability >= 1)
  180. return true;
  181. u32 random_int = Test::randomness_source().draw_value(1, [&]() {
  182. double drawn_probability = get_random_probability();
  183. return drawn_probability <= probability ? 1 : 0;
  184. });
  185. bool random_bool = random_int == 1;
  186. return random_bool;
  187. }
  188. // A (fair) boolean generator.
  189. //
  190. // Gen::boolean()
  191. // -> value false, RandomRun [0]
  192. // -> value true, RandomRun [1]
  193. //
  194. // Shrinks towards false.
  195. inline bool boolean()
  196. {
  197. return weighted_boolean(0.5);
  198. }
  199. // A vector generator of a random length between the given limits.
  200. //
  201. // Gen::vector(2,3,[]() { return Gen::unsigned_int(5); })
  202. // -> value [1,5], RandomRun [1,1,1,5,0]
  203. // -> value [1,5,0], RandomRun [1,1,1,5,1,0,0]
  204. // etc.
  205. //
  206. // In case `min == max`, the RandomRun footprint will be smaller, as there will
  207. // be no randomness involved in figuring out the length:
  208. //
  209. // Gen::vector(3,3,[]() { return Gen::unsigned_int(5); })
  210. // -> value [1,3], RandomRun [1,3]
  211. // -> value [5,2], RandomRun [5,2]
  212. // etc.
  213. //
  214. // Shrinks towards shorter vectors, with simpler elements inside.
  215. template<typename Fn>
  216. inline Vector<InvokeResult<Fn>> vector(size_t min, size_t max, Fn item_gen)
  217. {
  218. VERIFY(max >= min);
  219. size_t size = 0;
  220. Vector<InvokeResult<Fn>> acc;
  221. // Special case: no randomness for the boolean
  222. if (min == max) {
  223. while (size < min) {
  224. acc.append(item_gen());
  225. ++size;
  226. }
  227. return acc;
  228. }
  229. // General case: before each item we "flip a coin" to decide whether to
  230. // generate another one.
  231. //
  232. // This algorithm is used instead of the more intuitive "generate length,
  233. // then generate that many items" algorithm, because it produces RandomRun
  234. // patterns that shrink more easily.
  235. //
  236. // See the Hypothesis paper [1], section 3.3, around the paragraph starting
  237. // with "More commonly".
  238. //
  239. // [1]: https://drops.dagstuhl.de/opus/volltexte/2020/13170/pdf/LIPIcs-ECOOP-2020-13.pdf
  240. while (size < min) {
  241. acc.append(item_gen());
  242. ++size;
  243. }
  244. double average = static_cast<double>(min + max) / 2.0;
  245. VERIFY(average > 0);
  246. // A geometric distribution: https://en.wikipedia.org/wiki/Geometric_distribution#Moments_and_cumulants
  247. // The below derives from the E(X) = 1/p formula.
  248. //
  249. // We need to flip the `p` to `1-p` as our success ("another item!") is
  250. // a "failure" in the geometric distribution's interpretation ("we fail X
  251. // times before succeeding the first time").
  252. //
  253. // That gives us `1 - 1/p`. Then, E(X) also contains the final success, so we
  254. // need to say `1 + average` instead of `average`, as it will mean "our X
  255. // items + the final failure that stops the process".
  256. double probability = 1.0 - 1.0 / (1.0 + average);
  257. while (size < max) {
  258. if (weighted_boolean(probability)) {
  259. acc.append(item_gen());
  260. ++size;
  261. } else {
  262. break;
  263. }
  264. }
  265. return acc;
  266. }
  267. // A vector generator of a given length.
  268. //
  269. // Gen::vector_of_length(3,[]() { return Gen::unsigned_int(5); })
  270. // -> value [1,5,0], RandomRun [1,1,1,5,1,0,0]
  271. // -> value [2,9,3], RandomRun [1,2,1,9,1,3,0]
  272. // etc.
  273. //
  274. // Shrinks towards shorter vectors, with simpler elements inside.
  275. template<typename Fn>
  276. inline Vector<InvokeResult<Fn>> vector(size_t length, Fn item_gen)
  277. {
  278. return vector(length, length, item_gen);
  279. }
  280. // A vector generator of a random length between 0 and 32 elements.
  281. //
  282. // If you need a different length, use vector(max,item_gen) or
  283. // vector(min,max,item_gen).
  284. //
  285. // Gen::vector([]() { return Gen::unsigned_int(5); })
  286. // -> value [], RandomRun [0]
  287. // -> value [1], RandomRun [1,1,0]
  288. // -> value [1,5], RandomRun [1,1,1,5,0]
  289. // -> value [1,5,0], RandomRun [1,1,1,5,1,0,0]
  290. // -> value [1,5,0,2], RandomRun [1,1,1,5,1,0,1,2,0]
  291. // etc.
  292. //
  293. // Shrinks towards shorter vectors, with simpler elements inside.
  294. template<typename Fn>
  295. inline Vector<InvokeResult<Fn>> vector(Fn item_gen)
  296. {
  297. return vector(0, 32, item_gen);
  298. }
  299. } // namespace Gen
  300. } // namespace Randomized
  301. } // namespace Test