Nemo  2.4.2
Simulate forward-in-time genetic evolution in a spatially explicit, individual-based stochastic simulator
RAND Class Reference

Random number generation class, uses various types of random generators depending on the implementation. More...

#include <Uniform.h>

+ Collaboration diagram for RAND:

Static Public Member Functions

static void init (unsigned long seed)
 Initialize the random generator's seed. More...
 
static void free ()
 Memory de-allocation. More...
 
static double Uniform ()
 Generates a random number from [0.0, 1.0[ uniformly distributed. More...
 
static unsigned int Uniform (unsigned int max)
 Returns a uniformly distributed random number from [0.0, max[. More...
 
static bool RandBool ()
 Returns a random boolean. More...
 
static unsigned long RandULong ()
 Return a random unsigned long, from uniform distribution. More...
 
static double gammln (double xx)
 From the Numerical Recieps. More...
 
static double Poisson (double mean)
 From the Numerical Recieps. More...
 
static double Gaussian (double sigma)
 
static void BivariateGaussian (double sigma1, double sigma2, double rho, double *out1, double *out2)
 
static double LogNormal (double zeta, double sigma)
 
static double Gamma (double a, double b)
 
static double Bernoulli (double p)
 
static double Exponential (double mu)
 
static double Binomial (double p, unsigned int n)
 
static double Beta (const double a, const double b)
 
static unsigned int Binomial2 (double p, unsigned int n)
 
static void Multinomial (size_t K, unsigned int N, const double p[], unsigned int n[])
 
static void MultinomialOnNormalizedValarray (size_t K, unsigned int N, const std::valarray< double > &p, unsigned int n[])
 Multinomial draw assuming the probabilities sum to 1.0 and are all > 0. More...
 
static void MultinomialOnNormalizedValarray_expandedOut (size_t K, unsigned int N, const std::valarray< double > &p, unsigned int n[])
 Multinomial draw assuming the probabilities sum to 1.0 and are all > 0, the output is an array of size N. More...
 
static void MultinomialOnNormalizedValarray_scrambleOut (size_t K, unsigned int N, const std::valarray< double > &p, unsigned int n[])
 Multinomial draw assuming the probabilities sum to 1.0 and are all > 0, the output is an array of size N. More...
 
static void MultinomialOnNormalizedValarrayZipper_scrambleOut (size_t K, unsigned int N, const std::valarray< double > &p, unsigned int n[])
 Multinomial draw assuming the probabilities sum to 1.0 and are all > 0, the output is an array of size N. More...
 
static void ScrambleArrayUInt (const int length, unsigned int *array)
 Randomize the elements within an array. More...
 
static void Sample (const int from, const int to, const unsigned int num, int *result, bool replace)
 Creates a sample of integers within range [from, to), with or without replacement. More...
 
static void SampleSeq (int from, int to, int by, unsigned int num, int *result, bool replace=false)
 
static void SampleSeqWithReciprocal (int from, int to, int by, unsigned int num1, int *result1, unsigned int num2, int *result2)
 
static size_t Discrete (const gsl_ran_discrete_t *g)
 Calling the GSL ran_discrete function. More...
 

Static Public Attributes

static long Seed1 = 0
 
static long Seed2 = 98280582
 

Private Member Functions

 RAND ()
 

Detailed Description

Random number generation class, uses various types of random generators depending on the implementation.

Constructor & Destructor Documentation

◆ RAND()

RAND::RAND ( )
private

Member Function Documentation

◆ Bernoulli()

static double RAND::Bernoulli ( double  p)
inlinestatic
440  {
441 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
442  return gsl_ran_bernoulli(r, p);
443 #else
444  double u = RAND::Uniform() ;
445 
446  if (u < p)
447  {
448  return 1 ;
449  }
450  else
451  {
452  return 0 ;
453  }
454 #endif
455  }
static double Uniform()
Generates a random number from [0.0, 1.0[ uniformly distributed.
Definition: Uniform.h:125

References Uniform().

Referenced by TTNeutralGenes_byte::init_sequence(), and ParamsParser::rbernoul().

+ Here is the caller graph for this function:

◆ Beta()

static double RAND::Beta ( const double  a,
const double  b 
)
inlinestatic
537  {
538  /*from Knuth*/
539  double x1 = RAND::Gamma(a, 1.0);
540  double x2 = RAND::Gamma(b, 1.0);
541 
542  return x1 / (x1 + x2);
543  }
static double Gamma(double a, double b)
Definition: Uniform.h:395

References Gamma().

Referenced by Binomial().

+ Here is the caller graph for this function:

◆ Binomial()

static double RAND::Binomial ( double  p,
unsigned int  n 
)
inlinestatic
500  {
501  /*implements Knuth method*/
502  unsigned int i, a, b, k = 0;
503 
504  while (n > 10) /* This parameter is tunable */
505  {
506  double X;
507  a = 1 + (n / 2);
508  b = 1 + n - a;
509 
510  X = RAND::Beta((double) a, (double) b);
511 
512  if (X >= p)
513  {
514  n = a - 1;
515  p /= X;
516  }
517  else
518  {
519  k += a;
520  n = b - 1;
521  p = (p - X) / (1 - X);
522  }
523  }
524 
525  for (i = 0; i < n; i++)
526  {
527  double u = RAND::Uniform();
528  if (u < p)
529  k++;
530  }
531 
532  return k;
533 
534  }
static double Beta(const double a, const double b)
Definition: Uniform.h:536

References Beta(), and Uniform().

Referenced by Binomial2(), TProtoNeutralGenes::get_num_mutations(), TProtoQuanti::get_num_mutations(), Multinomial(), MultinomialOnNormalizedValarray(), MultinomialOnNormalizedValarray_expandedOut(), and MultinomialOnNormalizedValarray_scrambleOut().

+ Here is the caller graph for this function:

◆ Binomial2()

static unsigned int RAND::Binomial2 ( double  p,
unsigned int  n 
)
inlinestatic
545  {
546 
547 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
548  return gsl_ran_binomial (r, p, n);
549 #else
550  return Binomial(p, n);
551 #endif
552  }
static double Binomial(double p, unsigned int n)
Definition: Uniform.h:499

References Binomial().

◆ BivariateGaussian()

static void RAND::BivariateGaussian ( double  sigma1,
double  sigma2,
double  rho,
double *  out1,
double *  out2 
)
inlinestatic
340  {
341 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
342  gsl_ran_bivariate_gaussian(r,sigma1,sigma2,rho,out1,out2);
343 #else
344  //gsl code:
345  double u, v, r2, scale;
346  //double *x = out, *y = (++out);
347  do
348  {
349  /* choose x,y in uniform square (-1,-1) to (+1,+1) */
350 
351  u = -1 + 2 * Uniform ();
352  v = -1 + 2 * Uniform ();
353 
354  /* see if it is in the unit circle */
355  r2 = u * u + v * v;
356  }
357  while (r2 > 1.0 || r2 == 0);
358 
359  scale = sqrt (-2.0 * log (r2) / r2);
360 
361  *out1 = sigma1 * u * scale;
362  *out2 = sigma2 * (rho * u + sqrt(1 - rho*rho) * v) * scale;
363 
364 #endif
365  }

References Uniform().

Referenced by TProtoQuanti::getMutationEffectBivariateGaussian(), and TProtoQuanti::getMutationEffectBivariateGaussianLocSpec().

+ Here is the caller graph for this function:

◆ Discrete()

static size_t RAND::Discrete ( const gsl_ran_discrete_t *  g)
inlinestatic

Calling the GSL ran_discrete function.

824  {
825 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
826  return gsl_ran_discrete(r, g);
827 #else
828  /* GSL code here, modified to call our Uniform() */
829  size_t c=0;
830  double u,f;
831  u = Uniform();
832 
833 #if KNUTH_CONVENTION
834  c = (u*(g->K));
835 #else
836  u *= g->K;
837  c = u;
838  u -= c;
839 #endif
840 
841  f = (g->F)[c];
842  /* fprintf(stderr,"c,f,u: %d %.4f %f\n",c,f,u); */
843  if (f == 1.0) return c;
844 
845  if (u < f) {
846  return c;
847  }
848  else {
849  return (g->A)[c];
850  }
851 
852 #endif
853  }

References Uniform().

Referenced by LCE_Breed_Selection::do_breed_selection_WrightFisher_1sex(), LCE_Breed_Selection::do_breed_selection_WrightFisher_2sex(), and LCE_Disperse_base::getMigrationIndexGSLdiscrete().

+ Here is the caller graph for this function:

◆ Exponential()

static double RAND::Exponential ( double  mu)
inlinestatic
457  {
458  return -mu * log(RAND::Uniform());
459  }

References Uniform().

Referenced by ParamsParser::rexp(), and TProtoDeletMutations_bitstring::set_effects_exp().

+ Here is the caller graph for this function:

◆ free()

static void RAND::free ( )
inlinestatic

Memory de-allocation.

110  {
111 
112 #if defined(HAS_SPRNG)
113  // do nothing with pointer?
114 #elif defined(HAS_GSL)
115  gsl_rng_free(r);
116 #endif
117 
118  }

Referenced by SimRunner::run().

+ Here is the caller graph for this function:

◆ Gamma()

static double RAND::Gamma ( double  a,
double  b 
)
inlinestatic
395  {
396 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
397  return gsl_ran_gamma(r, a, b);
398 #else
399  /*pasting GSL code in here*/
400 
401  /* assume a > 0 */
402 
403  if (a < 1)
404  {
405  double u = Uniform();//might give singularity at 0....
406  return Gamma(1.0 + a, b) * pow (u, 1.0 / a);
407  }
408 
409  {
410  double x, v, u;
411  double d = a - 1.0 / 3.0;
412  double c = (1.0 / 3.0) / sqrt (d);
413 
414  while (1)
415  {
416  do
417  {
418  x = Gaussian(1.0); //should use the Ziggurat method?
419  v = 1.0 + c * x;
420  }
421  while (v <= 0);
422 
423  v = v * v * v;
424  u = Uniform();//might give singularity at 0....
425 
426  if (u < 1 - 0.0331 * x * x * x * x)
427  break;
428 
429  if (log (u) < 0.5 * x * x + d * (1 - v + log (v)))
430  break;
431  }
432 
433  return b * d * v;
434  }
435 
436 #endif
437  }
static double Gaussian(double sigma)
Definition: Uniform.h:271

References Gaussian(), and Uniform().

Referenced by Beta(), ParamsParser::rgamma(), and TProtoDeletMutations_bitstring::set_effects_gamma().

+ Here is the caller graph for this function:

◆ gammln()

static double RAND::gammln ( double  xx)
inlinestatic

From the Numerical Recieps.

214  {
215  double x,y,tmp,ser=1.000000000190015;
216  static double cof[6]={76.18009172947146,-86.50532032941677,
217  24.01409824083091,-1.231739572450155,
218  0.1208650973866179e-2,-0.5395239384953e-5};
219  int j;
220  y=x=xx;
221  tmp=x+5.5;
222  tmp -= (x+0.5)*log(tmp);
223  for (j = 0; j < 6; ++j) ser += cof[j]/++y;
224 
225  return -tmp+log(2.5066282746310005*ser/x);
226 
227  }

Referenced by Poisson().

+ Here is the caller graph for this function:

◆ Gaussian()

static double RAND::Gaussian ( double  sigma)
inlinestatic

From the GSL.

272  {
273 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
274 
275  return gsl_ran_gaussian_ziggurat (r, sigma);
276 
277 #else
279 // double x, y, r2;
280 //
281 // do
282 // {
283 // /* choose x,y in uniform square (-1,-1) to (+1,+1) */
284 //
285 // x = -1 + 2 * Uniform ( );
286 // y = -1 + 2 * Uniform ( );
287 //
288 // /* see if it is in the unit circle */
289 // r2 = x * x + y * y;
290 // }
291 // while (r2 > 1.0 || r2 == 0);
292 //
293 // /* Box-Muller transform */
294 // return sigma * y * sqrt (-2.0 * log (r2) / r2);
295 
296  /*trying the ratio method from GSL*/
297  /* see code in gsl/randist/gauss.c */
298  double u, v, x, y, Q;
299  const double s = 0.449871; /* Constants from Leva */
300  const double t = -0.386595;
301  const double a = 0.19600;
302  const double b = 0.25472;
303  const double r1 = 0.27597;
304  const double r2 = 0.27846;
305 
306  do /* This loop is executed 1.369 times on average */
307  {
308  /* Generate a point P = (u, v) uniform in a rectangle enclosing
309  the K+M region v^2 <= - 4 u^2 log(u). */
310 
311  /* u in (0, 1] to avoid singularity at u = 0 */
312  u = 1 - RAND::Uniform();
313 
314  /* v is in the asymmetric interval [-0.5, 0.5). However v = -0.5
315  is rejected in the last part of the while clause. The
316  resulting normal deviate is strictly symmetric about 0
317  (provided that v is symmetric once v = -0.5 is excluded). */
318  v = RAND::Uniform() - 0.5;
319 
320  /* Constant 1.7156 > sqrt(8/e) (for accuracy); but not by too
321  much (for efficiency). */
322  v *= 1.7156;
323 
324  /* Compute Leva's quadratic form Q */
325  x = u - s;
326  y = fabs (v) - t;
327  Q = x * x + y * (a * y - b * x);
328 
329  /* Accept P if Q < r1 (Leva) */
330  /* Reject P if Q > r2 (Leva) */
331  /* Accept if v^2 <= -4 u^2 log(u) (K+M) */
332  /* This final test is executed 0.012 times on average. */
333  }
334  while (Q >= r1 && (Q > r2 || v * v > -4 * u * u * log (u)));
335 
336  return sigma * (v / u);
337 #endif
338  }

References Uniform().

Referenced by Gamma(), LCE_PhenotypeExpression::get_env_cue_noise(), LCE_Selection_base::getFitnessMultivariateGaussian_VE(), LCE_Selection_base::getFitnessUnivariateGaussian_VE(), LCE_Breed_base::getGaussianFecundity(), TProtoQuanti::getMutationEffectUnivariateGaussian(), TProtoQuanti::getMutationEffectUnivariateGaussianLocSpec(), TTDispersal::init_sequence(), TTQuanti_continuous_full_pleio::init_sequence(), TTQuanti_continuous_var_pleio::init_sequence(), TTQuanti_continuous_no_pleio::init_sequence(), TTQuanti_continuous_full_pleio_epistasis::init_sequence(), TTQuanti_continuous_no_pleio_epistasis::init_sequence(), LCE_Patch_Extinction::rand_gaussian(), ParamsParser::rnorm(), and TProtoQuanti::set_trait_value_VE().

+ Here is the caller graph for this function:

◆ init()

static void RAND::init ( unsigned long  seed)
inlinestatic

Initialize the random generator's seed.

80  {
81 
82 #if defined(HAS_SPRNG)
83  // initializing the SPRNG stream with default param and LFG (0) generator
84 
85  stream = SelectType(4); //MLFG Modified Lagged Fibonacci
86 
87  stream->init_sprng( _myenv->workerRank(), _myenv->workerCount()+1, seed, SPRNG_DEFAULT );
88 
89 
90 #ifdef DEBUG_MPI
91  message("--- initialized the SPRNG random generator on rank %i\n", _myenv->workerRank());
92 
93  stream->print_sprng();
94 
95  message("--- process %i random number: %.14f\n", _myenv->workerRank(), stream->sprng());
96 #endif
97 
98 #elif defined(HAS_GSL)
99 
100  init_gsl( gsl_rng_mt19937, seed );
101 
102 #else
103 
104  Seed1 = seed;
105 
106 #endif
107  }
MPIenv * _myenv
Definition: MPImanager.cc:34
int workerCount() const
Definition: MPImanager.h:127
int workerRank() const
Definition: MPImanager.h:128
static long Seed1
Definition: Uniform.h:76
void message(const char *message,...)
Definition: output.cc:38

References _myenv, message(), Seed1, MPIenv::workerCount(), and MPIenv::workerRank().

Referenced by SimRunner::init_random_seed(), and SimRunner::run().

+ Here is the caller graph for this function:

◆ LogNormal()

static double RAND::LogNormal ( double  zeta,
double  sigma 
)
inlinestatic
367  {
368 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
369  return gsl_ran_lognormal(r,zeta,sigma);
370 #else
371  //this is the GSL code:
372  double u, v, r2, normal, z;
373 
374  do
375  {
376  /* choose x,y in uniform square (-1,-1) to (+1,+1) */
377 
378  u = -1 + 2 * Uniform();
379  v = -1 + 2 * Uniform();
380 
381  /* see if it is in the unit circle */
382  r2 = u * u + v * v;
383  }
384  while (r2 > 1.0 || r2 == 0);
385 
386  normal = u * sqrt (-2.0 * log (r2) / r2);
387 
388  z = exp (sigma * normal + zeta);
389 
390  return z;
391 
392 #endif
393  }

References Uniform().

Referenced by LCE_Breed_base::getLogNormalFecundity(), LCE_Patch_Extinction::rand_lognormal(), ParamsParser::rlognorm(), and TProtoDeletMutations_bitstring::set_effects_lognorm().

+ Here is the caller graph for this function:

◆ Multinomial()

static void RAND::Multinomial ( size_t  K,
unsigned int  N,
const double  p[],
unsigned int  n[] 
)
inlinestatic
555  {
556 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
557  return gsl_ran_multinomial (r, K, N, p, n);
558 #else
559  // GSL code here:
560  size_t k;
561  double norm = 0.0;
562  double sum_p = 0.0;
563 
564  unsigned int sum_n = 0;
565 
566  /* p[k] may contain non-negative weights that do not sum to 1.0.
567  * Even a probability distribution will not exactly sum to 1.0
568  * due to rounding errors.
569  */
570 
571  for (k = 0; k < K; k++)
572  {
573  norm += p[k];
574  }
575 
576  for (k = 0; k < K; k++)
577  {
578  if (p[k] > 0.0)
579  {
580  n[k] = Binomial (p[k] / (norm - sum_p), N - sum_n); //MOD
581  }
582  else
583  {
584  n[k] = 0;
585  }
586 
587  sum_p += p[k];
588  sum_n += n[k];
589  }
590 
591 #endif
592  }

References Binomial().

◆ MultinomialOnNormalizedValarray()

static void RAND::MultinomialOnNormalizedValarray ( size_t  K,
unsigned int  N,
const std::valarray< double > &  p,
unsigned int  n[] 
)
inlinestatic

Multinomial draw assuming the probabilities sum to 1.0 and are all > 0.

596  {
597  // GSL code here: FG 2020: modified for normalized arrays
598  size_t k;
599  double sum_p = 0.0;
600 
601  unsigned int sum_n = 0;
602 
603  for (k = 0; k < K; k++)
604  {
605  n[k] = RAND::Binomial (p[k] / (1.0 - sum_p), N - sum_n); //MOD FG
606  sum_p += p[k];
607  sum_n += n[k];
608  }
609  }

References Binomial().

◆ MultinomialOnNormalizedValarray_expandedOut()

static void RAND::MultinomialOnNormalizedValarray_expandedOut ( size_t  K,
unsigned int  N,
const std::valarray< double > &  p,
unsigned int  n[] 
)
inlinestatic

Multinomial draw assuming the probabilities sum to 1.0 and are all > 0, the output is an array of size N.

615  {
616  // GSL code here: FG 2020: modified for normalized arrays
617  size_t k;
618  double sum_p = 0.0;
619  unsigned int _n, sum_n = 0;
620  unsigned int i = 0, pos = 0;
621 
622  for (k = 0; k < K; k++) {
623  //draw number of events k with probability p[k]
624  _n = RAND::Binomial (p[k] / (1.0 - sum_p), N - sum_n);
625 
626  for(i = 0; i < _n; i++)
627  n[pos++] = k;
628 
629  sum_p += p[k];
630  sum_n += _n;
631  assert(pos <= N);
632  }
633  assert(sum_n == N);
634  }

References Binomial().

◆ MultinomialOnNormalizedValarray_scrambleOut()

static void RAND::MultinomialOnNormalizedValarray_scrambleOut ( size_t  K,
unsigned int  N,
const std::valarray< double > &  p,
unsigned int  n[] 
)
inlinestatic

Multinomial draw assuming the probabilities sum to 1.0 and are all > 0, the output is an array of size N.

640  {
641  // GSL code here: FG 2020: modified for normalized arrays
642  size_t k;
643  double sum_p = 0.0;
644  unsigned int _n, sum_n = 0;
645  unsigned int i = 0, pos = 0;
646 
647  for (k = 0; k < K; k++) {
648  //draw number of events k with probability p[k]
649  _n = RAND::Binomial (p[k] / (1.0 - sum_p), N - sum_n);
650 
651  for(i = 0; i < _n; i++)
652  n[pos++] = k;
653 
654  sum_p += p[k];
655  sum_n += _n;
656  assert(pos <= N);
657  }
658  assert(sum_n == N);
659 
660  //scramble the output array
662 
663  }
static void ScrambleArrayUInt(const int length, unsigned int *array)
Randomize the elements within an array.
Definition: Uniform.h:699

References Binomial(), and ScrambleArrayUInt().

◆ MultinomialOnNormalizedValarrayZipper_scrambleOut()

static void RAND::MultinomialOnNormalizedValarrayZipper_scrambleOut ( size_t  K,
unsigned int  N,
const std::valarray< double > &  p,
unsigned int  n[] 
)
inlinestatic

Multinomial draw assuming the probabilities sum to 1.0 and are all > 0, the output is an array of size N.

669  {
670  size_t k;
671  double sum = 0.0;
672  double rand;
673  unsigned int i = 0;
674 
675  for (k = 0; k < N; k++) {
676 
677  rand = std::min(0.99999995, RAND::Uniform()); // to avoid problems with rounding errors
678  i = 0;
679  sum = p[i];
680 
681  //zip through the proba array:
682  while( sum < rand ) {
683  i++;
684  sum += p[i];
685  }
686 
687  n[k] = i;
688 
689  }
690  //scramble the output array
692 
693  }

References ScrambleArrayUInt(), and Uniform().

◆ Poisson()

static double RAND::Poisson ( double  mean)
inlinestatic

From the Numerical Recieps.

229  {
230 
231 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
232  return gsl_ran_poisson(r, mean);
233 #else
234  static double sq,alxm,g,oldm=(-1.0);
235  double em,t,y;
236 
237  if (mean < 12.0)
238  {
239  if (mean != oldm){
240  oldm=mean;
241  g=exp(-mean);
242  }
243  em = -1;
244  t=1.0;
245  do {
246  ++em;
247  t *= Uniform();
248  } while (t > g);
249  }else
250  {
251  if (mean != oldm)
252  {
253  oldm=mean;
254  sq=sqrt(2.0*mean);
255  alxm=log(mean);
256  g=mean*alxm-gammln(mean+1.0);
257  }
258  do {
259  do {
260  y=tan(M_PI*Uniform());
261  em=sq*y+mean;
262  } while (em < 0.0);
263  em=floor(em);
264  t=0.9*(1.0+y*y)*exp(em*alxm-gammln(em+1.0)-g);
265  } while (Uniform() > t);
266  }
267  return em;
268 #endif
269  }
static double gammln(double xx)
From the Numerical Recieps.
Definition: Uniform.h:214

References gammln(), and Uniform().

Referenced by LCE_Breed_base::getPoissonFecundity(), TTDispersal::mutate(), TT_BDMI::mutate_diplo(), TT_BDMI::mutate_haplo(), TTDeletMutations_bitstring::mutate_noredraw(), TTDeletMutations_bitstring::mutate_noredraw_noBackMutation(), TTDeletMutations_bitstring::mutate_redraw(), LCE_Patch_Extinction::rand_poisson(), GeneticMap::recombine(), ParamsParser::rpoiss(), and LCE_Breed_Disperse::stochasticLogisticGrowth().

+ Here is the caller graph for this function:

◆ RandBool()

static bool RAND::RandBool ( )
inlinestatic

Returns a random boolean.

One bit is consumed per call from a cached random word, which is redrawn once its bits are exhausted. The shift must be done on an unsigned long: with the former 1 << num the shift count wrapped at 32, so bits 32-63 returned the same values as bits 0-31 of the same draw and the sequence repeated every 32 calls. This must stay consistent with RandULong() below: while RandULong() filled only the lower 32 bits, that same wrap was what kept these reads on the random half of the word, so fixing either one alone biases the result (see the CHANGELOG for 2.4.2).

170  {
171  //number of usable random bits per draw, and the cached draw itself
172 #ifdef HAS_SPRNG
173  static const unsigned int NBITS = 31; //isprng() returns a non-negative int
174  static unsigned long intrand = (unsigned long)stream->isprng();
175 #else
176  static const unsigned int NBITS = (unsigned int)(CHAR_BIT * sizeof(unsigned long));
177  static unsigned long intrand = RandULong();
178 #endif
179  static unsigned int num = 0;
180 
181  //redraw once all bits of the cached word have been consumed
182  if ( num == NBITS ) {
183  num = 0;
184 
185 #ifdef HAS_SPRNG
186  intrand = (unsigned long)stream->isprng();
187 #else
188  intrand = RandULong();
189 #endif
190 
191  }
192  return ( intrand >> num++ ) & 1UL;
193 
194  }
static unsigned long RandULong()
Return a random unsigned long, from uniform distribution.
Definition: Uniform.h:200

References RandULong().

Referenced by LCE_Patch_Extinction::do_remove(), TProtoQuanti::getMutationEffectBivariateDiallelic(), LCE_Breed_base::getOffsprgSexFixed(), LCE_Breed_base::getOffsprgSexRandom(), TTDispersal::inherit(), TTNeutralGenes_bitstring::inherit(), TProtoBDMI::inherit_free(), TProtoDeletMutations_bitstring::inherit_free(), TProtoQuanti::inherit_free(), TProtoNeutralGenes::inherit_free(), TTNeutralGenes_bitstring::init_sequence(), TTQuanti_continuous_full_pleio::init_sequence(), TTQuanti_continuous_var_pleio::init_sequence(), TTQuanti_continuous_no_pleio::init_sequence(), TTQuanti_diallelic_no_pleio::init_sequence(), TTQuanti_diallelic_full_pleio::init_sequence(), TTQuanti_diallelic_var_pleio::init_sequence(), TTQuanti_diallelic_bitstring_no_pleio::init_sequence(), TTQuanti_diallelic_bitstring_full_pleio::init_sequence(), TTQuanti_diallelic_bitstring_var_pleio::init_sequence(), TTQuanti_continuous_full_pleio_epistasis::init_sequence(), TTQuanti_diallelic_full_pleio_epistasis::init_sequence(), TTQuanti_continuous_no_pleio_epistasis::init_sequence(), TTQuanti_diallelic_no_pleio_epistasis::init_sequence(), TTQuanti_diallelic_bitstring_no_pleio_epistasis::init_sequence(), TTQuanti_diallelic_bitstring_full_pleio_epistasis::init_sequence(), LCE_Disperse_EvolDisp::Migrate_SteppingStone1D(), TTDispersal::mutate(), TTNeutralGenes_bitstring::mutate(), TTNeutralGenes_byte::mutate_2all(), TProtoQuanti::mutate_diallelic_no_pleio(), TProtoQuanti::mutate_diallelic_pleio(), TProtoQuanti::mutate_diallelic_var_pleio(), TT_BDMI::mutate_diplo(), TProtoQuanti::mutate_full_pleio(), TProtoQuanti::mutate_inplace_full_pleio(), TProtoQuanti::mutate_inplace_no_pleio(), TProtoQuanti::mutate_inplace_var_pleio(), TTNeutralGenes_byte::mutate_KAM(), TProtoQuanti::mutate_no_pleio(), TTDeletMutations_bitstring::mutate_noredraw(), TTDeletMutations_bitstring::mutate_noredraw_noBackMutation(), TTDeletMutations_bitstring::mutate_redraw(), TTNeutralGenes_byte::mutate_SSM(), TProtoQuanti::mutate_var_pleio(), GeneticMap::recombine(), LCE_Breed_Wolbachia::wolbachia_model_1(), and LCE_Breed_Wolbachia::wolbachia_model_2().

◆ RandULong()

static unsigned long RAND::RandULong ( )
inlinestatic

Return a random unsigned long, from uniform distribution.

The GSL integer generators (mt19937 used here) return only 32 random bits, so we compose two draws to fill all 64 bits. Without this the upper 32 bits are always 0, which biases the word-level mask recombination.

200  {
201 #if defined(HAS_GSL) && !defined(HAS_SPRNG)
202  return ((unsigned long)(gsl_rng_get(r) & 0xFFFFFFFFUL) << 32)
203  | (unsigned long)(gsl_rng_get(r) & 0xFFFFFFFFUL);
204 #else
205  unsigned long rnd, limit = 0x10000000; //=2^28 this gives ~7% redraws
206  do{
207  rnd = (unsigned long)(Uniform()*ULONG_MAX);
208  }while(rnd < limit);
209 
210  return rnd;
211 #endif
212  }

References Uniform().

Referenced by TTNeutralGenes_bitstring::inherit(), TProtoDeletMutations_bitstring::inherit_free(), and RandBool().

+ Here is the caller graph for this function:

◆ Sample()

static void RAND::Sample ( const int  from,
const int  to,
const unsigned int  num,
int *  result,
bool  replace 
)
inlinestatic

Creates a sample of integers within range [from, to), with or without replacement.

Can be used to scramble an array (without replacement). The random sequence of integers is placed in the 'results' array.

Parameters
fromstarting number of the series
tolast number of the series
numnumber of elements to draw within [from, to)
resultcontainer to hold the resulting randomized sequence of integers
724  {
725  assert(from < to);
726 
727  unsigned int seq_length = to - from; //don't include last (to)
728 
729  assert(num <= seq_length);
730 
731  // we build a sequence of indexes to choose from
732  int *seq = new int [seq_length];
733 
734  seq[0] = from;
735 
736  for(unsigned int i = 1; seq[i-1] < to && i < seq_length; ++i)
737  seq[i] = seq[i-1] + 1;
738 
739  if(!replace) { //without replacement
740 
741  unsigned int size = seq_length, pos, last = seq_length - 1;
742 
743  for (unsigned int i = 0; i < num; i++) {
744  pos = RAND::Uniform(size);
745  result[i] = seq[pos];
746  seq[pos] = seq[last];
747  // seq[last] = result[i]; useless operation
748  size--; last--;
749  }
750 
751  } else { //with replacement
752  for (unsigned int i = 0; i < num; i++)
753  result[i] = seq[ RAND::Uniform(seq_length) ];
754  }
755 
756  delete [] seq;
757  }

References Uniform().

Referenced by MPFileHandler::createAndPrintSample(), ParamsParser::sample(), and FileServices::subSamplePatch().

+ Here is the caller graph for this function:

◆ SampleSeq()

static void RAND::SampleSeq ( int  from,
int  to,
int  by,
unsigned int  num,
int *  result,
bool  replace = false 
)
inlinestatic
760  {
761  assert(from < to && by < to && by > 0);
762 
763  unsigned int seq_length = (int)((to - from) / by); //don't include last (to)
764 
765  assert(num <= seq_length);
766 
767  int *seq = new int [seq_length];
768 
769  seq[0] = from;
770 
771  for(unsigned int i = 1; seq[i-1] + by < to && i < seq_length; ++i) seq[i] = seq[i-1] + by;
772 
773  if(!replace) { //without replacement
774 
775  unsigned int size = seq_length, pos, last = seq_length - 1;
776 
777  for (unsigned int i = 0; i < num; i++) {
778  pos = RAND::Uniform(size);
779  result[i] = seq[pos];
780  seq[pos] = seq[last];
781  // seq[last] = result[i]; useless operation
782  size--; last--;
783  }
784 
785  } else { //with replacement
786  for (unsigned int i = 0; i < num; i++) result[i] = seq[ RAND::Uniform(seq_length) ];
787  }
788 
789  delete [] seq;
790  }

References Uniform().

◆ SampleSeqWithReciprocal()

static void RAND::SampleSeqWithReciprocal ( int  from,
int  to,
int  by,
unsigned int  num1,
int *  result1,
unsigned int  num2,
int *  result2 
)
inlinestatic
793  {
794  assert(from < to && by < to && by > 0);
795 
796  unsigned int seq_length = (int)((to - from) / by); //don't include last (to)
797 
798  assert(num1 + num2 == seq_length);
799 
800  int *seq = new int [seq_length];
801 
802  seq[0] = from;
803 
804  for(unsigned int i = 1; seq[i-1] + by < to && i < seq_length; ++i) seq[i] = seq[i-1] + by;
805 
806  unsigned int size = seq_length, pos, last = seq_length - 1;
807 
808  for (unsigned int i = 0; i < num1; i++) {
809  pos = RAND::Uniform(size);
810  result1[i] = seq[pos];
811  seq[pos] = seq[last];
812  seq[last] = result1[i];
813  size--; last--;
814  }
815 
816  for (unsigned int i = 0; i < num2 && i < size; i++)
817  result2[i] = seq[i];
818 
819  delete [] seq;
820  }

References Uniform().

Referenced by LCE_NtrlInit::init_allele_freq(), and LCE_QuantiInit::init_allele_freq().

+ Here is the caller graph for this function:

◆ ScrambleArrayUInt()

static void RAND::ScrambleArrayUInt ( const int  length,
unsigned int *  array 
)
inlinestatic

Randomize the elements within an array.

Parameters
lengththe length of the array
arraythe array to scramble
700  {
701  unsigned int size = length, pos, last = length - 1, num = length -1, el;
702 
703  // with stop after 2 elements are left
704  // this algo allows swapping an element with itself, which is fine
705  for (unsigned int i = 0; i < num; i++) {
706  pos = RAND::Uniform(size);
707  el = array[last];
708  array[last] = array[pos];
709  array[pos] = el;
710  size--; last--;
711  }
712 
713  assert(size == 1); //we stopped before swapping the last (first) element with itself
714  }

References Uniform().

Referenced by MultinomialOnNormalizedValarray_scrambleOut(), and MultinomialOnNormalizedValarrayZipper_scrambleOut().

+ Here is the caller graph for this function:

◆ Uniform() [1/2]

static double RAND::Uniform ( )
inlinestatic

Generates a random number from [0.0, 1.0[ uniformly distributed.

If SPRNG or GSL libraries are not used, implement a random generator from: L'Ecuyer, 1988, "Efficient and Portable Combined Random Number Generators", Communication of the ACM, 31(6):742-774.

125  {
126 
127 #ifdef HAS_SPRNG
128  return stream->sprng();
129 #elif defined(HAS_GSL)
130  return gsl_rng_uniform(r);
131 #else
132  register long z, w;
133 
134  do{
135  w = Seed1 / 53668;
136 
137  Seed1 = 40014 * (Seed1 - w * 53668) - w * 12211;
138 
139  if (Seed1 < 0) Seed1 += 2147483563;
140 
141  w = (Seed2 / 52774);
142 
143  Seed2 = 40692 * (Seed2 - w * 52774) - w * 3791;
144 
145  if (Seed2 < 0) Seed2 += 2147483399;
146 
147  z = Seed1 - Seed2;
148 
149  if (z < 1) z += 2147483562;
150 
151  }while (!((z * 4.656613e-10) < 1.0));
152 
153  return (z * 4.656613e-10);
154 #endif
155  }
static long Seed2
Definition: Uniform.h:76

References Seed1, and Seed2.

Referenced by Bernoulli(), Binomial(), BivariateGaussian(), LCE_Breed_base::checkPolygyny(), LCE_Cross::create_individual_ancestors(), Discrete(), LCE_Patch_Extinction::do_remove(), LCE_Selection_base::doViabilitySelection(), LCE_Disperse_EvolDisp::evoldisp(), LCE_BreedAssortativeMating::execute(), LCE_Aging::execute(), LCE_Patch_Extinction::execute(), Exponential(), BinaryDataLoader::extractPop(), Metapop::fillPopulationFromSource(), LCE_Disperse_EvolDisp::fixdisp(), LCE_Breed_base::fullPolyginy_manyMales(), Gamma(), Gaussian(), LCE_Breed_Disperse::get_parent(), LCE_Disperse_base::getMigrationIndex(), LCE_Disperse_base::getMigrationPatchBackward(), LCE_Disperse_base::getMigrationPatchForward(), TProtoQuanti::getMutationEffectBivariateDiallelic(), LCE_QuantiInit::init_allele_freq(), TT_BDMI::init_sequence(), TTDeletMutations_bitstring::init_sequence(), TTDispersal::init_sequence(), TTNeutralGenes_byte::init_sequence(), LogNormal(), LCE_Breed_Selection::makeOffspringWithSelection(), LCE_Breed_Disperse::mate_selfing(), LCE_Disperse_EvolDisp::Migrate_Island(), LCE_Disperse_EvolDisp::Migrate_Island_Propagule(), LCE_Disperse_EvolDisp::Migrate_Lattice(), LCE_Disperse_ConstDisp::MigratePatchByNumber(), MultinomialOnNormalizedValarrayZipper_scrambleOut(), TTDispersal::mutate(), TTNeutralGenes_bitstring::mutate(), TTWolbachia::mutate(), TTNeutralGenes_byte::mutate_2all(), TProtoQuanti::mutate_diallelic_no_pleio(), TProtoQuanti::mutate_diallelic_pleio(), TProtoQuanti::mutate_diallelic_var_pleio(), TT_BDMI::mutate_diplo(), TProtoQuanti::mutate_full_pleio(), TT_BDMI::mutate_haplo(), TProtoQuanti::mutate_inplace_full_pleio(), TProtoQuanti::mutate_inplace_no_pleio(), TProtoQuanti::mutate_inplace_var_pleio(), TTNeutralGenes_byte::mutate_KAM(), TProtoQuanti::mutate_no_pleio(), TTDeletMutations_bitstring::mutate_noredraw(), TTDeletMutations_bitstring::mutate_noredraw_noBackMutation(), TTDeletMutations_bitstring::mutate_redraw(), TTNeutralGenes_byte::mutate_SSM(), TProtoQuanti::mutate_var_pleio(), LCE_Breed_base::partialMonoginy(), LCE_Breed_base::partialPolyginy(), LCE_Breed_base::partialPolyginy_manyMales(), LCE_Breed_base::partialSelfing(), Poisson(), LCE_Patch_Extinction::rand_exp(), LCE_Patch_Extinction::rand_uniform(), LCE_Breed_base::random_hermaphrodite(), LCE_Breed_base::RandomMating(), RandULong(), GeneticMap::recombine(), LCE_Resize::regulateAgeClassNoBackup(), LCE_Resize::regulateAgeClassWithBackup(), LCE_Regulation::regulatePatch(), ParamsParser::runif(), Sample(), ParamsParser::sample(), LCE_Cross::sampleAmongPop(), SampleSeq(), SampleSeqWithReciprocal(), LCE_Cross::sampleWithinPop(), ScrambleArrayUInt(), LCE_BreedAssortativeMating::ScrambleContainer(), LCE_Disperse_base::setPropaguleTargets(), TTProtoWithMap::setRecombinationMapRandom(), setSpatialMatrix(), LCE_Breed_Disperse::stochasticFecundityGrowth(), Uniform(), LCE_Breed_Wolbachia::wolbachia_model_1(), LCE_Breed_base::WrightFisherPopulation(), and LCE_Breed_Quanti::WrightFisherPopulation().

◆ Uniform() [2/2]

static unsigned int RAND::Uniform ( unsigned int  max)
inlinestatic

Returns a uniformly distributed random number from [0.0, max[.

158  {
159  return (unsigned int)(Uniform() * max);
160  }

References Uniform().

Member Data Documentation

◆ Seed1

long RAND::Seed1 = 0
static

Referenced by init(), and Uniform().

◆ Seed2

long RAND::Seed2 = 98280582
static

Referenced by Uniform().


The documentation for this class was generated from the following files:

Generated for Nemo v2.4.2 by  doxygen 1.9.1

Catalogued on GSR