faure.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367
  1. /* boost random/faure.hpp header file
  2. *
  3. * Copyright Justinas Vygintas Daugmaudis 2010-2018
  4. * Distributed under the Boost Software License, Version 1.0. (See
  5. * accompanying file LICENSE_1_0.txt or copy at
  6. * http://www.boost.org/LICENSE_1_0.txt)
  7. */
  8. #ifndef BOOST_RANDOM_FAURE_HPP
  9. #define BOOST_RANDOM_FAURE_HPP
  10. #include <boost/random/detail/qrng_base.hpp>
  11. #include <cmath>
  12. #include <vector>
  13. #include <algorithm>
  14. #include <boost/assert.hpp>
  15. namespace boost {
  16. namespace random {
  17. /** @cond */
  18. namespace detail {
  19. namespace qrng_tables {
  20. // There is no particular reason why 187 first primes were chosen
  21. // to be put into this table. The only reason was, perhaps, that
  22. // the number of dimensions for Faure generator would be around
  23. // the same order of magnitude as the number of dimensions supported
  24. // by the Sobol qrng.
  25. struct primes
  26. {
  27. typedef unsigned short value_type;
  28. BOOST_STATIC_CONSTANT(int, number_of_primes = 187);
  29. // A function that returns lower bound prime for a given n
  30. static value_type lower_bound(std::size_t n)
  31. {
  32. static const value_type prim_a[number_of_primes] = {
  33. 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53,
  34. 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
  35. 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181,
  36. 191, 193, 197, 199, 211, 223, 227, 229, 233, 239, 241, 251,
  37. 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
  38. 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397,
  39. 401, 409, 419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
  40. 467, 479, 487, 491, 499, 503, 509, 521, 523, 541, 547, 557,
  41. 563, 569, 571, 577, 587, 593, 599, 601, 607, 613, 617, 619,
  42. 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
  43. 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787,
  44. 797, 809, 811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
  45. 877, 881, 883, 887, 907, 911, 919, 929, 937, 941, 947, 953,
  46. 967, 971, 977, 983, 991, 997, 1009, 1013, 1019, 1021, 1031,
  47. 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093,
  48. 1097, 1103, 1109, 1117 };
  49. qrng_detail::dimension_assert("Faure", n, prim_a[number_of_primes - 1]);
  50. return *std::lower_bound(prim_a, prim_a + number_of_primes, n);
  51. }
  52. };
  53. } // namespace qrng_tables
  54. } // namespace detail
  55. namespace qrng_detail {
  56. namespace fr {
  57. // Returns the integer part of the logarithm base Base of arg.
  58. // In erroneous situations, e.g., integer_log(base, 0) the function
  59. // returns 0 and does not report the error. This is the intended
  60. // behavior.
  61. template <typename T>
  62. inline T integer_log(T base, T arg)
  63. {
  64. T ilog = T();
  65. while (base <= arg)
  66. {
  67. arg /= base; ++ilog;
  68. }
  69. return ilog;
  70. }
  71. // Perform exponentiation by squaring (potential for code reuse in multiprecision::powm)
  72. template <typename T>
  73. inline T integer_pow(T base, T e)
  74. {
  75. T result = static_cast<T>(1);
  76. while (e)
  77. {
  78. if (e & static_cast<T>(1))
  79. result *= base;
  80. e >>= 1;
  81. base *= base;
  82. }
  83. return result;
  84. }
  85. } // namespace fr
  86. // Computes a table of binomial coefficients modulo qs.
  87. template<typename RealType, typename SeqSizeT, typename PrimeTable>
  88. struct binomial_coefficients
  89. {
  90. typedef RealType value_type;
  91. typedef SeqSizeT size_type;
  92. // Binomial values modulo qs_base will never be bigger than qs_base.
  93. // We can choose an appropriate integer type to hold modulo values and
  94. // shave off memory footprint.
  95. typedef typename PrimeTable::value_type packed_uint_t;
  96. // default copy c-tor is fine
  97. explicit binomial_coefficients(std::size_t dimension)
  98. {
  99. resize(dimension);
  100. }
  101. void resize(std::size_t dimension)
  102. {
  103. qs_base = PrimeTable::lower_bound(dimension);
  104. // Throw away previously computed coefficients.
  105. // This will trigger recomputation on next update
  106. coeff.clear();
  107. }
  108. template <typename Iterator>
  109. void update(size_type seq, Iterator first, Iterator last)
  110. {
  111. if (first != last)
  112. {
  113. const size_type ilog = fr::integer_log(static_cast<size_type>(qs_base), seq);
  114. const size_type hisum = ilog + 1;
  115. if (coeff.size() != size_hint(hisum)) {
  116. ytemp.resize(static_cast<std::size_t>(hisum)); // cast safe because log is small
  117. compute_coefficients(hisum);
  118. qs_pow = fr::integer_pow(static_cast<size_type>(qs_base), ilog);
  119. }
  120. *first = compute_recip(seq, ytemp.rbegin());
  121. // Find other components using the Faure method.
  122. ++first;
  123. for ( ; first != last; ++first)
  124. {
  125. *first = RealType();
  126. RealType r = static_cast<RealType>(1);
  127. for (size_type i = 0; i != hisum; ++i)
  128. {
  129. RealType ztemp = ytemp[static_cast<std::size_t>(i)] * upper_element(i, i, hisum);
  130. for (size_type j = i + 1; j != hisum; ++j)
  131. ztemp += ytemp[static_cast<std::size_t>(j)] * upper_element(i, j, hisum);
  132. // Sum ( J <= I <= HISUM ) ( old ytemp(i) * binom(i,j) ) mod QS.
  133. ytemp[static_cast<std::size_t>(i)] = std::fmod(ztemp, static_cast<RealType>(qs_base));
  134. r *= static_cast<RealType>(qs_base);
  135. *first += ytemp[static_cast<std::size_t>(i)] / r;
  136. }
  137. }
  138. }
  139. }
  140. private:
  141. inline static size_type size_hint(size_type n)
  142. {
  143. return n * (n + 1) / 2;
  144. }
  145. packed_uint_t& upper_element(size_type i, size_type j, size_type dim)
  146. {
  147. BOOST_ASSERT( i < dim );
  148. BOOST_ASSERT( j < dim );
  149. BOOST_ASSERT( i <= j );
  150. return coeff[static_cast<std::size_t>((i * (2 * dim - i + 1)) / 2 + j - i)];
  151. }
  152. template<typename Iterator>
  153. RealType compute_recip(size_type seq, Iterator out) const
  154. {
  155. // Here we do
  156. // Sum ( 0 <= J <= HISUM ) YTEMP(J) * QS**J
  157. // Sum ( 0 <= J <= HISUM ) YTEMP(J) / QS**(J+1)
  158. // in one go
  159. RealType r = RealType();
  160. size_type m, k = qs_pow;
  161. for( ; k != 0; ++out, seq = m, k /= qs_base )
  162. {
  163. m = seq % k;
  164. RealType v = static_cast<RealType>((seq - m) / k); // RealType <- size type
  165. r += v;
  166. r /= static_cast<RealType>(qs_base);
  167. *out = v; // saves double dereference
  168. }
  169. return r;
  170. }
  171. void compute_coefficients(const size_type n)
  172. {
  173. // Resize and initialize to zero
  174. coeff.resize(static_cast<std::size_t>(size_hint(n)));
  175. std::fill(coeff.begin(), coeff.end(), packed_uint_t());
  176. // The first row and the diagonal is assigned to 1
  177. upper_element(0, 0, n) = 1;
  178. for (size_type i = 1; i < n; ++i)
  179. {
  180. upper_element(0, i, n) = 1;
  181. upper_element(i, i, n) = 1;
  182. }
  183. // Computes binomial coefficients MOD qs_base
  184. for (size_type i = 1; i < n; ++i)
  185. {
  186. for (size_type j = i + 1; j < n; ++j)
  187. {
  188. upper_element(i, j, n) = ( upper_element(i, j-1, n) +
  189. upper_element(i-1, j-1, n) ) % qs_base;
  190. }
  191. }
  192. }
  193. private:
  194. packed_uint_t qs_base;
  195. // here we cache precomputed data; note that binomial coefficients have
  196. // to be recomputed iff the integer part of the logarithm of seq changes,
  197. // which happens relatively rarely.
  198. std::vector<packed_uint_t> coeff; // packed upper (!) triangular matrix
  199. std::vector<RealType> ytemp;
  200. size_type qs_pow;
  201. };
  202. } // namespace qrng_detail
  203. typedef detail::qrng_tables::primes default_faure_prime_table;
  204. /** @endcond */
  205. //!Instantiations of class template faure_engine model a \quasi_random_number_generator.
  206. //!The faure_engine uses the algorithm described in
  207. //! \blockquote
  208. //!Henri Faure,
  209. //!Discrepance de suites associees a un systeme de numeration (en dimension s),
  210. //!Acta Arithmetica,
  211. //!Volume 41, 1982, pages 337-351.
  212. //! \endblockquote
  213. //
  214. //! \blockquote
  215. //!Bennett Fox,
  216. //!Algorithm 647:
  217. //!Implementation and Relative Efficiency of Quasirandom
  218. //!Sequence Generators,
  219. //!ACM Transactions on Mathematical Software,
  220. //!Volume 12, Number 4, December 1986, pages 362-376.
  221. //! \endblockquote
  222. //!
  223. //!In the following documentation @c X denotes the concrete class of the template
  224. //!faure_engine returning objects of type @c RealType, u and v are the values of @c X.
  225. //!
  226. //!Some member functions may throw exceptions of type @c std::bad_alloc.
  227. template<typename RealType, typename SeqSizeT, typename PrimeTable = default_faure_prime_table>
  228. class faure_engine
  229. : public qrng_detail::qrng_base<
  230. faure_engine<RealType, SeqSizeT, PrimeTable>
  231. , qrng_detail::binomial_coefficients<RealType, SeqSizeT, PrimeTable>
  232. , SeqSizeT
  233. >
  234. {
  235. typedef faure_engine<RealType, SeqSizeT, PrimeTable> self_t;
  236. typedef qrng_detail::binomial_coefficients<RealType, SeqSizeT, PrimeTable> lattice_t;
  237. typedef qrng_detail::qrng_base<self_t, lattice_t, SeqSizeT> base_t;
  238. friend class qrng_detail::qrng_base<self_t, lattice_t, SeqSizeT>;
  239. public:
  240. typedef RealType result_type;
  241. /** @copydoc boost::random::niederreiter_base2_engine::min() */
  242. static BOOST_CONSTEXPR result_type min BOOST_PREVENT_MACRO_SUBSTITUTION ()
  243. { return static_cast<result_type>(0); }
  244. /** @copydoc boost::random::niederreiter_base2_engine::max() */
  245. static BOOST_CONSTEXPR result_type max BOOST_PREVENT_MACRO_SUBSTITUTION ()
  246. { return static_cast<result_type>(1); }
  247. //!Effects: Constructs the `s`-dimensional default Faure quasi-random number generator.
  248. //!
  249. //!Throws: bad_alloc, invalid_argument.
  250. explicit faure_engine(std::size_t s)
  251. : base_t(s) // initialize the binomial table here
  252. {}
  253. /** @copydetails boost::random::niederreiter_base2_engine::seed(UIntType)
  254. * Throws: bad_alloc.
  255. */
  256. void seed(SeqSizeT init = 0)
  257. {
  258. compute_seq(init);
  259. base_t::reset_seq(init);
  260. }
  261. #ifdef BOOST_RANDOM_DOXYGEN
  262. //=========================Doxygen needs this!==============================
  263. /** @copydoc boost::random::niederreiter_base2_engine::dimension() */
  264. std::size_t dimension() const { return base_t::dimension(); }
  265. /** @copydoc boost::random::niederreiter_base2_engine::operator()() */
  266. result_type operator()()
  267. {
  268. return base_t::operator()();
  269. }
  270. /** @copydoc boost::random::niederreiter_base2_engine::discard(boost::uintmax_t)
  271. * Throws: bad_alloc.
  272. */
  273. void discard(boost::uintmax_t z)
  274. {
  275. base_t::discard(z);
  276. }
  277. /** Returns true if the two generators will produce identical sequences of outputs. */
  278. BOOST_RANDOM_DETAIL_EQUALITY_OPERATOR(faure_engine, x, y)
  279. { return static_cast<const base_t&>(x) == y; }
  280. /** Returns true if the two generators will produce different sequences of outputs. */
  281. BOOST_RANDOM_DETAIL_INEQUALITY_OPERATOR(faure_engine)
  282. /** Writes the textual representation of the generator to a @c std::ostream. */
  283. BOOST_RANDOM_DETAIL_OSTREAM_OPERATOR(os, faure_engine, s)
  284. { return os << static_cast<const base_t&>(s); }
  285. /** Reads the textual representation of the generator from a @c std::istream. */
  286. BOOST_RANDOM_DETAIL_ISTREAM_OPERATOR(is, faure_engine, s)
  287. { return is >> static_cast<base_t&>(s); }
  288. #endif // BOOST_RANDOM_DOXYGEN
  289. private:
  290. /** @cond hide_private_members */
  291. void compute_seq(SeqSizeT seq)
  292. {
  293. qrng_detail::check_seed_sign(seq);
  294. this->lattice.update(seq, this->state_begin(), this->state_end());
  295. }
  296. /** @endcond */
  297. };
  298. /**
  299. * @attention This specialization of \faure_engine supports up to 1117 dimensions.
  300. *
  301. * However, it is possible to provide your own prime table to \faure_engine should the default one be insufficient.
  302. */
  303. typedef faure_engine<double, boost::uint_least64_t, default_faure_prime_table> faure;
  304. } // namespace random
  305. } // namespace boost
  306. #endif // BOOST_RANDOM_FAURE_HPP