/src/ocudu/tests/test_doubles/utils/test_rng.h
Line | Count | Source |
1 | | // SPDX-FileCopyrightText: Copyright (C) 2021-2026 Software Radio Systems Limited |
2 | | // SPDX-FileCopyrightText: Copyright (C) 2026 OCUDU contributors |
3 | | // SPDX-License-Identifier: BSD-3-Clause-Open-MPI |
4 | | |
5 | | #pragma once |
6 | | |
7 | | #include <limits> |
8 | | #include <random> |
9 | | #include <vector> |
10 | | |
11 | | namespace ocudu::test_rng { |
12 | | |
13 | | /// Fetch the seed under use for unit tests. The user can force a seed via --gtest_random_seed= command line option. |
14 | | uint32_t seed(); |
15 | | |
16 | | /// Fetch thread-local random generator. |
17 | | std::mt19937& tls_gen(); |
18 | | |
19 | | /// Returns a random integer with uniform distribution within the specified bounds. |
20 | | template <typename Integer> |
21 | | Integer uniform_int(Integer min, Integer max) |
22 | 0 | { |
23 | 0 | return std::uniform_int_distribution<Integer>{min, max}(tls_gen()); |
24 | 0 | } Unexecuted instantiation: unsigned char ocudu::test_rng::uniform_int<unsigned char>(unsigned char, unsigned char) Unexecuted instantiation: unsigned int ocudu::test_rng::uniform_int<unsigned int>(unsigned int, unsigned int) |
25 | | template <typename Integer> |
26 | | Integer uniform_int() |
27 | 0 | { |
28 | 0 | return uniform_int(std::numeric_limits<Integer>::min(), std::numeric_limits<Integer>::max()); |
29 | 0 | } |
30 | | |
31 | | /// Returns a random boolean with probability \c p of being true. |
32 | | inline bool bernoulli(double p = 0.5) |
33 | 0 | { |
34 | 0 | return std::bernoulli_distribution(p)(tls_gen()); |
35 | 0 | } |
36 | | |
37 | | /// Returns a random floating point value with normal distribution. |
38 | | template <typename FloatingPoint> |
39 | | FloatingPoint normal_dist(FloatingPoint mean, FloatingPoint stddev) |
40 | | { |
41 | | return std::normal_distribution<FloatingPoint>(mean, stddev)(tls_gen()); |
42 | | } |
43 | | |
44 | | /// Return a vector of integers with specified size filled with random values. |
45 | | template <typename Integer> |
46 | | std::vector<Integer> vector_of_uniform_ints(size_t sz) |
47 | | { |
48 | | std::uniform_int_distribution<Integer> dist{std::numeric_limits<Integer>::min(), std::numeric_limits<Integer>::max()}; |
49 | | auto& rng = tls_gen(); |
50 | | |
51 | | std::vector<Integer> vec(sz); |
52 | | for (unsigned i = 0; i != sz; ++i) { |
53 | | vec[i] = dist(rng); |
54 | | } |
55 | | return vec; |
56 | | } |
57 | | |
58 | | } // namespace ocudu::test_rng |