lsst.afw  15.0-17-g0b88e3da8+6
Random.cc
Go to the documentation of this file.
1 // -*- lsst-c++ -*-
2 
3 /*
4  * LSST Data Management System
5  * Copyright 2008-2016 LSST Corporation.
6  *
7  * This product includes software developed by the
8  * LSST Project (http://www.lsst.org/).
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the LSST License Statement and
21  * the GNU General Public License along with this program. If not,
22  * see <http://www.lsstcorp.org/LegalNotices/>.
23  */
24 
25 /*
26  * Random number generator implementaion.
27  */
28 
29 #include <cstdlib>
30 #include <limits>
31 
32 #include "boost/format.hpp"
33 
34 #include "gsl/gsl_errno.h"
35 #include "gsl/gsl_randist.h"
36 
37 #include "lsst/pex/exceptions.h"
38 
39 #include "lsst/afw/math/Random.h"
40 
42 
43 namespace ex = lsst::pex::exceptions;
44 
45 namespace lsst {
46 namespace afw {
47 namespace math {
48 
49 // -- Static data --------
50 
51 ::gsl_rng_type const *const Random::_gslRngTypes[Random::NUM_ALGORITHMS] = {
52  ::gsl_rng_mt19937, ::gsl_rng_ranlxs0, ::gsl_rng_ranlxs1, ::gsl_rng_ranlxs2, ::gsl_rng_ranlxd1,
53  ::gsl_rng_ranlxd2, ::gsl_rng_ranlux, ::gsl_rng_ranlux389, ::gsl_rng_cmrg, ::gsl_rng_mrg,
54  ::gsl_rng_taus, ::gsl_rng_taus2, ::gsl_rng_gfsr4};
55 
56 char const *const Random::_algorithmNames[Random::NUM_ALGORITHMS] = {
57  "MT19937", "RANLXS0", "RANLXS1", "RANLXS2", "RANLXD1", "RANLXD2", "RANLUX",
58  "RANLUX389", "CMRG", "MRG", "TAUS", "TAUS2", "GFSR4"};
59 
60 char const *const Random::_algorithmEnvVarName = "LSST_RNG_ALGORITHM";
61 char const *const Random::_seedEnvVarName = "LSST_RNG_SEED";
62 
63 // -- Private helper functions --------
64 
65 void Random::initialize() {
66  ::gsl_rng *rng = ::gsl_rng_alloc(_gslRngTypes[_algorithm]);
67  if (rng == 0) {
68  throw std::bad_alloc();
69  }
70  // This seed is guaranteed to be non-zero.
71  // We want to give a non-zero seed to GSL to avoid it choosing its own.
72  unsigned long int useSeed = _seed == 0 ? std::numeric_limits<unsigned long int>::max() : _seed;
73  ::gsl_rng_set(rng, useSeed);
74  _rng.reset(rng, ::gsl_rng_free);
75 }
76 
77 void Random::initialize(std::string const &algorithm) {
78  // linear search (the number of algorithms is small)
79  for (int i = 0; i < NUM_ALGORITHMS; ++i) {
80  if (_algorithmNames[i] == algorithm) {
81  _algorithm = static_cast<Algorithm>(i);
82  initialize();
83  return;
84  }
85  }
86  throw LSST_EXCEPT(ex::InvalidParameterError, "RNG algorithm " + algorithm + " is not supported");
87 }
88 
89 // -- Constructor --------
90 
91 Random::Random(Algorithm const algorithm, unsigned long seed) : _rng(), _seed(seed), _algorithm(algorithm) {
92  if (_algorithm < 0 || _algorithm >= NUM_ALGORITHMS) {
93  throw LSST_EXCEPT(ex::InvalidParameterError, "Invalid RNG algorithm");
94  }
95  initialize();
96 }
97 
98 Random::Random(std::string const &algorithm, unsigned long seed) : _rng(), _seed(seed) {
99  initialize(algorithm);
100 }
101 
102 Random::Random(std::shared_ptr<pex::policy::Policy> const policy) : _rng(), _seed() {
103  std::string const seed(policy->getString("rngSeed"));
104  try {
105  _seed = std::stoul(seed);
106  } catch (std::invalid_argument &) {
107  throw LSST_EXCEPT(
109  (boost::format("Invalid argument in \"rngSeed\" policy value: \"%1%\"") % seed).str());
110  } catch (std::out_of_range &) {
112  (boost::format("Out of range in \"rngSeed\" policy value: \"%1%\"") % seed).str());
113  }
114  initialize(policy->getString("rngAlgorithm"));
115 }
116 
118  Random rng = *this;
119  rng._rng.reset(::gsl_rng_clone(_rng.get()), ::gsl_rng_free);
120  if (!rng._rng) {
121  throw std::bad_alloc();
122  }
123  return rng;
124 }
125 
127  return State(static_cast<char *>(::gsl_rng_state(_rng.get())), getStateSize());
128 }
129 
130 void Random::setState(State const &state) {
131  if (state.size() != getStateSize()) {
132  throw LSST_EXCEPT(
134  (boost::format("Size of given state vector (%d) does not match expected size (%d)") %
135  state.size() % getStateSize())
136  .str());
137  }
138  std::copy(state.begin(), state.end(), static_cast<char *>(::gsl_rng_state(_rng.get())));
139 }
140 
141 std::size_t Random::getStateSize() const { return ::gsl_rng_size(_rng.get()); }
142 
143 // -- Accessors --------
144 
145 Random::Algorithm Random::getAlgorithm() const { return _algorithm; }
146 
147 std::string Random::getAlgorithmName() const { return std::string(_algorithmNames[_algorithm]); }
148 
150  static std::vector<std::string> names;
151  if (names.size() == 0) {
152  for (int i = 0; i < NUM_ALGORITHMS; ++i) {
153  names.push_back(_algorithmNames[i]);
154  }
155  }
156  return names;
157 }
158 
159 unsigned long Random::getSeed() const { return _seed; }
160 
161 // -- Mutators: generating random numbers --------
162 
163 double Random::uniform() { return ::gsl_rng_uniform(_rng.get()); }
164 
165 double Random::uniformPos() { return ::gsl_rng_uniform_pos(_rng.get()); }
166 
167 unsigned long Random::uniformInt(unsigned long n) {
168  if (n > ::gsl_rng_max(_rng.get()) - ::gsl_rng_min(_rng.get())) {
169  throw LSST_EXCEPT(ex::RangeError, "Desired random number range exceeds generator range");
170  }
171  return ::gsl_rng_uniform_int(_rng.get(), n);
172 }
173 
174 // -- Mutators: computing random variates for various distributions --------
175 
176 double Random::flat(double const a, double const b) { return ::gsl_ran_flat(_rng.get(), a, b); }
177 
178 double Random::gaussian() { return ::gsl_ran_gaussian_ziggurat(_rng.get(), 1.0); }
179 
180 double Random::chisq(double nu) { return ::gsl_ran_chisq(_rng.get(), nu); }
181 
182 double Random::poisson(double mu) { return ::gsl_ran_poisson(_rng.get(), mu); }
183 }
184 }
185 } // lsst::afw::math
double poisson(double const mu)
Returns a random variate from the poisson distribution with mean mu.
Definition: Random.cc:182
T copy(T... args)
std::string State
Accessors for the opaque state of the random number generator.
Definition: Random.h:176
State getState() const
Accessors for the opaque state of the random number generator.
Definition: Random.cc:126
Random(Algorithm algorithm=MT19937, unsigned long seed=1)
Creates a random number generator that uses the given algorithm to produce random numbers...
Definition: Random.cc:91
static std::vector< std::string > const & getAlgorithmNames()
Definition: Random.cc:149
std::string getAlgorithmName() const
Definition: Random.cc:147
T end(T... args)
unsigned long uniformInt(unsigned long n)
Returns a uniformly distributed random integer from 0 to n-1.
Definition: Random.cc:167
T stoul(T... args)
STL class.
T push_back(T... args)
Number of supported algorithms.
Definition: Random.h:97
void setState(State const &state)
Accessors for the opaque state of the random number generator.
Definition: Random.cc:130
A base class for image defects.
table::Key< int > b
double chisq(double const nu)
Returns a random variate from the chi-squared distribution with nu degrees of freedom.
Definition: Random.cc:180
T reset(T... args)
double flat(double const a, double const b)
Returns a random variate from the flat (uniform) distribution on [a, b).
Definition: Random.cc:176
unsigned long getSeed() const
Definition: Random.cc:159
T max(T... args)
double gaussian()
Returns a gaussian random variate with mean 0 and standard deviation 1
Definition: Random.cc:178
double uniformPos()
Returns a uniformly distributed random double precision floating point number from the generator...
Definition: Random.cc:165
Random deepCopy() const
Creates a deep copy of this random number generator.
Definition: Random.cc:117
Algorithm
Identifiers for the list of supported algorithms.
Definition: Random.h:65
T get(T... args)
T size(T... args)
std::size_t getStateSize() const
Accessors for the opaque state of the random number generator.
Definition: Random.cc:141
#define LSST_EXCEPT(type,...)
T begin(T... args)
STL class.
table::Key< int > a
double uniform()
Returns a uniformly distributed random double precision floating point number from the generator...
Definition: Random.cc:163
Algorithm getAlgorithm() const
Definition: Random.cc:145
A class that can be used to generate sequences of random numbers according to a number of different a...
Definition: Random.h:62