source: trunk/yat/random/random.h @ 706

Last change on this file since 706 was 706, checked in by Jari Häkkinen, 17 years ago

Addresses #65 and #170.

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id
File size: 14.2 KB
Line 
1#ifndef _theplu_yat_random_
2#define _theplu_yat_random_
3
4// $Id: random.h 706 2006-12-19 08:59:19Z jari $
5
6/*
7  Copyright (C) 2005, 2006 Jari Häkkinen, Peter Johansson
8
9  This file is part of the yat library, http://lev.thep.lu.se/trac/yat
10
11  The yat library is free software; you can redistribute it and/or
12  modify it under the terms of the GNU General Public License as
13  published by the Free Software Foundation; either version 2 of the
14  License, or (at your option) any later version.
15
16  The yat library is distributed in the hope that it will be useful,
17  but WITHOUT ANY WARRANTY; without even the implied warranty of
18  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  General Public License for more details.
20
21  You should have received a copy of the GNU General Public License
22  along with this program; if not, write to the Free Software
23  Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
24  02111-1307, USA.
25*/
26
27#include "yat/statistics/Histogram.h"
28
29#include <gsl/gsl_rng.h>
30#include <gsl/gsl_randist.h>
31
32#include <string>
33
34namespace theplu {
35namespace yat {
36namespace random {
37
38  //forward declarion
39  class RNG_state;
40
41  ///
42  /// @brief Random Number Generator
43  ///
44  /// The RNG class is wrapper to the GSL random number generator
45  /// (rng). This class provides a single global instance of the rng,
46  /// and makes sure there is only one point of access to the
47  /// generator.
48  ///
49  /// There is information about how to change seeding and generators
50  /// at run time without recompilation using environment
51  /// variables. RNG of course support seeding at compile time if you
52  /// don't want to bother about environment variables and GSL.
53  ///
54  /// There are many different rng's available in GSL. Currently only
55  /// the default generator is implemented and no other one is
56  /// choosable through the class interface. This means that you have
57  /// to fall back to the use of environment variables as described in
58  /// the GSL documentation, or be bold and request support for other
59  /// rng's through the class interface.
60  ///
61  /// Not all GSL functionality is implemented, we'll add
62  /// functionality when needed and may do it when requested. Better
63  /// yet, supply us with code and we will probably add it to the code
64  /// (BUT remember to implement reasonable tests for your code and
65  /// follow the coding style.)
66  ///
67  /// This implementation may be thread safe (according to GSL
68  /// documentation), but should be checked to be so before trusting
69  /// thread safety.
70  ///
71  /// @see Design Patterns (the singleton and adapter pattern). GSL
72  /// documentation.
73  ///
74  class RNG
75  {
76  public:
77
78    virtual ~RNG(void);
79
80    ///
81    /// @brief Get an instance of the random number generator.
82    ///
83    /// Get an instance of the random number generator. If the random
84    /// number generator is not already created, the call will create
85    /// a new generator and use the default seed. The seed must be
86    /// changed with the seed or seed_from_devurandom member
87    /// functions.
88    ///
89    /// @return A pointer to the random number generator.
90    ///
91    /// @see seed and seed_from_devurandom
92    ///
93    static RNG* instance(void)
94      { if (!instance_) instance_=new RNG; return instance_; }
95
96    ///
97    /// @brief Returns the largest number that the random number
98    /// generator can return.
99    ///
100    inline u_long max(void) const { return gsl_rng_max(rng_); }
101
102    ///
103    /// @brief Returns the smallest number that the random number
104    /// generator can return.
105    ///
106    inline u_long min(void) const { return gsl_rng_min(rng_); }
107
108    ///
109    /// @brief Returns the name of the random number generator
110    ///
111    inline std::string name(void) const { return gsl_rng_name(rng_); }
112
113    ///
114    /// @return const pointer to underlying GSL random generator.
115    ///
116    inline const gsl_rng* rng(void) const { return rng_; }
117
118    ///
119    /// @brief Set the seed \a s for the rng.
120    ///
121    /// Set the seed \a s for the rng. If \a s is zero, a default
122    /// value from the rng's original implementation is used (cf. GSL
123    /// documentation).
124    ///
125    /// @see seed_from_devurandom
126    ///
127    inline void seed(u_long s) const { gsl_rng_set(rng_,s); }
128
129    ///
130    /// @brief Seed the rng using the /dev/urandom device.
131    ///
132    /// @return The seed acquired from /dev/urandom.
133    ///
134    u_long seed_from_devurandom(void);
135
136    ///
137    /// @brief set the state
138    ///
139    /// @return see gsl_rng_memcpy
140    ///
141    int set_state(const RNG_state&);
142
143  private:
144    RNG(void);
145
146    static RNG* instance_;
147    gsl_rng* rng_;
148  };
149
150
151  ///
152  /// @brief Class holding state of a random generator
153  ///
154  class RNG_state
155  {
156  public:
157    ///
158    /// @brief Constructor
159    ///
160    RNG_state(const RNG*);
161
162    ///
163    /// @brief Destructor
164    ///
165    ~RNG_state(void);
166
167    ///
168    /// @return const pointer to underlying GSL random generator.
169    ///
170    inline const gsl_rng* rng(void) const { return rng_; }
171
172
173  private:
174    gsl_rng* rng_;
175
176  };
177   
178
179  // --------------------- Discrete distribtuions ---------------------
180
181  ///
182  /// @brief Discrete random number distributions.
183  ///
184  /// Abstract base class for discrete random number
185  /// distributions. Given K discrete events with different
186  /// probabilities \f$ P[k] \f$, produce a random value k consistent
187  /// with its probability.
188  ///
189  class Discrete
190  {
191  public:
192    ///
193    /// @brief Constructor
194    ///
195    Discrete(void);
196
197    ///
198    /// @brief The destructor
199    ///
200    virtual ~Discrete(void);
201
202    ///
203    /// @brief Set the seed to \a s.
204    ///
205    /// Set the seed to \a s in the underlying rng. If \a s is zero, a
206    /// default value from the rng's original implementation is used
207    /// (cf. GSL documentation).
208    ///
209    /// @see seed_from_devurandom, RNG::seed_from_devurandom, RNG::seed
210    ///
211    inline void seed(u_long s) const { rng_->seed(s); }
212
213    ///
214    /// @brief Set the seed using the /dev/urandom device.
215    ///
216    /// @return The seed acquired from /dev/urandom.
217    ///
218    /// @see seed, RNG::seed_from_devurandom, RNG::seed
219    ///
220    u_long seed_from_devurandom(void) { return rng_->seed_from_devurandom(); }
221
222    ///
223    /// @return A random number.
224    ///
225    virtual u_long operator()(void) const = 0;
226   
227  protected:
228    /// GSL random gererator
229    RNG* rng_;
230  };
231
232  ///
233  /// @brief General
234  ///
235  class DiscreteGeneral : public Discrete
236  {
237  public:
238    ///
239    /// @brief Constructor
240    ///
241    /// @param hist is a Histogram defining the probability distribution
242    ///
243    DiscreteGeneral(const statistics::Histogram& hist);
244   
245    ///
246    /// @brief Destructor
247    ///
248    ~DiscreteGeneral(void);
249
250    ///
251    /// The generated number is an integer and proportinal to the
252    /// frequency in the corresponding histogram bin. In other words,
253    /// the probability that 0 is returned is proportinal to the size
254    /// of the first bin.
255    ///
256    /// @return A random number.
257    ///
258    inline u_long
259    operator()(void) const { return gsl_ran_discrete(rng_->rng(), gen_); }
260
261  private:
262     gsl_ran_discrete_t* gen_;
263  };
264
265  ///
266  /// @brief Discrete uniform distribution
267  ///
268  /// Discrete uniform distribution also known as the "equally likely
269  /// outcomes" distribution. Each outcome, in this case an integer
270  /// from [0,n-1] , have equal probability to occur.
271  ///
272  /// Distribution function \f$ p(k) = \frac{1}{n+1} \f$ for \f$ 0 \le
273  /// k < n \f$ \n
274  /// Expectation value: \f$ \frac{n-1}{2} \f$ \n
275  /// Variance: \f$ \frac{1}{12}(n-1)(n+1) \f$
276  ///
277  class DiscreteUniform : public Discrete
278  {
279  public:
280    ///
281    /// @brief Default constructor.
282    ///
283    DiscreteUniform(void) : range_(rng_->max()) {}
284
285    ///
286    /// @brief Constructor.
287    ///
288    /// The generator will generate integers from \f$ [0,n-1] \f$. If
289    /// \a n is larger than the maximum number the random number
290    /// generator can return, then (currently) \a n is adjusted
291    /// appropriately.
292    ///
293    /// @todo If a too large \a n is given an exception should be
294    /// thrown, i.e. the behaviour of this class will change. The case
295    /// when argument is 0 is not treated gracefully (underlying GSL
296    /// functionality will not return).
297    ///
298    DiscreteUniform(const u_long n) : range_(n)
299    { if ( range_>rng_->max() ) range_=rng_->max(); }
300
301    ///
302    /// This function returns a random integer from 0 to n-1
303    /// inclusive. All integers in the range [0,n-1] are equally
304    /// likely. n is set in constructor.
305    ///
306    inline u_long
307    operator()(void) const { return gsl_rng_uniform_int(rng_->rng(), range_); }
308
309    ///
310    /// This function returns a random integer from 0 to n-1
311    /// inclusive. All integers in the range [0,n-1] are equally
312    /// likely.
313    ///
314    inline u_long operator()(const u_long n) const
315    { return gsl_rng_uniform_int(rng_->rng(), n); }
316
317  private:
318    u_long range_;
319  };
320
321  ///
322  /// @brief Poisson Distribution
323  ///
324  /// Having a Poisson process (i.e. no memory), number of occurences
325  /// within a given time window is Poisson distributed. This
326  /// distribution is the limit of a Binomial distribution when number
327  /// of attempts is large, and the probability for one attempt to be
328  /// succesful is small (in such a way that the expected number of
329  /// succesful attempts is \f$ m \f$.
330  ///
331  /// Probability function \f$ p(k) = e^{-m}\frac{m^k}{k!} \f$ for \f$ 0 \le
332  /// k  \f$ \n
333  /// Expectation value: \f$ m \f$ \n
334  /// Variance: \f$ m \f$
335  ///
336  class Poisson : public Discrete
337  {
338  public:
339    ///
340    /// @brief Constructor
341    ///
342    /// @param m is expectation value
343    ///
344    Poisson(const double m=1);
345
346    ///
347    /// @return A Poisson distributed number.
348    ///
349    inline u_long
350    operator()(void) const { return gsl_ran_poisson(rng_->rng(), m_); }
351
352    ///
353    /// @return A Poisson distributed number with expectation value \a
354    /// m
355    ///
356    /// @note this operator ignores parameters set in Constructor
357    ///
358    inline u_long
359    operator()(const double m) const { return gsl_ran_poisson(rng_->rng(), m); }
360
361  private:
362    double m_;
363  };
364
365  // --------------------- Continuous distribtuions ---------------------
366
367  ///
368  /// @brief Continuous random number distributions.
369  ///
370  /// Abstract base class for continuous random number distributions.
371  ///
372  class Continuous
373  {
374  public:
375
376    ///
377    /// @brief Constructor
378    ///
379    Continuous(void);
380
381    ///
382    /// @brief The destructor
383    ///
384    virtual ~Continuous(void);
385
386    ///
387    /// @brief Set the seed to \a s.
388    ///
389    /// Set the seed to \a s in the underlying rng. If \a s is zero, a
390    /// default value from the rng's original implementation is used
391    /// (cf. GSL documentation).
392    ///
393    /// @see seed_from_devurandom, RNG::seed_from_devurandom, RNG::seed
394    ///
395    inline void seed(u_long s) const { rng_->seed(s); }
396
397    ///
398    /// @brief Set the seed using the /dev/urandom device.
399    ///
400    /// @return The seed acquired from /dev/urandom.
401    ///
402    /// @see seed, RNG::seed_from_devurandom, RNG::seed
403    ///
404    u_long seed_from_devurandom(void) { return rng_->seed_from_devurandom(); }
405
406    ///
407    /// @return A random number
408    ///
409    virtual double operator()(void) const = 0;
410
411  protected:
412    /// pointer to GSL random generator
413    RNG* rng_;
414  };
415
416  ///
417  /// @brief Uniform distribution
418  ///
419  /// Class for generating a random number from a uniform distribution
420  /// in the range [0,1), i.e. zero is included but not 1.
421  ///
422  /// Distribution function \f$ f(x) = 1 \f$ for \f$ 0 \le x < 1 \f$ \n
423  /// Expectation value: 0.5 \n
424  /// Variance: \f$ \frac{1}{12} \f$
425  ///
426  class ContinuousUniform : public Continuous
427  {
428  public:
429    inline double operator()(void) const { return gsl_rng_uniform(rng_->rng());}
430  };
431
432  ///
433  /// Class to generate numbers from a histogram in a continuous manner.
434  ///
435  class ContinuousGeneral : public Continuous
436  {
437  public:
438    ///
439    /// @brief Constructor
440    ///
441    /// @param hist is a Histogram defining the probability distribution
442    ///
443    ContinuousGeneral(const statistics::Histogram& hist);
444
445    ///
446    /// The number is generated in a two step process. First the bin
447    /// in the histogram is randomly selected (see
448    /// DiscreteGeneral). Then a number is generated uniformly from
449    /// the interval defined by the bin.
450    ///
451    /// @return A random number.
452    ///
453    inline double operator()(void) const 
454    { return hist_.observation_value(discrete_())+(u_()-0.5)*hist_.spacing(); }
455
456  private:
457    const DiscreteGeneral discrete_;
458    const statistics::Histogram& hist_;
459    ContinuousUniform u_;
460  };
461
462  ///
463  /// @brief Generator of random numbers from an exponential
464  /// distribution.
465  ///
466  /// The distribution function is \f$ f(x) = \frac{1}{m}\exp(-x/a)
467  /// \f$ for \f$ x \f$ with the expectation value \f$ m \f$ and
468  /// variance \f$ m^2 \f$
469  ///
470  class Exponential : public Continuous
471  {
472  public:
473    ///
474    /// @brief Constructor
475    ///
476    /// @param m is the expectation value of the distribution.
477    ///
478    inline Exponential(const double m=1);
479
480    ///
481    /// @return A random number from exponential distribution.
482    ///
483    inline double
484    operator()(void) const { return gsl_ran_exponential(rng_->rng(), m_); }
485
486    ///
487    /// @return A random number from exponential distribution, with
488    /// expectation value \a m
489    ///
490    /// @note This operator ignores parameters given in constructor.
491    ///
492    inline double operator()(const double m) const
493    { return gsl_ran_exponential(rng_->rng(), m); }
494
495  private:
496    double m_;
497  };
498
499  ///
500  /// @brief Gaussian distribution
501  ///
502  /// Class for generating a random number from a Gaussian
503  /// distribution between zero and unity. Utilizes the Box-Muller
504  /// algorithm, which needs two calls to random generator.
505  ///
506  /// Distribution function \f$ f(x) =
507  /// \frac{1}{\sqrt{2\pi\sigma^2}}\exp(-\frac{(x-\mu)^2}{2\sigma^2})
508  /// \f$ \n
509  /// Expectation value: \f$ \mu \f$ \n
510  /// Variance: \f$ \sigma^2 \f$
511  ///
512  class Gaussian : public Continuous
513  {
514  public:
515    ///
516    /// @brief Constructor
517    ///
518    /// @param s is the standard deviation \f$ \sigma \f$ of distribution
519    /// @param m is the expectation value \f$ \mu \f$ of the distribution
520    ///
521    Gaussian(const double s=1, const double m=0);
522
523    ///
524    /// @return A random Gaussian number
525    ///
526    inline double
527    operator()(void) const { return gsl_ran_gaussian(rng_->rng(), s_)+m_; }
528
529    ///
530    /// @return A random Gaussian number with standard deviation \a s
531    /// and expectation value 0.
532    ///
533    /// @note this operator ignores parameters given in Constructor
534    ///
535    inline double
536    operator()(const double s) const { return gsl_ran_gaussian(rng_->rng(), s); }
537
538    ///
539    /// @return A random Gaussian number with standard deviation \a s
540    /// and expectation value \a m.
541    ///
542    /// @note this operator ignores parameters given in Constructor
543    ///
544    inline double operator()(const double s, const double m) const
545    { return gsl_ran_gaussian(rng_->rng(), s)+m; }
546
547  private:
548    double m_;
549    double s_;
550  };
551
552}}} // of namespace random, yat, and theplu
553
554#endif
Note: See TracBrowser for help on using the repository browser.