SOLA
Loading...
Searching...
No Matches
distribution.h
1// Copyright 2023 The SOLA authors
2//
3// This file is part of DAISI.
4//
5// DAISI is free software: you can redistribute it and/or modify it under the terms of the GNU
6// General Public License as published by the Free Software Foundation; version 2.
7//
8// DAISI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
9// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
10// Public License for more details.
11//
12// You should have received a copy of the GNU General Public License along with DAISI. If not, see
13// <https://www.gnu.org/licenses/>.
14//
15// SPDX-License-Identifier: GPL-2.0-only
16
17#ifndef DAISI_UTILS_DISTRIBUTION_H_
18#define DAISI_UTILS_DISTRIBUTION_H_
19
20#include <random>
21#include <variant>
22
23namespace daisi {
24
25/*
26 * Container for different random distributions
27 * with unified API to get the next random value
28 */
29template <typename T> struct Dist {
33 template <typename Generator> T operator()(Generator &gen) {
34 static_assert(std::is_integral_v<T>, "T needs to be an integral type");
35 if (auto fixed = std::get_if<T>(&dist)) {
36 return *fixed;
37 }
38
39 if (auto normal = std::get_if<std::normal_distribution<double>>(&dist)) {
40 double number = normal->operator()(gen);
41 return static_cast<uint64_t>(std::clamp(number, 0.0, std::numeric_limits<double>::max()));
42 }
43
44 if (auto uniform = std::get_if<std::uniform_int_distribution<T>>(&dist)) {
45 return uniform->operator()(gen);
46 }
47
48 if (auto discrete = std::get_if<std::discrete_distribution<T>>(&dist)) {
49 return discrete->operator()(gen);
50 }
51 throw std::runtime_error("invalid distribution");
52 }
53
54 std::variant<T, std::normal_distribution<double>, std::uniform_int_distribution<T>,
55 std::discrete_distribution<T>>
56 dist;
57};
58
59} // namespace daisi
60#endif
Definition distribution.h:29
T operator()(Generator &gen)
Definition distribution.h:33