Eigen  3.4.90 (git rev 5a9f66fb35d03a4da9ef8976e67a61b30aa16dcf)
 
Loading...
Searching...
No Matches
RandomImpl.h
1// This file is part of Eigen, a lightweight C++ template library
2// for linear algebra.
3//
4// Copyright (C) 2024 Charles Schlosser <[email protected]>
5//
6// This Source Code Form is subject to the terms of the Mozilla
7// Public License v. 2.0. If a copy of the MPL was not distributed
8// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
9
10#ifndef EIGEN_RANDOM_IMPL_H
11#define EIGEN_RANDOM_IMPL_H
12
13// IWYU pragma: private
14#include "./InternalHeaderCheck.h"
15
16namespace Eigen {
17
18namespace internal {
19
20/****************************************************************************
21 * Implementation of random *
22 ****************************************************************************/
23
24template <typename Scalar, bool IsComplex, bool IsInteger>
25struct random_default_impl {};
26
27template <typename Scalar>
28struct random_impl : random_default_impl<Scalar, NumTraits<Scalar>::IsComplex, NumTraits<Scalar>::IsInteger> {};
29
30template <typename Scalar>
31struct random_retval {
32 typedef Scalar type;
33};
34
35template <typename Scalar>
36inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random(const Scalar& x, const Scalar& y) {
37 return EIGEN_MATHFUNC_IMPL(random, Scalar)::run(x, y);
38}
39
40template <typename Scalar>
41inline EIGEN_MATHFUNC_RETVAL(random, Scalar) random() {
42 return EIGEN_MATHFUNC_IMPL(random, Scalar)::run();
43}
44
45// TODO: replace or provide alternatives to this, e.g. std::random_device
46struct eigen_random_device {
47 using ReturnType = int;
48 static constexpr int Entropy = meta_floor_log2<(unsigned int)(RAND_MAX) + 1>::value;
49 static constexpr ReturnType Highest = RAND_MAX;
50 static EIGEN_DEVICE_FUNC inline ReturnType run() { return std::rand(); }
51};
52
53// Fill a built-in unsigned integer with numRandomBits beginning with the least significant bit
54template <typename Scalar>
55struct random_bits_impl {
56 EIGEN_STATIC_ASSERT(std::is_unsigned<Scalar>::value, SCALAR MUST BE A BUILT - IN UNSIGNED INTEGER)
57 using RandomDevice = eigen_random_device;
58 using RandomReturnType = typename RandomDevice::ReturnType;
59 static constexpr int kEntropy = RandomDevice::Entropy;
60 static constexpr int kTotalBits = sizeof(Scalar) * CHAR_BIT;
61 // return a Scalar filled with numRandomBits beginning from the least significant bit
62 static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) {
63 eigen_assert((numRandomBits >= 0) && (numRandomBits <= kTotalBits));
64 const Scalar mask = Scalar(-1) >> ((kTotalBits - numRandomBits) & (kTotalBits - 1));
65 Scalar randomBits = 0;
66 for (int shift = 0; shift < numRandomBits; shift += kEntropy) {
67 RandomReturnType r = RandomDevice::run();
68 randomBits |= static_cast<Scalar>(r) << shift;
69 }
70 // clear the excess bits
71 randomBits &= mask;
72 return randomBits;
73 }
74};
75
76template <typename BitsType>
77EIGEN_DEVICE_FUNC inline BitsType getRandomBits(int numRandomBits) {
78 return random_bits_impl<BitsType>::run(numRandomBits);
79}
80
81// random implementation for a built-in floating point type
82template <typename Scalar, bool BuiltIn = std::is_floating_point<Scalar>::value>
83struct random_float_impl {
84 using BitsType = typename numext::get_integer_by_size<sizeof(Scalar)>::unsigned_type;
85 static constexpr EIGEN_DEVICE_FUNC inline int mantissaBits() {
86 const int digits = NumTraits<Scalar>::digits();
87 return digits - 1;
88 }
89 static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) {
90 eigen_assert(numRandomBits >= 0 && numRandomBits <= mantissaBits());
91 BitsType randomBits = getRandomBits<BitsType>(numRandomBits);
92 // if fewer than MantissaBits is requested, shift them to the left
93 randomBits <<= (mantissaBits() - numRandomBits);
94 // randomBits is in the half-open interval [2,4)
95 randomBits |= numext::bit_cast<BitsType>(Scalar(2));
96 // result is in the half-open interval [-1,1)
97 Scalar result = numext::bit_cast<Scalar>(randomBits) - Scalar(3);
98 return result;
99 }
100};
101// random implementation for a custom floating point type
102// uses double as the implementation with a mantissa with a size equal to either the target scalar's mantissa or that of
103// double, whichever is smaller
104template <typename Scalar>
105struct random_float_impl<Scalar, false> {
106 static EIGEN_DEVICE_FUNC inline int mantissaBits() {
107 const int digits = NumTraits<Scalar>::digits();
108 constexpr int kDoubleDigits = NumTraits<double>::digits();
109 return numext::mini(digits, kDoubleDigits) - 1;
110 }
111 static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) {
112 eigen_assert(numRandomBits >= 0 && numRandomBits <= mantissaBits());
113 Scalar result = static_cast<Scalar>(random_float_impl<double>::run(numRandomBits));
114 return result;
115 }
116};
117
118// random implementation for long double
119// this specialization is not compatible with double-double scalars
120template <bool Specialize = (sizeof(long double) == 2 * sizeof(uint64_t)) &&
121 ((std::numeric_limits<long double>::digits != (2 * std::numeric_limits<double>::digits)))>
122struct random_longdouble_impl {
123 static constexpr int Size = sizeof(long double);
124 static constexpr EIGEN_DEVICE_FUNC inline int mantissaBits() { return NumTraits<long double>::digits() - 1; }
125 static EIGEN_DEVICE_FUNC inline long double run(int numRandomBits) {
126 eigen_assert(numRandomBits >= 0 && numRandomBits <= mantissaBits());
127 EIGEN_USING_STD(memcpy);
128 int numLowBits = numext::mini(numRandomBits, 64);
129 int numHighBits = numext::maxi(numRandomBits - 64, 0);
130 uint64_t randomBits[2];
131 long double result = 2.0L;
132 memcpy(&randomBits, &result, Size);
133 randomBits[0] |= getRandomBits<uint64_t>(numLowBits);
134 randomBits[1] |= getRandomBits<uint64_t>(numHighBits);
135 memcpy(&result, &randomBits, Size);
136 result -= 3.0L;
137 return result;
138 }
139};
140template <>
141struct random_longdouble_impl<false> {
142 static constexpr EIGEN_DEVICE_FUNC inline int mantissaBits() { return NumTraits<double>::digits() - 1; }
143 static EIGEN_DEVICE_FUNC inline long double run(int numRandomBits) {
144 return static_cast<long double>(random_float_impl<double>::run(numRandomBits));
145 }
146};
147template <>
148struct random_float_impl<long double> : random_longdouble_impl<> {};
149
150template <typename Scalar>
151struct random_default_impl<Scalar, false, false> {
152 using Impl = random_float_impl<Scalar>;
153 static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y, int numRandomBits) {
154 Scalar half_x = Scalar(0.5) * x;
155 Scalar half_y = Scalar(0.5) * y;
156 Scalar result = (half_x + half_y) + (half_y - half_x) * run(numRandomBits);
157 // result is in the half-open interval [x, y) -- provided that x < y
158 return result;
159 }
160 static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y) {
161 return run(x, y, Impl::mantissaBits());
162 }
163 static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) { return Impl::run(numRandomBits); }
164 static EIGEN_DEVICE_FUNC inline Scalar run() { return run(Impl::mantissaBits()); }
165};
166
167template <typename Scalar, bool IsSigned = NumTraits<Scalar>::IsSigned, bool BuiltIn = std::is_integral<Scalar>::value>
168struct random_int_impl;
169
170// random implementation for a built-in unsigned integer type
171template <typename Scalar>
172struct random_int_impl<Scalar, false, true> {
173 static constexpr int kTotalBits = sizeof(Scalar) * CHAR_BIT;
174 static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y) {
175 if (y <= x) return x;
176 Scalar range = y - x;
177 // handle edge case where [x,y] spans the entire range of Scalar
178 if (range == NumTraits<Scalar>::highest()) return run();
179 Scalar count = range + 1;
180 // calculate the number of random bits needed to fill range
181 int numRandomBits = log2_ceil(count);
182 Scalar randomBits;
183 do {
184 randomBits = getRandomBits<Scalar>(numRandomBits);
185 // if the random draw is outside [0, range), try again (rejection sampling)
186 // in the worst-case scenario, the probability of rejection is: 1/2 - 1/2^numRandomBits < 50%
187 } while (randomBits >= count);
188 Scalar result = x + randomBits;
189 return result;
190 }
191 static EIGEN_DEVICE_FUNC inline Scalar run() { return getRandomBits<Scalar>(kTotalBits); }
192};
193
194// random implementation for a built-in signed integer type
195template <typename Scalar>
196struct random_int_impl<Scalar, true, true> {
197 static constexpr int kTotalBits = sizeof(Scalar) * CHAR_BIT;
198 using BitsType = typename make_unsigned<Scalar>::type;
199 static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y) {
200 if (y <= x) return x;
201 // Avoid overflow by representing `range` as an unsigned type
202 BitsType range = static_cast<BitsType>(y) - static_cast<BitsType>(x);
203 BitsType randomBits = random_int_impl<BitsType>::run(0, range);
204 // Avoid overflow in the case where `x` is negative and there is a large range so
205 // `randomBits` would also be negative if cast to `Scalar` first.
206 Scalar result = static_cast<Scalar>(static_cast<BitsType>(x) + randomBits);
207 return result;
208 }
209 static EIGEN_DEVICE_FUNC inline Scalar run() { return static_cast<Scalar>(getRandomBits<BitsType>(kTotalBits)); }
210};
211
212// todo: custom integers
213template <typename Scalar, bool IsSigned>
214struct random_int_impl<Scalar, IsSigned, false> {
215 static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar&, const Scalar&) { return run(); }
216 static EIGEN_DEVICE_FUNC inline Scalar run() {
217 eigen_assert(std::false_type::value && "RANDOM FOR CUSTOM INTEGERS NOT YET SUPPORTED");
218 return Scalar(0);
219 }
220};
221
222template <typename Scalar>
223struct random_default_impl<Scalar, false, true> : random_int_impl<Scalar> {};
224
225template <>
226struct random_impl<bool> {
227 static EIGEN_DEVICE_FUNC inline bool run(const bool& x, const bool& y) {
228 if (y <= x) return x;
229 return run();
230 }
231 static EIGEN_DEVICE_FUNC inline bool run() { return getRandomBits<unsigned>(1) ? true : false; }
232};
233
234template <typename Scalar>
235struct random_default_impl<Scalar, true, false> {
236 typedef typename NumTraits<Scalar>::Real RealScalar;
237 using Impl = random_impl<RealScalar>;
238 static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y, int numRandomBits) {
239 return Scalar(Impl::run(x.real(), y.real(), numRandomBits), Impl::run(x.imag(), y.imag(), numRandomBits));
240 }
241 static EIGEN_DEVICE_FUNC inline Scalar run(const Scalar& x, const Scalar& y) {
242 return Scalar(Impl::run(x.real(), y.real()), Impl::run(x.imag(), y.imag()));
243 }
244 static EIGEN_DEVICE_FUNC inline Scalar run(int numRandomBits) {
245 return Scalar(Impl::run(numRandomBits), Impl::run(numRandomBits));
246 }
247 static EIGEN_DEVICE_FUNC inline Scalar run() { return Scalar(Impl::run(), Impl::run()); }
248};
249
250} // namespace internal
251} // namespace Eigen
252
253#endif // EIGEN_RANDOM_IMPL_H
Namespace containing all symbols from the Eigen library.
Definition Core:137