psim  1.0
Generalized 2D phonon transport using a Monte Carlo method
utils.h
Go to the documentation of this file.
1 #ifndef PSIM_UTILS_H
2 #define PSIM_UTILS_H
3 
4 #include <array>
5 #include <random>
6 
7 namespace Utils {
8 
9 inline constexpr double PI = 3.1415926535897932384626433832795028841971693993751058209749445923;
10 
11 // Generates a random number from a uniform distribution over [0,1].
12 inline double urand() noexcept {
13  static std::random_device rd;// NOLINT
14  static thread_local std::mt19937 generator(rd());
15  std::uniform_real_distribution<double> dist(0., std::nextafter(1.0, 2.0));// NOLINT
16  return dist(generator);
17 }
18 
19 // Allows usage of enum classes as integral values similar to unscoped enums. Enum classes seems to
20 // require a static_cast<std::size_t> so this save having to type that everytime.
21 // Can use eType(enum) instead of std::static_cast<std::size_t>(enum).
22 // Must be constexpr to work with std::get when using variants
23 template<typename E> constexpr auto toInteger(E enumerator) noexcept {
24  return static_cast<std::underlying_type_t<E>>(enumerator);
25 }
26 
27 // Custom to function to emulate python zip functionality
28 // General implementation
29 template<typename In1, typename In2, typename Out>
30 void zip(In1 begin1, In2 end1, In2 begin2, In2 end2, Out result) {// NOLINT
31  auto it1{ begin1 };
32  auto it2{ begin2 };
33  while (it1 != end1 && it2 != end2) { result++ = { *it1++, *it2++ }; }
34 }
35 
36 // Specifically for vectors
37 template<typename T, typename U>
38 std::vector<std::pair<T, U>> zip(const std::vector<T>& r1, const std::vector<U> r2) {// NOLINT
39  std::vector<std::pair<T, U>> result;
40  zip(std::cbegin(r1), std::cend(r1), std::cbegin(r2), std::cend(r2), std::back_inserter(result));
41  return result;
42 }
43 
44 // Specifically for arrays
45 template<typename T, typename U, std::size_t V>
46 std::array<std::pair<T, U>, V> zip(const std::array<T, V>& r1, const std::array<U, V>& r2) {// NOLINT
47  std::array<std::pair<T, U>, V> result;
48  std::size_t index = 0;
49  auto it1{ std::cbegin(r1) };
50  auto it2{ std::cbegin(r2) };
51  while (it1 != std::cend(r1) && it2 != std::cend(r2)) { result[index++] = { *it1++, *it2++ }; }
52  return result;
53 }
54 }// namespace Utils
55 
56 #endif// PSIM_UTILS_H
Definition: utils.h:7
double urand() noexcept
Definition: utils.h:12
constexpr double PI
Definition: utils.h:9
constexpr auto toInteger(E enumerator) noexcept
Definition: utils.h:23
void zip(In1 begin1, In2 end1, In2 begin2, In2 end2, Out result)
Definition: utils.h:30