bpp-core  2.2.0
RandomTools.h
Go to the documentation of this file.
1 //
2 // File RandomTools.h
3 // Author : Julien Dutheil
4 // Sylvain Gaillard
5 // Last modification : Thu November 6 2008
6 //
7 
8 /*
9  Copyright or © or Copr. Bio++ Development Team, (November 17, 2004)
10 
11  This software is a computer program whose purpose is to provide classes
12  for numerical calculus.
13 
14  This software is governed by the CeCILL license under French law and
15  abiding by the rules of distribution of free software. You can use,
16  modify and/ or redistribute the software under the terms of the CeCILL
17  license as circulated by CEA, CNRS and INRIA at the following URL
18  "http://www.cecill.info".
19 
20  As a counterpart to the access to the source code and rights to copy,
21  modify and redistribute granted by the license, users are provided only
22  with a limited warranty and the software's author, the holder of the
23  economic rights, and the successive licensors have only limited
24  liability.
25 
26  In this respect, the user's attention is drawn to the risks associated
27  with loading, using, modifying and/or developing or reproducing the
28  software by the user in light of its specific status of free software,
29  that may mean that it is complicated to manipulate, and that also
30  therefore means that it is reserved for developers and experienced
31  professionals having in-depth computer knowledge. Users are therefore
32  encouraged to load and test the software's suitability as regards their
33  requirements in conditions enabling the security of their systems and/or
34  data to be ensured and, more generally, to use and operate it in the
35  same conditions as regards security.
36 
37  The fact that you are presently reading this means that you have had
38  knowledge of the CeCILL license and that you accept its terms.
39 */
40 
41 #ifndef _RANDOMTOOLS_H_
42 #define _RANDOMTOOLS_H_
43 
44 #include "RandomFactory.h"
45 #include "../VectorExceptions.h"
46 #include "../VectorTools.h"
47 #include "../../Exceptions.h"
48 
49 // From the STL:
50 #include <cmath>
51 #include <cassert>
52 #include <ctime>
53 #include <vector>
54 
55 namespace bpp
56 {
57 
70  {
71  public:
73  virtual ~RandomTools() {}
74 
75  private:
79  static double incompletebetafe(double a,
80  double b,
81  double x,
82  double big,
83  double biginv);
84  static double incompletebetafe2(double a,
85  double b,
86  double x,
87  double big,
88  double biginv);
89  static double incompletebetaps(double a,
90  double b,
91  double x,
92  double maxgam);
93 
94  public:
96 
104  static double giveRandomNumberBetweenZeroAndEntry(double entry, const RandomFactory& generator = *DEFAULT_GENERATOR);
105 
111  static bool flipCoin(const RandomFactory& generator = *DEFAULT_GENERATOR);
112 
120  template<class intType>
121  static intType giveIntRandomNumberBetweenZeroAndEntry(intType entry, const RandomFactory& generator = *DEFAULT_GENERATOR) {
122  return static_cast<intType>(giveRandomNumberBetweenZeroAndEntry(static_cast<double>(entry), generator));
123  }
124 
130  static void setSeed(long seed);
131 
138  static double randGaussian(double mean, double variance, const RandomFactory& generator = *DEFAULT_GENERATOR);
139 
145  static double randGamma(double dblAlpha, const RandomFactory& generator = *DEFAULT_GENERATOR);
146 
153  static double randGamma(double alpha, double beta, const RandomFactory& generator = *DEFAULT_GENERATOR);
154 
161  static double randBeta(double alpha, double beta, const RandomFactory& generator = *DEFAULT_GENERATOR);
162 
168  static double randExponential(double mean, const RandomFactory& generator = *DEFAULT_GENERATOR);
169 
182  template<class T>
183  static T pickOne(std::vector<T>& v, bool replace = false) throw (EmptyVectorException<T>) {
184  if (v.empty())
185  throw EmptyVectorException<T>("RandomTools::pickOne: input vector is empty", &v);
186  size_t pos = RandomTools::giveIntRandomNumberBetweenZeroAndEntry<size_t>(v.size());
187  if (replace)
188  return v[pos];
189  else {
190  T e = v[pos];
191  v[pos] = v.back();
192  v.pop_back();
193  return e;
194  }
195  }
196 
197  template<class T>
198  static T pickOne(const std::vector<T>& v) throw (EmptyVectorException<T>) {
199  if (v.empty())
200  throw EmptyVectorException<T>("RandomTools::pickOne: input vector is empty", &v);
201  size_t pos = RandomTools::giveIntRandomNumberBetweenZeroAndEntry<size_t>(v.size());
202  return v[pos];
203  }
204 
222  template<class T>
223  static void getSample(const std::vector<T>& vin, std::vector<T>& vout, bool replace = false) throw (EmptyVectorException<T>, IndexOutOfBoundsException)
224  {
225  if (vout.size() > vin.size() && !replace)
226  throw IndexOutOfBoundsException("RandomTools::getSample: size exceeded v.size.", vout.size(), 0, vin.size());
227  std::vector<size_t> hat(vin.size());
228  for (size_t i = 0 ; i < vin.size() ; i++)
229  hat[i] = i;
230  for (size_t i = 0 ; i < vout.size() ; i++)
231  vout[i] = vin[pickOne(hat, replace)];
232  }
233 
249  template<class T>
250  static T pickOne(std::vector<T>& v, std::vector<double>& w, bool replace = false) throw (EmptyVectorException<T>) {
251  if (v.empty())
252  throw EmptyVectorException<T>("RandomTools::pickOne (with weight): input vector is empty", &v);
253  //Compute cumulative sum of weights:
254  std::vector<double> sumw = VectorTools::cumSum(w);
255  //Convert to cumulative distribution:
256  sumw /= sumw.back();
257  //Get random positions:
259  size_t pos = v.size() - 1;
260  for (size_t i = 0; i < v.size(); ++i) {
261  if (prob < sumw[i]) {
262  pos = i;
263  break;
264  }
265  }
266  if (replace)
267  return v[pos];
268  else {
269  T e = v[pos];
270  v[pos] = v.back();
271  v.pop_back();
272  w[pos] = w.back();
273  w.pop_back();
274  return e;
275  }
276  }
277 
302  template<class T>
303  static void getSample(const std::vector<T>& vin, const std::vector<double>& w, std::vector<T>& vout, bool replace = false) throw (EmptyVectorException<T>, IndexOutOfBoundsException)
304  {
305  if (vout.size() > vin.size() && !replace)
306  throw IndexOutOfBoundsException("RandomTools::getSample (with weights): size exceeded v.size.", vout.size(), 0, vin.size());
307  std::vector<size_t> hat(vin.size());
308  for (size_t i = 0 ; i < vin.size() ; i++)
309  hat[i] = i;
310  std::vector<double> w2(w); //non const copy
311  for (size_t i = 0 ; i < vout.size() ; i++)
312  vout[i] = vin[pickOne(hat, w2, replace)];
313  }
314 
325  static std::vector<size_t> randMultinomial(size_t n, const std::vector<double>& probs);
326 
352  static double qNorm(double prob);
353 
373  static double qNorm(double prob, double mu, double sigma);
374 
386  static double lnGamma (double alpha);
387 
404  static double incompleteGamma(double x, double alpha, double ln_gamma_alpha);
405 
406 
421  static double qChisq(double prob, double v);
422 
430  static double pChisq(double x, double v)
431  {
432  if (x < 0) return 0;
433  return pGamma(x, v / 2, 0.5);
434  }
435 
444  static double qGamma(double prob, double alpha, double beta)
445  {
446  return qChisq(prob,2.0*(alpha))/(2.0*(beta));
447  }
448 
459  static double pGamma(double x, double alpha, double beta) throw (Exception)
460  {
461  if (alpha < 0) throw Exception("RandomTools::pGamma. Negative alpha is not allowed.");
462  if (beta < 0) throw Exception("RandomTools::pGamma. Negative beta is not allowed.");
463  if (alpha == 0.) return 1.;
464  return incompleteGamma(beta*x, alpha, lnGamma(alpha));
465  }
466 
488  static double pNorm(double z);
489 
490  /* @brief Normal cumulative function.
491  *
492  * Returns Prob{x<=z} where x ~ N(mu,sigma^2)
493 
494  * @param z the value.
495  * @param mu The mean of the distribution
496  * @param sigma The standard deviation of the distribution
497  * @return The corresponding probability.
498  */
499 
500  static double pNorm(double z, double mu, double sigma);
501 
513  static double lnBeta (double alpha, double beta);
514 
528  static double incompleteBeta(double x, double alpha, double beta);
529  static double pBeta(double x, double alpha, double beta)
530  {
531  return incompleteBeta(x,alpha,beta);
532  }
533 
547  static double qBeta(double prob, double alpha, double beta);
548 
551  private:
552  static double DblGammaGreaterThanOne(double dblAlpha, const RandomFactory& generator);
553  static double DblGammaLessThanOne(double dblAlpha, const RandomFactory& generator);
554  };
555 
556 } //end of namespace bpp.
557 
558 #endif //_RANDOMTOOLS_H_
559 
static double pNorm(double z)
Normal cumulative function.
static double pChisq(double x, double v)
cumulative probability function.
Definition: RandomTools.h:430
static void getSample(const std::vector< T > &vin, const std::vector< double > &w, std::vector< T > &vout, bool replace=false)
Sample a vector, with associated probability weights.
Definition: RandomTools.h:303
static T pickOne(std::vector< T > &v, bool replace=false)
Pick one element in a vector.
Definition: RandomTools.h:183
static RandomFactory * DEFAULT_GENERATOR
Definition: RandomTools.h:95
This class allows to perform a correspondence analysis.
Utilitary function dealing with random numbers.
Definition: RandomTools.h:69
static double incompletebetafe2(double a, double b, double x, double big, double biginv)
static intType giveIntRandomNumberBetweenZeroAndEntry(intType entry, const RandomFactory &generator= *DEFAULT_GENERATOR)
Get an integer random value (between 0 and specified range).
Definition: RandomTools.h:121
static bool flipCoin(const RandomFactory &generator= *DEFAULT_GENERATOR)
Get a boolean random value.
Definition: RandomTools.cpp:70
static double randGamma(double dblAlpha, const RandomFactory &generator= *DEFAULT_GENERATOR)
Definition: RandomTools.cpp:80
static double DblGammaGreaterThanOne(double dblAlpha, const RandomFactory &generator)
static void getSample(const std::vector< T > &vin, std::vector< T > &vout, bool replace=false)
Sample a vector.
Definition: RandomTools.h:223
This is the interface for the Random Number Generators.
Definition: RandomFactory.h:52
static T pickOne(std::vector< T > &v, std::vector< double > &w, bool replace=false)
Pick one element in a vector, with associated probability weights.
Definition: RandomTools.h:250
static double qBeta(double prob, double alpha, double beta)
The Beta quantile function.
static double randGaussian(double mean, double variance, const RandomFactory &generator= *DEFAULT_GENERATOR)
Definition: RandomTools.cpp:75
static double incompleteGamma(double x, double alpha, double ln_gamma_alpha)
Returns the incomplete gamma ratio I(x,alpha).
static double qNorm(double prob)
Normal quantile function.
static double lnGamma(double alpha)
Computes given .
static T pickOne(const std::vector< T > &v)
Definition: RandomTools.h:198
Exception thrown when an empty vector was found.
static void setSeed(long seed)
Set the default generator seed.
Definition: RandomTools.cpp:55
static std::vector< T > cumSum(const std::vector< T > &v1)
Definition: VectorTools.h:627
static double incompletebetafe(double a, double b, double x, double big, double biginv)
functions for the computation of incompleteBeta
static double pGamma(double x, double alpha, double beta)
cumulative probability function.
Definition: RandomTools.h:459
static double pBeta(double x, double alpha, double beta)
Definition: RandomTools.h:529
static double DblGammaLessThanOne(double dblAlpha, const RandomFactory &generator)
Exception base class.
Definition: Exceptions.h:57
virtual ~RandomTools()
Definition: RandomTools.h:73
static double incompletebetaps(double a, double b, double x, double maxgam)
static double randBeta(double alpha, double beta, const RandomFactory &generator= *DEFAULT_GENERATOR)
static double giveRandomNumberBetweenZeroAndEntry(double entry, const RandomFactory &generator= *DEFAULT_GENERATOR)
Get a double random value (between 0 and specified range).
Definition: RandomTools.cpp:62
Index out of bounds exception class.
Definition: Exceptions.h:298
static std::vector< size_t > randMultinomial(size_t n, const std::vector< double > &probs)
Get a random state from a set of probabilities/scores.
static double qGamma(double prob, double alpha, double beta)
The Gamma quantile function.
Definition: RandomTools.h:444
static double qChisq(double prob, double v)
quantile function.
static double randExponential(double mean, const RandomFactory &generator= *DEFAULT_GENERATOR)
Definition: RandomTools.cpp:96
static double incompleteBeta(double x, double alpha, double beta)
Returns the regularized incomplete beta function .
static double lnBeta(double alpha, double beta)
Computes given and .