naive_monte_carlo.hpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. /*
  2. * Copyright Nick Thompson, 2018
  3. * Use, modification and distribution are subject to the
  4. * Boost Software License, Version 1.0. (See accompanying file
  5. * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
  6. */
  7. #ifndef BOOST_MATH_QUADRATURE_NAIVE_MONTE_CARLO_HPP
  8. #define BOOST_MATH_QUADRATURE_NAIVE_MONTE_CARLO_HPP
  9. #include <sstream>
  10. #include <algorithm>
  11. #include <vector>
  12. #include <atomic>
  13. #include <memory>
  14. #include <functional>
  15. #include <future>
  16. #include <thread>
  17. #include <initializer_list>
  18. #include <utility>
  19. #include <random>
  20. #include <chrono>
  21. #include <map>
  22. #include <type_traits>
  23. #include <boost/math/policies/error_handling.hpp>
  24. #include <boost/math/special_functions/fpclassify.hpp>
  25. #ifdef BOOST_NAIVE_MONTE_CARLO_DEBUG_FAILURES
  26. # include <iostream>
  27. #endif
  28. namespace boost { namespace math { namespace quadrature {
  29. namespace detail {
  30. enum class limit_classification {FINITE,
  31. LOWER_BOUND_INFINITE,
  32. UPPER_BOUND_INFINITE,
  33. DOUBLE_INFINITE};
  34. }
  35. template<class Real, class F, class RandomNumberGenerator = std::mt19937_64, class Policy = boost::math::policies::policy<>,
  36. typename std::enable_if<std::is_trivially_copyable<Real>::value, bool>::type = true>
  37. class naive_monte_carlo
  38. {
  39. public:
  40. naive_monte_carlo(const F& integrand,
  41. std::vector<std::pair<Real, Real>> const & bounds,
  42. Real error_goal,
  43. bool singular = true,
  44. uint64_t threads = std::thread::hardware_concurrency(),
  45. uint64_t seed = 0) noexcept : m_num_threads{threads}, m_seed{seed}, m_volume(1)
  46. {
  47. using std::numeric_limits;
  48. using std::sqrt;
  49. using boost::math::isinf;
  50. uint64_t n = bounds.size();
  51. m_lbs.resize(n);
  52. m_dxs.resize(n);
  53. m_limit_types.resize(n);
  54. static const char* function = "boost::math::quadrature::naive_monte_carlo<%1%>";
  55. for (uint64_t i = 0; i < n; ++i)
  56. {
  57. if (bounds[i].second <= bounds[i].first)
  58. {
  59. boost::math::policies::raise_domain_error(function, "The upper bound is <= the lower bound.\n", bounds[i].second, Policy());
  60. return;
  61. }
  62. if (isinf(bounds[i].first))
  63. {
  64. if (isinf(bounds[i].second))
  65. {
  66. m_limit_types[i] = detail::limit_classification::DOUBLE_INFINITE;
  67. }
  68. else
  69. {
  70. m_limit_types[i] = detail::limit_classification::LOWER_BOUND_INFINITE;
  71. // Ok ok this is bad to use the second bound as the lower limit and then reflect.
  72. m_lbs[i] = bounds[i].second;
  73. m_dxs[i] = numeric_limits<Real>::quiet_NaN();
  74. }
  75. }
  76. else if (isinf(bounds[i].second))
  77. {
  78. m_limit_types[i] = detail::limit_classification::UPPER_BOUND_INFINITE;
  79. if (singular)
  80. {
  81. // I've found that it's easier to sample on a closed set and perturb the boundary
  82. // than to try to sample very close to the boundary.
  83. m_lbs[i] = std::nextafter(bounds[i].first, (std::numeric_limits<Real>::max)());
  84. }
  85. else
  86. {
  87. m_lbs[i] = bounds[i].first;
  88. }
  89. m_dxs[i] = numeric_limits<Real>::quiet_NaN();
  90. }
  91. else
  92. {
  93. m_limit_types[i] = detail::limit_classification::FINITE;
  94. if (singular)
  95. {
  96. if (bounds[i].first == 0)
  97. {
  98. m_lbs[i] = std::numeric_limits<Real>::epsilon();
  99. }
  100. else
  101. {
  102. m_lbs[i] = std::nextafter(bounds[i].first, (std::numeric_limits<Real>::max)());
  103. }
  104. m_dxs[i] = std::nextafter(bounds[i].second, std::numeric_limits<Real>::lowest()) - m_lbs[i];
  105. }
  106. else
  107. {
  108. m_lbs[i] = bounds[i].first;
  109. m_dxs[i] = bounds[i].second - bounds[i].first;
  110. }
  111. m_volume *= m_dxs[i];
  112. }
  113. }
  114. m_integrand = [this, &integrand](std::vector<Real> & x)->Real
  115. {
  116. Real coeff = m_volume;
  117. for (uint64_t i = 0; i < x.size(); ++i)
  118. {
  119. // Variable transformation are listed at:
  120. // https://en.wikipedia.org/wiki/Numerical_integration
  121. // However, we've made some changes to these so that we can evaluate on a compact domain.
  122. if (m_limit_types[i] == detail::limit_classification::FINITE)
  123. {
  124. x[i] = m_lbs[i] + x[i]*m_dxs[i];
  125. }
  126. else if (m_limit_types[i] == detail::limit_classification::UPPER_BOUND_INFINITE)
  127. {
  128. Real t = x[i];
  129. Real z = 1/(1 + numeric_limits<Real>::epsilon() - t);
  130. coeff *= (z*z)*(1 + numeric_limits<Real>::epsilon());
  131. x[i] = m_lbs[i] + t*z;
  132. }
  133. else if (m_limit_types[i] == detail::limit_classification::LOWER_BOUND_INFINITE)
  134. {
  135. Real t = x[i];
  136. Real z = 1/(t+sqrt((numeric_limits<Real>::min)()));
  137. coeff *= (z*z);
  138. x[i] = m_lbs[i] + (t-1)*z;
  139. }
  140. else
  141. {
  142. Real t1 = 1/(1+numeric_limits<Real>::epsilon() - x[i]);
  143. Real t2 = 1/(x[i]+numeric_limits<Real>::epsilon());
  144. x[i] = (2*x[i]-1)*t1*t2/4;
  145. coeff *= (t1*t1+t2*t2)/4;
  146. }
  147. }
  148. return coeff*integrand(x);
  149. };
  150. // If we don't do a single function call in the constructor,
  151. // we can't do a restart.
  152. std::vector<Real> x(m_lbs.size());
  153. // If the seed is zero, that tells us to choose a random seed for the user:
  154. if (seed == 0)
  155. {
  156. std::random_device rd;
  157. seed = rd();
  158. }
  159. RandomNumberGenerator gen(seed);
  160. Real inv_denom = 1/static_cast<Real>(((gen.max)()-(gen.min)()));
  161. m_num_threads = (std::max)(m_num_threads, static_cast<uint64_t>(1));
  162. m_thread_calls.reset(new std::atomic<uint64_t>[threads]);
  163. m_thread_Ss.reset(new std::atomic<Real>[threads]);
  164. m_thread_averages.reset(new std::atomic<Real>[threads]);
  165. Real avg = 0;
  166. for (uint64_t i = 0; i < m_num_threads; ++i)
  167. {
  168. for (uint64_t j = 0; j < m_lbs.size(); ++j)
  169. {
  170. x[j] = (gen()-(gen.min)())*inv_denom;
  171. }
  172. Real y = m_integrand(x);
  173. m_thread_averages[i] = y; // relaxed store
  174. m_thread_calls[i] = 1;
  175. m_thread_Ss[i] = 0;
  176. avg += y;
  177. }
  178. avg /= m_num_threads;
  179. m_avg = avg; // relaxed store
  180. m_error_goal = error_goal; // relaxed store
  181. m_start = std::chrono::system_clock::now();
  182. m_done = false; // relaxed store
  183. m_total_calls = m_num_threads; // relaxed store
  184. m_variance = (numeric_limits<Real>::max)();
  185. }
  186. std::future<Real> integrate()
  187. {
  188. // Set done to false in case we wish to restart:
  189. m_done.store(false); // relaxed store, no worker threads yet
  190. m_start = std::chrono::system_clock::now();
  191. return std::async(std::launch::async,
  192. &naive_monte_carlo::m_integrate, this);
  193. }
  194. void cancel()
  195. {
  196. // If seed = 0 (meaning have the routine pick the seed), this leaves the seed the same.
  197. // If seed != 0, then the seed is changed, so a restart doesn't do the exact same thing.
  198. m_seed = m_seed*m_seed;
  199. m_done = true; // relaxed store, worker threads will get the message eventually
  200. // Make sure the error goal is infinite, because otherwise we'll loop when we do the final error goal check:
  201. m_error_goal = (std::numeric_limits<Real>::max)();
  202. }
  203. Real variance() const
  204. {
  205. return m_variance.load();
  206. }
  207. Real current_error_estimate() const
  208. {
  209. using std::sqrt;
  210. //
  211. // There is a bug here: m_variance and m_total_calls get updated asynchronously
  212. // and may be out of synch when we compute the error estimate, not sure if it matters though...
  213. //
  214. return sqrt(m_variance.load()/m_total_calls.load());
  215. }
  216. std::chrono::duration<Real> estimated_time_to_completion() const
  217. {
  218. auto now = std::chrono::system_clock::now();
  219. std::chrono::duration<Real> elapsed_seconds = now - m_start;
  220. Real r = this->current_error_estimate()/m_error_goal.load(); // relaxed load
  221. if (r*r <= 1) {
  222. return 0*elapsed_seconds;
  223. }
  224. return (r*r - 1)*elapsed_seconds;
  225. }
  226. void update_target_error(Real new_target_error)
  227. {
  228. m_error_goal = new_target_error; // relaxed store
  229. }
  230. Real progress() const
  231. {
  232. Real r = m_error_goal.load()/this->current_error_estimate(); // relaxed load
  233. if (r*r >= 1)
  234. {
  235. return 1;
  236. }
  237. return r*r;
  238. }
  239. Real current_estimate() const
  240. {
  241. return m_avg.load();
  242. }
  243. uint64_t calls() const
  244. {
  245. return m_total_calls.load(); // relaxed load
  246. }
  247. private:
  248. Real m_integrate()
  249. {
  250. uint64_t seed;
  251. // If the user tells us to pick a seed, pick a seed:
  252. if (m_seed == 0)
  253. {
  254. std::random_device rd;
  255. seed = rd();
  256. }
  257. else // use the seed we are given:
  258. {
  259. seed = m_seed;
  260. }
  261. RandomNumberGenerator gen(seed);
  262. int max_repeat_tries = 5;
  263. do{
  264. if (max_repeat_tries < 5)
  265. {
  266. m_done = false;
  267. #ifdef BOOST_NAIVE_MONTE_CARLO_DEBUG_FAILURES
  268. std::cerr << "Failed to achieve required tolerance first time through..\n";
  269. std::cerr << " variance = " << m_variance << std::endl;
  270. std::cerr << " average = " << m_avg << std::endl;
  271. std::cerr << " total calls = " << m_total_calls << std::endl;
  272. for (std::size_t i = 0; i < m_num_threads; ++i)
  273. std::cerr << " thread_calls[" << i << "] = " << m_thread_calls[i] << std::endl;
  274. for (std::size_t i = 0; i < m_num_threads; ++i)
  275. std::cerr << " thread_averages[" << i << "] = " << m_thread_averages[i] << std::endl;
  276. for (std::size_t i = 0; i < m_num_threads; ++i)
  277. std::cerr << " thread_Ss[" << i << "] = " << m_thread_Ss[i] << std::endl;
  278. #endif
  279. }
  280. std::vector<std::thread> threads(m_num_threads);
  281. for (uint64_t i = 0; i < threads.size(); ++i)
  282. {
  283. threads[i] = std::thread(&naive_monte_carlo::m_thread_monte, this, i, gen());
  284. }
  285. do {
  286. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  287. uint64_t total_calls = 0;
  288. for (uint64_t i = 0; i < m_num_threads; ++i)
  289. {
  290. uint64_t t_calls = m_thread_calls[i].load(std::memory_order_consume);
  291. total_calls += t_calls;
  292. }
  293. Real variance = 0;
  294. Real avg = 0;
  295. for (uint64_t i = 0; i < m_num_threads; ++i)
  296. {
  297. uint64_t t_calls = m_thread_calls[i].load(std::memory_order_consume);
  298. // Will this overflow? Not hard to remove . . .
  299. avg += m_thread_averages[i].load(std::memory_order_relaxed)*(static_cast<Real>(t_calls) / static_cast<Real>(total_calls));
  300. variance += m_thread_Ss[i].load(std::memory_order_relaxed);
  301. }
  302. m_avg.store(avg, std::memory_order_release);
  303. m_variance.store(variance / (total_calls - 1), std::memory_order_release);
  304. m_total_calls = total_calls; // relaxed store, it's just for user feedback
  305. // Allow cancellation:
  306. if (m_done) // relaxed load
  307. {
  308. break;
  309. }
  310. } while (m_total_calls < 2048 || this->current_error_estimate() > m_error_goal.load(std::memory_order_consume));
  311. // Error bound met; signal the threads:
  312. m_done = true; // relaxed store, threads will get the message in the end
  313. std::for_each(threads.begin(), threads.end(),
  314. std::mem_fn(&std::thread::join));
  315. if (m_exception)
  316. {
  317. std::rethrow_exception(m_exception);
  318. }
  319. // Incorporate their work into the final estimate:
  320. uint64_t total_calls = 0;
  321. for (uint64_t i = 0; i < m_num_threads; ++i)
  322. {
  323. uint64_t t_calls = m_thread_calls[i].load(std::memory_order_consume);
  324. total_calls += t_calls;
  325. }
  326. Real variance = 0;
  327. Real avg = 0;
  328. for (uint64_t i = 0; i < m_num_threads; ++i)
  329. {
  330. uint64_t t_calls = m_thread_calls[i].load(std::memory_order_consume);
  331. // Averages weighted by the number of calls the thread made:
  332. avg += m_thread_averages[i].load(std::memory_order_relaxed)*(static_cast<Real>(t_calls) / static_cast<Real>(total_calls));
  333. variance += m_thread_Ss[i].load(std::memory_order_relaxed);
  334. }
  335. m_avg.store(avg, std::memory_order_release);
  336. m_variance.store(variance / (total_calls - 1), std::memory_order_release);
  337. m_total_calls = total_calls; // relaxed store, this is just user feedback
  338. // Sometimes, the master will observe the variance at a very "good" (or bad?) moment,
  339. // Then the threads proceed to find the variance is much greater by the time they hear the message to stop.
  340. // This *WOULD* make sure that the final error estimate is within the error bounds.
  341. }
  342. while ((--max_repeat_tries >= 0) && (this->current_error_estimate() > m_error_goal));
  343. return m_avg.load(std::memory_order_consume);
  344. }
  345. void m_thread_monte(uint64_t thread_index, uint64_t seed)
  346. {
  347. using std::numeric_limits;
  348. try
  349. {
  350. std::vector<Real> x(m_lbs.size());
  351. RandomNumberGenerator gen(seed);
  352. Real inv_denom = static_cast<Real>(1) / static_cast<Real>(( (gen.max)() - (gen.min)() ));
  353. Real M1 = m_thread_averages[thread_index].load(std::memory_order_consume);
  354. Real S = m_thread_Ss[thread_index].load(std::memory_order_consume);
  355. // Kahan summation is required or the value of the integrand will go on a random walk during long computations.
  356. // See the implementation discussion.
  357. // The idea is that the unstabilized additions have error sigma(f)/sqrt(N) + epsilon*N, which diverges faster than it converges!
  358. // Kahan summation turns this to sigma(f)/sqrt(N) + epsilon^2*N, and the random walk occurs on a timescale of 10^14 years (on current hardware)
  359. Real compensator = 0;
  360. uint64_t k = m_thread_calls[thread_index].load(std::memory_order_consume);
  361. while (!m_done) // relaxed load
  362. {
  363. int j = 0;
  364. // If we don't have a certain number of calls before an update, we can easily terminate prematurely
  365. // because the variance estimate is way too low. This magic number is a reasonable compromise, as 1/sqrt(2048) = 0.02,
  366. // so it should recover 2 digits if the integrand isn't poorly behaved, and if it is, it should discover that before premature termination.
  367. // Of course if the user has 64 threads, then this number is probably excessive.
  368. int magic_calls_before_update = 2048;
  369. while (j++ < magic_calls_before_update)
  370. {
  371. for (uint64_t i = 0; i < m_lbs.size(); ++i)
  372. {
  373. x[i] = (gen() - (gen.min)())*inv_denom;
  374. }
  375. Real f = m_integrand(x);
  376. using std::isfinite;
  377. if (!isfinite(f))
  378. {
  379. // The call to m_integrand transform x, so this error message states the correct node.
  380. std::stringstream os;
  381. os << "Your integrand was evaluated at {";
  382. for (uint64_t i = 0; i < x.size() -1; ++i)
  383. {
  384. os << x[i] << ", ";
  385. }
  386. os << x[x.size() -1] << "}, and returned " << f << std::endl;
  387. static const char* function = "boost::math::quadrature::naive_monte_carlo<%1%>";
  388. boost::math::policies::raise_domain_error(function, os.str().c_str(), /*this is a dummy arg to make it compile*/ 7.2, Policy());
  389. }
  390. ++k;
  391. Real term = (f - M1)/k;
  392. Real y1 = term - compensator;
  393. Real M2 = M1 + y1;
  394. compensator = (M2 - M1) - y1;
  395. S += (f - M1)*(f - M2);
  396. M1 = M2;
  397. }
  398. m_thread_averages[thread_index].store(M1, std::memory_order_release);
  399. m_thread_Ss[thread_index].store(S, std::memory_order_release);
  400. m_thread_calls[thread_index].store(k, std::memory_order_release);
  401. }
  402. }
  403. catch (...)
  404. {
  405. // Signal the other threads that the computation is ruined:
  406. m_done = true; // relaxed store
  407. std::lock_guard<std::mutex> lock(m_exception_mutex); // Scoped lock to prevent race writing to m_exception
  408. m_exception = std::current_exception();
  409. }
  410. }
  411. std::function<Real(std::vector<Real> &)> m_integrand;
  412. uint64_t m_num_threads;
  413. std::atomic<uint64_t> m_seed;
  414. std::atomic<Real> m_error_goal;
  415. std::atomic<bool> m_done{};
  416. std::vector<Real> m_lbs;
  417. std::vector<Real> m_dxs;
  418. std::vector<detail::limit_classification> m_limit_types;
  419. Real m_volume;
  420. std::atomic<uint64_t> m_total_calls{};
  421. // I wanted these to be vectors rather than maps,
  422. // but you can't resize a vector of atomics.
  423. std::unique_ptr<std::atomic<uint64_t>[]> m_thread_calls;
  424. std::atomic<Real> m_variance;
  425. std::unique_ptr<std::atomic<Real>[]> m_thread_Ss;
  426. std::atomic<Real> m_avg;
  427. std::unique_ptr<std::atomic<Real>[]> m_thread_averages;
  428. std::chrono::time_point<std::chrono::system_clock> m_start;
  429. std::exception_ptr m_exception;
  430. std::mutex m_exception_mutex;
  431. };
  432. }}}
  433. #endif