Momentum
A library for solving nonlinear optimization problems related to human body kinematics
Loading...
Searching...
No Matches
random-inl.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * This source code is licensed under the MIT license found in the
5 * LICENSE file in the root directory of this source tree.
6 */
7
8#pragma once
9
11#include <momentum/math/types.h>
12
13#include <algorithm>
14#include <limits>
15
16namespace momentum {
17
18namespace detail {
19
20template <typename RealType>
21using UniformRealDist = std::uniform_real_distribution<RealType>;
22
23template <typename IntType>
24using UniformIntDist = std::uniform_int_distribution<IntType>;
25
26template <typename RealType>
27using NormalRealDist = std::normal_distribution<RealType>;
28
29// Whitelists the integer types that std::uniform_int_distribution<T> permits.
30// The standard restricts the IntType template parameter to (un)signed
31// short/int/long/long long; using e.g. char or int8_t is undefined behavior.
32// Ref: https://en.cppreference.com/w/cpp/numeric/random/uniform_int_distribution
33template <typename T>
35 : std::disjunction<
36 std::is_same<std::remove_cv_t<T>, short>,
37 std::is_same<std::remove_cv_t<T>, int>,
38 std::is_same<std::remove_cv_t<T>, long>,
39 std::is_same<std::remove_cv_t<T>, long long>,
40 std::is_same<std::remove_cv_t<T>, unsigned short>,
41 std::is_same<std::remove_cv_t<T>, unsigned int>,
42 std::is_same<std::remove_cv_t<T>, unsigned long>,
43 std::is_same<std::remove_cv_t<T>, unsigned long long>> {};
44
45template <typename T>
48
49template <template <typename...> class C, typename... Ts>
50std::true_type is_base_of_template_impl(const C<Ts...>*);
51
52template <template <typename...> class C>
53std::false_type is_base_of_template_impl(...);
54
55template <template <typename...> class C, typename T>
56using is_base_of_template = decltype(is_base_of_template_impl<C>(std::declval<T*>()));
57
58template <typename T>
60
61template <typename T>
63
64// Note: when T is neither floating-point nor a whitelisted integer type
65// (e.g. bool, char, int8_t, uint8_t), no branch is taken and the function
66// returns a value-initialized T. TODO: consider a static_assert to fail at
67// compile time instead of silently returning T{}.
68template <typename T, typename Generator>
69[[nodiscard]] T generateScalarUniform(const T& min, const T& max, Generator& generator) {
70 if constexpr (std::is_floating_point_v<T>) {
71 // std::uniform_real_distribution generates on the half-open interval
72 // [min, max); some implementations may return max due to rounding.
73 UniformRealDist<T> dist(min, max);
74 return dist(generator);
76 // Closed interval [min, max] for integer distribution.
77 UniformIntDist<T> dist(min, max);
78 return dist(generator);
79 }
80}
81
82// Generates a random vector/matrix element-wise. The four `if constexpr`
83// branches dispatch to the matching Eigen NullaryExpr overload (matrix vs
84// vector, dynamic vs fixed) since each takes a different signature for the
85// size arguments and the generator lambda.
86template <typename Derived, typename Generator>
87[[nodiscard]] typename Derived::PlainObject generateMatrixUniform(
88 const Eigen::MatrixBase<Derived>& min,
89 const Eigen::MatrixBase<Derived>& max,
90 Generator& generator) {
91 if constexpr (!Derived::IsVectorAtCompileTime && Derived::SizeAtCompileTime == Eigen::Dynamic) {
92 return Derived::PlainObject::NullaryExpr(
93 min.rows(), min.cols(), [&](const Eigen::Index i, const Eigen::Index j) {
94 return generateScalarUniform<typename Derived::Scalar>(min(i, j), max(i, j), generator);
95 });
96 } else if constexpr (
97 !Derived::IsVectorAtCompileTime && Derived::SizeAtCompileTime != Eigen::Dynamic) {
98 return Derived::PlainObject::NullaryExpr([&](const Eigen::Index i, const Eigen::Index j) {
99 return generateScalarUniform<typename Derived::Scalar>(min(i, j), max(i, j), generator);
100 });
101 } else if constexpr (
102 Derived::IsVectorAtCompileTime && Derived::SizeAtCompileTime == Eigen::Dynamic) {
103 return Derived::PlainObject::NullaryExpr(min.size(), [&](const Eigen::Index i) {
104 return generateScalarUniform<typename Derived::Scalar>(min[i], max[i], generator);
105 });
106 } else if constexpr (
107 Derived::IsVectorAtCompileTime && Derived::SizeAtCompileTime != Eigen::Dynamic) {
108 return Derived::PlainObject::NullaryExpr([&](const Eigen::Index i) {
109 return generateScalarUniform<typename Derived::Scalar>(min[i], max[i], generator);
110 });
111 }
112};
113
114template <typename T, typename Generator>
115[[nodiscard]] T generateUniform(const T& min, const T& max, Generator& generator) {
116 if constexpr (std::is_arithmetic_v<T>) {
117 return generateScalarUniform(min, max, generator);
118 } else if constexpr (is_base_of_matrix_v<T>) {
119 return generateMatrixUniform(min, max, generator);
120 }
121}
122
123template <typename T, typename Generator>
124[[nodiscard]] T generateScalarNormal(const T& mean, const T& sigma, Generator& generator) {
125 if constexpr (std::is_floating_point_v<T>) {
126 NormalRealDist<T> dist(mean, sigma);
127 return dist(generator);
129 // No discrete normal distribution exists in <random>; sample from a double normal then round
130 // to the nearest integer. Use `double` (not `float`) so the precision is sufficient for
131 // 64-bit integer T, and clamp the rounded result to T's representable range so a tail sample
132 // does not invoke undefined behavior in the narrowing cast.
133 const double realNumber = NormalRealDist<double>(mean, sigma)(generator);
134 const double rounded = std::round(realNumber);
135 const double clamped = std::clamp(
136 rounded,
137 static_cast<double>(std::numeric_limits<T>::lowest()),
138 static_cast<double>(std::numeric_limits<T>::max()));
139 return static_cast<T>(clamped);
140 }
141}
142
143// Generates a random vector/matrix element-wise. Each element is drawn
144// independently — this is NOT a multivariate normal (no covariance structure);
145// `sigma` supplies a per-element standard deviation.
146template <typename Derived, typename Generator>
147[[nodiscard]] typename Derived::PlainObject generateMatrixNormal(
148 const Eigen::MatrixBase<Derived>& mean,
149 const Eigen::MatrixBase<Derived>& sigma,
150 Generator& generator) {
151 if constexpr (!Derived::IsVectorAtCompileTime && Derived::SizeAtCompileTime == Eigen::Dynamic) {
152 return Derived::PlainObject::NullaryExpr(
153 mean.rows(), mean.cols(), [&](const Eigen::Index i, const Eigen::Index j) {
154 return generateScalarNormal<typename Derived::Scalar>(mean(i, j), sigma(i, j), generator);
155 });
156 } else if constexpr (
157 !Derived::IsVectorAtCompileTime && Derived::SizeAtCompileTime != Eigen::Dynamic) {
158 return Derived::PlainObject::NullaryExpr([&](const Eigen::Index i, const Eigen::Index j) {
159 return generateScalarNormal<typename Derived::Scalar>(mean(i, j), sigma(i, j), generator);
160 });
161 } else if constexpr (
162 Derived::IsVectorAtCompileTime && Derived::SizeAtCompileTime == Eigen::Dynamic) {
163 return Derived::PlainObject::NullaryExpr(mean.size(), [&](const Eigen::Index i) {
164 return generateScalarNormal<typename Derived::Scalar>(mean[i], sigma[i], generator);
165 });
166 } else if constexpr (
167 Derived::IsVectorAtCompileTime && Derived::SizeAtCompileTime != Eigen::Dynamic) {
168 return Derived::PlainObject::NullaryExpr([&](const Eigen::Index i) {
169 return generateScalarNormal<typename Derived::Scalar>(mean[i], sigma[i], generator);
170 });
171 }
172};
173
174template <typename T, typename Generator>
175[[nodiscard]] T generateNormal(const T& mean, const T& sigma, Generator& generator) {
176 if constexpr (std::is_arithmetic_v<T>) {
177 return generateScalarNormal(mean, sigma, generator);
178 } else if constexpr (is_base_of_matrix_v<T>) {
179 return generateMatrixNormal(mean, sigma, generator);
180 }
181}
182
183} // namespace detail
184
185template <typename Generator>
187 static Random<Generator> singleton;
188 return singleton;
189}
190
191template <typename Generator>
192Random<Generator>::Random(uint32_t seed) : seed_(seed), generator_(seed_) {}
193
194template <typename Generator>
195template <typename T>
196T Random<Generator>::uniform(const T& min, const T& max) {
197 return detail::generateUniform(min, max, generator_);
198}
199
200template <typename Generator>
201template <typename FixedSizeT>
203 typename FixedSizeT::Scalar min,
204 typename FixedSizeT::Scalar max) {
206 FixedSizeT::Constant(min), FixedSizeT::Constant(max), generator_);
207}
208
209template <typename Generator>
210template <typename DynamicVector>
212 Eigen::Index size,
213 typename DynamicVector::Scalar min,
214 typename DynamicVector::Scalar max) {
216 DynamicVector::Constant(size, min), DynamicVector::Constant(size, max), generator_);
217}
218
219template <typename Generator>
220template <typename DynamicMatrix>
222 Eigen::Index rows,
223 Eigen::Index cols,
224 typename DynamicMatrix::Scalar min,
225 typename DynamicMatrix::Scalar max) {
227 DynamicMatrix::Constant(rows, cols, min),
228 DynamicMatrix::Constant(rows, cols, max),
229 generator_);
230}
231
232template <typename Generator>
233template <typename T>
237
238template <typename Generator>
239template <typename T>
243
244template <typename Generator>
245template <typename T>
248 out.linear() = uniformRotationMatrix<T>();
249 out.translation() = uniform<Vector3<T>>(min, max);
250 return out;
251}
252
253template <typename Generator>
254template <typename T>
256 T scaleMin,
257 T scaleMax,
258 const Vector3<T>& min,
259 const Vector3<T>& max) {
260 static_assert(
261 std::is_floating_point_v<T>,
262 "uniformAffine3 requires a floating-point T; integer T would silently truncate the "
263 "default scale range and the rotation factor.");
265 // Linear part is rotation * isotropic_scale; this samples a single scale
266 // factor applied to all three axes, not a full anisotropic affine.
267 out.linear() = uniformRotationMatrix<T>() * uniform<T>(scaleMin, scaleMax);
268 out.translation().noalias() = uniform<Vector3<T>>(min, max);
269 return out;
270}
271
272template <typename Generator>
273template <typename T>
274T Random<Generator>::normal(const T& mean, const T& sigma) {
275 return detail::generateNormal(mean, sigma, generator_);
276}
277
278template <typename Generator>
279template <typename FixedSizeT>
281 typename FixedSizeT::Scalar mean,
282 typename FixedSizeT::Scalar sigma) {
284 FixedSizeT::Constant(mean), FixedSizeT::Constant(sigma), generator_);
285}
286
287template <typename Generator>
288template <typename DynamicVector>
290 Eigen::Index size,
291 typename DynamicVector::Scalar mean,
292 typename DynamicVector::Scalar sigma) {
294 DynamicVector::Constant(size, mean), DynamicVector::Constant(size, sigma), generator_);
295}
296
297template <typename Generator>
298template <typename DynamicMatrix>
300 Eigen::Index rows,
301 Eigen::Index cols,
302 typename DynamicMatrix::Scalar mean,
303 typename DynamicMatrix::Scalar sigma) {
305 DynamicMatrix::Constant(rows, cols, mean),
306 DynamicMatrix::Constant(rows, cols, sigma),
307 generator_);
308}
309
310template <typename Generator>
312 return seed_;
313}
314
315template <typename Generator>
316void Random<Generator>::setSeed(uint32_t seed) {
317 // Always re-seed the engine, even when the value is unchanged. Callers (e.g. test fixtures that
318 // re-seed before every case) rely on setSeed() resetting the generator to the start of the
319 // deterministic sequence for `seed`; skipping the reset when seed == seed_ would silently leave
320 // the engine advanced by previous draws and make consumers order-dependent.
321 seed_ = seed;
322 generator_.seed(seed_);
323}
324
325template <typename T>
326T uniform(const T& min, const T& max) {
327 auto& rand = Random<>::GetSingleton();
328 return rand.uniform(min, max);
329}
330
331template <typename FixedSizeT>
332FixedSizeT uniform(typename FixedSizeT::Scalar min, typename FixedSizeT::Scalar max) {
333 auto& rand = Random<>::GetSingleton();
334 return rand.uniform<FixedSizeT>(min, max);
335}
336
337template <typename DynamicVector>
338DynamicVector
339uniform(Eigen::Index size, typename DynamicVector::Scalar min, typename DynamicVector::Scalar max) {
340 auto& rand = Random<>::GetSingleton();
341 return rand.uniform<DynamicVector>(size, min, max);
342}
343
344template <typename DynamicMatrix>
345DynamicMatrix uniform(
346 Eigen::Index rows,
347 Eigen::Index cols,
348 typename DynamicMatrix::Scalar min,
349 typename DynamicMatrix::Scalar max) {
350 auto& rand = Random<>::GetSingleton();
351 return rand.uniform<DynamicMatrix>(rows, cols, min, max);
352}
353
354template <typename T>
356 auto& rand = Random<>::GetSingleton();
357 return rand.uniformQuaternion<T>();
358}
359
360template <typename T>
362 return uniformQuaternion<T>().toRotationMatrix();
363}
364
365template <typename T>
367 auto& rand = Random<>::GetSingleton();
368 return rand.uniformIsometry3<T>(min, max);
369}
370
371template <typename T>
372Affine3<T> uniformAffine3(T scaleMin, T scaleMax, const Vector3<T>& min, const Vector3<T>& max) {
373 static_assert(
374 std::is_floating_point_v<T>,
375 "uniformAffine3 requires a floating-point T; integer T would silently truncate the "
376 "default scale range and the rotation factor.");
377 auto& rand = Random<>::GetSingleton();
378 return rand.uniformAffine3<T>(scaleMin, scaleMax, min, max);
379}
380
381template <typename T>
382T normal(const T& mean, const T& sigma) {
383 auto& rand = Random<>::GetSingleton();
384 return rand.normal(mean, sigma);
385}
386
387template <typename FixedSizeT>
388FixedSizeT normal(typename FixedSizeT::Scalar mean, typename FixedSizeT::Scalar sigma) {
389 auto& rand = Random<>::GetSingleton();
390 return rand.normal<FixedSizeT>(mean, sigma);
391}
392
393template <typename DynamicVector>
394DynamicVector normal(
395 Eigen::Index size,
396 typename DynamicVector::Scalar mean,
397 typename DynamicVector::Scalar sigma) {
398 auto& rand = Random<>::GetSingleton();
399 return rand.normal<DynamicVector>(size, mean, sigma);
400}
401
402template <typename DynamicMatrix>
403DynamicMatrix normal(
404 Eigen::Index rows,
405 Eigen::Index cols,
406 typename DynamicMatrix::Scalar mean,
407 typename DynamicMatrix::Scalar sigma) {
408 auto& rand = Random<>::GetSingleton();
409 return rand.normal<DynamicMatrix>(rows, cols, mean, sigma);
410}
411
412} // namespace momentum
static Random & GetSingleton()
Returns the process-wide singleton instance.
Definition random-inl.h:186
Affine3< T > uniformAffine3(T scaleMin=T(0.1), T scaleMax=T(10.0), const Vector3< T > &min=Vector3< T >::Zero(), const Vector3< T > &max=Vector3< T >::Ones())
Generates a random affine transformation with rotation drawn uniformly from SO(3),...
Definition random-inl.h:255
Quaternion< T > uniformQuaternion()
Generates a random unit quaternion uniformly distributed on SO(3) (Haar measure).
Definition random-inl.h:234
Matrix3< T > uniformRotationMatrix()
Generates a random rotation matrix uniformly distributed on SO(3) (Haar measure).
Definition random-inl.h:240
T normal(const T &mean, const T &sigma)
Generates a value from a normal (Gaussian) distribution N(mean, sigma^2).
Definition random-inl.h:274
Random(uint32_t seed=std::random_device{}())
Constructs a generator seeded with the given value.
Definition random-inl.h:192
void setSeed(uint32_t seed)
Re-seeds the internal engine, resetting its state to the deterministic sequence implied by seed.
Definition random-inl.h:316
uint32_t getSeed() const
Returns the seed last used to initialize the engine.
Definition random-inl.h:311
Isometry3< T > uniformIsometry3(const Vector3< T > &min=Vector3< T >::Zero(), const Vector3< T > &max=Vector3< T >::Ones())
Generates a random isometry (rigid transformation) on SE(3) with rotation drawn uniformly from SO(3) ...
Definition random-inl.h:246
T uniform(const T &min, const T &max)
Generates a random scalar/vector/matrix from the uniform distribution.
Definition random-inl.h:196
constexpr bool is_compatible_to_uniform_int_distribution_v
Definition random-inl.h:46
Derived::PlainObject generateMatrixUniform(const Eigen::MatrixBase< Derived > &min, const Eigen::MatrixBase< Derived > &max, Generator &generator)
Definition random-inl.h:87
T generateNormal(const T &mean, const T &sigma, Generator &generator)
Definition random-inl.h:175
Derived::PlainObject generateMatrixNormal(const Eigen::MatrixBase< Derived > &mean, const Eigen::MatrixBase< Derived > &sigma, Generator &generator)
Definition random-inl.h:147
std::uniform_real_distribution< RealType > UniformRealDist
Definition random-inl.h:21
std::normal_distribution< RealType > NormalRealDist
Definition random-inl.h:27
std::uniform_int_distribution< IntType > UniformIntDist
Definition random-inl.h:24
constexpr bool is_base_of_matrix_v
Definition random-inl.h:62
decltype(is_base_of_template_impl< C >(std::declval< T * >())) is_base_of_template
Definition random-inl.h:56
std::true_type is_base_of_template_impl(const C< Ts... > *)
is_base_of_template< Eigen::MatrixBase, T > is_base_of_matrix
Definition random-inl.h:59
T generateScalarUniform(const T &min, const T &max, Generator &generator)
Definition random-inl.h:69
T generateScalarNormal(const T &mean, const T &sigma, Generator &generator)
Definition random-inl.h:124
T generateUniform(const T &min, const T &max, Generator &generator)
Definition random-inl.h:115
T normal(const T &mean, const T &sigma)
Normally distributed value via the global Random singleton.
Definition random-inl.h:382
Matrix3< T > uniformRotationMatrix()
Uniformly distributed rotation matrix on SO(3) via the global Random singleton.
Definition random-inl.h:361
T uniform(const T &min, const T &max)
Convenience wrappers that forward to Random<>::GetSingleton().
Definition random-inl.h:326
Eigen::Matrix< T, 3, 3 > Matrix3
Definition types.h:96
Isometry3< T > uniformIsometry3(const Vector3< T > &min, const Vector3< T > &max)
Random isometry on SE(3) via the global Random singleton (uniform rotation, uniform translation in [m...
Definition random-inl.h:366
Eigen::Quaternion< T > Quaternion
Unit quaternion representing a 3D rotation.
Definition types.h:385
Eigen::Transform< T, 3, Eigen::Isometry > Isometry3
3D rigid transform (rotation + translation, no scale or shear).
Definition types.h:397
Quaternion< T > uniformQuaternion()
Uniformly distributed unit quaternion on SO(3) via the global Random singleton.
Definition random-inl.h:355
Vector< T, 3 > Vector3
Definition types.h:236
Affine3< T > uniformAffine3(T scaleMin, T scaleMax, const Vector3< T > &min, const Vector3< T > &max)
Random affine transformation via the global Random singleton (uniform rotation, uniform scale in [sca...
Definition random-inl.h:372
Eigen::Transform< T, 3, Eigen::Affine > Affine3
3D affine transform (linear part + translation).
Definition types.h:404