Block-Structured AMR Software Framework
Loading...
Searching...
No Matches
AMReX_Random.H
Go to the documentation of this file.
1#ifndef AMREX_RAND_H
2#define AMREX_RAND_H
3#include <AMReX_Config.H>
4
5#include <AMReX.H>
9#include <limits>
10#include <cmath>
11#include <cstdint>
12
13namespace amrex
14{
16 namespace random_util {
17
23 Real one_to_zero (Real v) noexcept { return (v == Real(1)) ? Real(0) : v; }
24
29 Real zero_to_one (Real v) noexcept { return (v == Real(0)) ? Real(1) : v; }
30
38 Real clamp_below_one (Real v) noexcept
39 {
40 // The constexpr equivalent of std::nextafter(Real(1), Real(0)), which
41 // is not available in device code. That this really is the immediate
42 // predecessor of one follows from the two assertions below: it is less
43 // than one, and the midpoint between it and one already rounds to one,
44 // so no Real lies in between. Tests/Base/Random additionally checks it
45 // against std::nextafter itself on the host.
46 constexpr Real almost_one
47 = Real(1) - Real(0.5)*std::numeric_limits<Real>::epsilon();
48 static_assert(almost_one < Real(1));
49 static_assert(Real(1) - Real(0.25)*std::numeric_limits<Real>::epsilon() == Real(1));
50 // No generator produces NaN, but note this maps it to almost_one
51 // rather than propagating it, since the comparison is false for NaN.
52 return (v < almost_one) ? v : almost_one;
53 }
54
55 }
57
74 Real Random ();
75
78 Real Random (RandomEngine const& random_engine)
79 {
80#if defined (__SYCL_DEVICE_ONLY__)
81 // clamped for the same reason as the host path: the documented [0,1)
82 // of the vendor generator is not a bound we want to depend on
83 mkl::rng::device::uniform<Real> distr;
84 return random_util::clamp_below_one(mkl::rng::device::generate(distr, *random_engine.engine));
85#else
86 // hiprand/curand draw from (0,1]. Relocating the single endpoint
87 // that is out of range converts that to the documented [0,1) exactly,
88 // with no arithmetic. Subtracting from one would also convert the
89 // interval, but not exactly: for a draw below half an ULP of one,
90 // `1 - draw` rounds back up to 1.0, and the subtraction additionally
91 // collapses every value below 0.5 onto a 2^-24 grid.
92#ifdef BL_USE_FLOAT
95 return random_util::one_to_zero(hiprand_uniform(random_engine.rand_state)); ,
96 return random_util::one_to_zero(curand_uniform(random_engine.rand_state));
97 )
98 ))
99#else
102 return random_util::one_to_zero(hiprand_uniform_double(random_engine.rand_state)); ,
103 return random_util::one_to_zero(curand_uniform_double(random_engine.rand_state));
104 )
105 ))
106#endif
108 amrex::ignore_unused(random_engine);
109 return Random();
110 ))
111#endif
112 }
113
169
172 Real RandomPositive (RandomEngine const& random_engine)
173 {
174#if defined (__SYCL_DEVICE_ONLY__)
175 // oneMKL draws from [0,1); relocating the zero endpoint converts that
176 // to (0,1] with no arithmetic, and stays correct even if the
177 // generator reaches its own upper bound, since 1.0 is in range here
178 mkl::rng::device::uniform<Real> distr;
179 return random_util::zero_to_one(mkl::rng::device::generate(distr, *random_engine.engine));
180#else
181 // (0,1] is the native interval of hiprand/curand, so unlike Random()
182 // this needs no endpoint relocated and no clamp: the draw is
183 // returned exactly as the generator produced it.
184#ifdef BL_USE_FLOAT
187 return hiprand_uniform(random_engine.rand_state); ,
188 return curand_uniform(random_engine.rand_state);
189 )
190 ))
191#else
194 return hiprand_uniform_double(random_engine.rand_state); ,
195 return curand_uniform_double(random_engine.rand_state);
196 )
197 ))
198#endif
200 amrex::ignore_unused(random_engine);
201 return RandomPositive();
202 ))
203#endif
204 }
205
214 Real RandomNormal (Real mean, Real stddev);
215
218 Real RandomNormal (Real mean, Real stddev, RandomEngine const& random_engine)
219 {
220#if defined (__SYCL_DEVICE_ONLY__)
221 mkl::rng::device::gaussian<Real> distr(mean, stddev);
222 return mkl::rng::device::generate(distr, *random_engine.engine);
223#else
224#ifdef BL_USE_FLOAT
227 return stddev * hiprand_normal(random_engine.rand_state) + mean; ,
228 return stddev * curand_normal(random_engine.rand_state) + mean;
229 )
230 ))
231#else
234 return stddev * hiprand_normal_double(random_engine.rand_state) + mean; ,
235 return stddev * curand_normal_double(random_engine.rand_state) + mean;
236 )
237 ))
238#endif
240 amrex::ignore_unused(random_engine);
241 return RandomNormal(mean, stddev);
242 ))
243#endif
244 }
245
256 unsigned int RandomPoisson (Real lambda);
257
260 unsigned int RandomPoisson (Real lambda, RandomEngine const& random_engine)
261 {
262#if defined (__SYCL_DEVICE_ONLY__)
263 mkl::rng::device::poisson<unsigned int> distr(lambda);
264 return mkl::rng::device::generate(distr, *random_engine.engine);
265#else
268 return hiprand_poisson(random_engine.rand_state, lambda); ,
269 return curand_poisson(random_engine.rand_state, lambda);
270 )
271 ))
273 amrex::ignore_unused(random_engine);
274 return RandomPoisson(lambda);
275 ))
276#endif
277 }
278
280 namespace random_util {
281
283 Real RandomGamma_alpha_ge_1 (Real alpha, Real beta, RandomEngine const& random_engine)
284 {
285 AMREX_ASSERT(alpha >= 1);
286 AMREX_ASSERT(beta > 0);
287
288 Real x, v, u;
289 Real d = alpha - 1.0_rt / 3.0_rt;
290 Real c = (1.0_rt / 3.0_rt) / std::sqrt(d);
291
292 while (true) {
293 do {
294 x = amrex::RandomNormal(0.0_rt, 1.0_rt, random_engine);
295 v = 1.0_rt + c * x;
296 } while (v <= 0.0_rt);
297
298 v = v * v * v;
299 u = amrex::RandomPositive(random_engine); // std::log(u) below
300
301 if (u < 1.0_rt - 0.0331_rt * x * x * x * x) {
302 break;
303 }
304
305 if (std::log(u) < 0.5_rt * x * x + d * (1.0_rt - v + std::log(v))) {
306 break;
307 }
308 }
309 return beta * d * v;
310 }
311 }
313
326 Real RandomGamma (Real alpha, Real beta);
327
330 Real RandomGamma (Real alpha, Real beta, RandomEngine const& random_engine)
331 {
332 AMREX_ASSERT(alpha > 0);
333 AMREX_ASSERT(beta > 0);
334
336 if (alpha < 1)
337 {
338 Real u = amrex::RandomPositive(random_engine); // std::pow(u, 1/alpha) below
339 return amrex::random_util::RandomGamma_alpha_ge_1(1.0_rt + alpha, beta, random_engine) * std::pow(u, 1.0_rt / alpha);
340 } else {
341 return amrex::random_util::RandomGamma_alpha_ge_1(alpha, beta, random_engine);
342 }
343 ))
344
346 amrex::ignore_unused(random_engine);
347 return RandomGamma(alpha, beta);
348 ))
349 }
350
360 unsigned int Random_int (unsigned int n); // [0,n-1]
361
364 unsigned int Random_int (unsigned int n, RandomEngine const& random_engine)
365 {
366 if (n == 0) { return 0;}
367#if defined(__SYCL_DEVICE_ONLY__)
368 mkl::rng::device::uniform<unsigned int> distr(0,n);
369 return mkl::rng::device::generate(distr, *random_engine.engine);
370#else
372 unsigned int rand;
373 constexpr unsigned int RAND_M = 4294967295; // 2**32-1
374 do {
375 AMREX_HIP_OR_CUDA( rand = hiprand(random_engine.rand_state);,
376 rand = curand(random_engine.rand_state) );
377 } while (rand >= (RAND_M - RAND_M % n));
378 return rand % n;
379 ))
381 amrex::ignore_unused(random_engine);
382 return Random_int(n);
383 ))
384#endif
385 }
386
396 ULong Random_long (ULong n); // [0,n-1]
397
406 void FillRandom (Real* p, Long N);
407
410 void FillRandomNormal (Real* p, Long N, Real mean, Real stddev);
411
413 namespace detail {
414 inline ULong DefaultGpuSeed () {
415 return ParallelDescriptor::MyProc()*1234567ULL + 12345ULL;
416 }
417 }
419
433 void InitRandom (ULong cpu_seed, int nprocs=ParallelDescriptor::NProcs(),
434 ULong gpu_seed = detail::DefaultGpuSeed());
435
437 void ResetRandomSeed (ULong cpu_seed, ULong gpu_seed = detail::DefaultGpuSeed());
438
447 void SaveRandomState (std::ostream& os);
448
456 void RestoreRandomState (std::istream& is, int nthreads_old, int nstep_old);
457
468 void UniqueRandomSubset (Vector<int> &uSet, int setSize, int poolSize,
469 bool printSet = false);
470
472}
473
474#endif
Runtime initialization/finalization helpers and global diagnostics.
#define AMREX_ASSERT(EX)
Definition AMReX_BLassert.H:38
#define AMREX_FORCE_INLINE
Definition AMReX_Extension.H:124
#define AMREX_HIP_OR_CUDA(a, b)
Definition AMReX_GpuControl.H:17
#define AMREX_IF_ON_DEVICE(CODE)
Definition AMReX_GpuQualifiers.H:56
#define AMREX_IF_ON_HOST(CODE)
Definition AMReX_GpuQualifiers.H:58
#define AMREX_GPU_DEVICE
Definition AMReX_GpuQualifiers.H:18
#define AMREX_GPU_HOST_DEVICE
Definition AMReX_GpuQualifiers.H:20
amrex_real Real
Floating Point Type for Fields.
Definition AMReX_REAL.H:79
amrex_ulong ULong
Unsigned integer type guaranteed to be wider than unsigned int.
Definition AMReX_INT.H:32
amrex_long Long
Definition AMReX_INT.H:30
int MyProc() noexcept
Definition AMReX_ParallelDescriptor.H:128
int NProcs() noexcept
Definition AMReX_ParallelDescriptor.H:255
void InitRandom(ULong cpu_seed, int nprocs, ULong gpu_seed)
Set the seed of the random number generator.
Definition AMReX_Random.cpp:99
unsigned int Random_int(unsigned int n)
Generates one pseudorandom unsigned integer which is uniformly distributed on [0,n-1]-interval for ea...
Definition AMReX_Random.cpp:173
Real Random()
Generate a psuedo-random real from uniform distribution.
Definition AMReX_Random.cpp:142
Real RandomPositive()
Generate a pseudo-random real from uniform distribution, excluding zero.
Definition AMReX_Random.cpp:149
Real RandomNormal(Real mean, Real stddev)
Generate a psuedo-random real from a normal distribution.
Definition AMReX_Random.cpp:126
ULong Random_long(ULong n)
Generates one pseudorandom unsigned long which is uniformly distributed on [0,n-1]-interval for each ...
Definition AMReX_Random.cpp:181
void ResetRandomSeed(ULong cpu_seed, ULong gpu_seed)
Definition AMReX_Random.cpp:246
void UniqueRandomSubset(Vector< int > &uSet, int setSize, int poolSize, bool printSet)
Create a unique subset of random numbers from a pool of integers in the range [0, poolSize - 1] the s...
Definition AMReX_Random.cpp:224
unsigned int RandomPoisson(Real lambda)
Generate a psuedo-random integer from a Poisson distribution.
Definition AMReX_Random.cpp:159
void SaveRandomState(std::ostream &os)
Save host random state.
Definition AMReX_Random.cpp:190
void RestoreRandomState(std::istream &is, int nthreads_old, int nstep_old)
Restore host random state saved by SaveRandomState.
Definition AMReX_Random.cpp:198
Real RandomGamma(Real alpha, Real beta)
Generate a psuedo-random floating point number from the Gamma distribution.
Definition AMReX_Random.cpp:166
Definition AMReX_Amr.cpp:50
__host__ __device__ void ignore_unused(const Ts &...)
No-op helper that marks variables as intentionally unused.
Definition AMReX.H:259
void FillRandomNormal(MultiFab &mf, int scomp, int ncomp, Real mean, Real stddev)
Fill MultiFab with random numbers from normal distribution.
Definition AMReX_MultiFabUtil.cpp:1261
void FillRandom(MultiFab &mf, int scomp, int ncomp)
Fill MultiFab with random numbers from uniform distribution.
Definition AMReX_MultiFabUtil.cpp:1248
void DeallocateRandomSeedDevArray()
Definition AMReX_Random.cpp:252
Definition AMReX_RandomEngine.H:72
randState_t * rand_state
Definition AMReX_RandomEngine.H:73