lsst.afw  14.0-22-gc76603d1b
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 
31 #include "boost/format.hpp"
32 
33 #include "gsl/gsl_errno.h"
34 #include "gsl/gsl_randist.h"
35 
36 #include "lsst/pex/exceptions.h"
37 
38 #include "lsst/afw/math/Random.h"
39 
41 
42 namespace ex = lsst::pex::exceptions;
43 
44 namespace lsst {
45 namespace afw {
46 namespace math {
47 
48 // -- Static data --------
49 
50 ::gsl_rng_type const *const Random::_gslRngTypes[Random::NUM_ALGORITHMS] = {
51  ::gsl_rng_mt19937, ::gsl_rng_ranlxs0, ::gsl_rng_ranlxs1, ::gsl_rng_ranlxs2, ::gsl_rng_ranlxd1,
52  ::gsl_rng_ranlxd2, ::gsl_rng_ranlux, ::gsl_rng_ranlux389, ::gsl_rng_cmrg, ::gsl_rng_mrg,
53  ::gsl_rng_taus, ::gsl_rng_taus2, ::gsl_rng_gfsr4};
54 
55 char const *const Random::_algorithmNames[Random::NUM_ALGORITHMS] = {
56  "MT19937", "RANLXS0", "RANLXS1", "RANLXS2", "RANLXD1", "RANLXD2", "RANLUX",
57  "RANLUX389", "CMRG", "MRG", "TAUS", "TAUS2", "GFSR4"};
58 
59 char const *const Random::_algorithmEnvVarName = "LSST_RNG_ALGORITHM";
60 char const *const Random::_seedEnvVarName = "LSST_RNG_SEED";
61 
62 // -- Private helper functions --------
63 
64 void Random::initialize() {
65  if (_seed == 0) {
66  throw LSST_EXCEPT(ex::InvalidParameterError, (boost::format("Invalid RNG seed: %lu") % _seed).str());
67  }
68  ::gsl_rng *rng = ::gsl_rng_alloc(_gslRngTypes[_algorithm]);
69  if (rng == 0) {
70  throw LSST_EXCEPT(ex::MemoryError, "gsl_rng_alloc() failed");
71  }
72  ::gsl_rng_set(rng, _seed);
73  _rng.reset(rng, ::gsl_rng_free);
74 }
75 
76 void Random::initialize(std::string const &algorithm) {
77  // linear search (the number of algorithms is small)
78  for (int i = 0; i < NUM_ALGORITHMS; ++i) {
79  if (_algorithmNames[i] == algorithm) {
80  _algorithm = static_cast<Algorithm>(i);
81  initialize();
82  return;
83  }
84  }
85  throw LSST_EXCEPT(ex::InvalidParameterError, "RNG algorithm " + algorithm + " is not supported");
86 }
87 
88 // -- Constructor --------
89 
90 Random::Random(Algorithm const algorithm, unsigned long seed) : _rng(), _seed(seed), _algorithm(algorithm) {
91  if (_algorithm < 0 || _algorithm >= NUM_ALGORITHMS) {
92  throw LSST_EXCEPT(ex::InvalidParameterError, "Invalid RNG algorithm");
93  }
94  initialize();
95 }
96 
97 Random::Random(std::string const &algorithm, unsigned long seed) : _rng(), _seed(seed) {
98  initialize(algorithm);
99 }
100 
101 Random::Random(std::shared_ptr<pex::policy::Policy> const policy) : _rng(), _seed() {
102  std::string const seed(policy->getString("rngSeed"));
103  try {
104  _seed = std::stoul(seed);
105  } catch (std::invalid_argument &) {
106  throw LSST_EXCEPT(
108  (boost::format("Invalid argument in \"rngSeed\" policy value: \"%1%\"") % seed).str());
109  } catch (std::out_of_range &) {
111  (boost::format("Out of range in \"rngSeed\" policy value: \"%1%\"") % seed).str());
112  }
113  initialize(policy->getString("rngAlgorithm"));
114 }
115 
117  Random rng = *this;
118  rng._rng.reset(::gsl_rng_clone(_rng.get()), ::gsl_rng_free);
119  if (!rng._rng) {
120  throw LSST_EXCEPT(ex::MemoryError, "gsl_rng_clone() failed");
121  }
122  return rng;
123 }
124 
126  return State(static_cast<char *>(::gsl_rng_state(_rng.get())), getStateSize());
127 }
128 
129 void Random::setState(State const &state) {
130  if (state.size() != getStateSize()) {
131  throw LSST_EXCEPT(
133  (boost::format("Size of given state vector (%d) does not match expected size (%d)") %
134  state.size() % getStateSize())
135  .str());
136  }
137  std::copy(state.begin(), state.end(), static_cast<char *>(::gsl_rng_state(_rng.get())));
138 }
139 
140 std::size_t Random::getStateSize() const { return ::gsl_rng_size(_rng.get()); }
141 
142 // -- Accessors --------
143 
144 Random::Algorithm Random::getAlgorithm() const { return _algorithm; }
145 
146 std::string Random::getAlgorithmName() const { return std::string(_algorithmNames[_algorithm]); }
147 
149  static std::vector<std::string> names;
150  if (names.size() == 0) {
151  for (int i = 0; i < NUM_ALGORITHMS; ++i) {
152  names.push_back(_algorithmNames[i]);
153  }
154  }
155  return names;
156 }
157 
158 unsigned long Random::getSeed() const { return _seed; }
159 
160 // -- Mutators: generating random numbers --------
161 
162 double Random::uniform() { return ::gsl_rng_uniform(_rng.get()); }
163 
164 double Random::uniformPos() { return ::gsl_rng_uniform_pos(_rng.get()); }
165 
166 unsigned long Random::uniformInt(unsigned long n) {
167  if (n > ::gsl_rng_max(_rng.get()) - ::gsl_rng_min(_rng.get())) {
168  throw LSST_EXCEPT(ex::RangeError, "Desired random number range exceeds generator range");
169  }
170  return ::gsl_rng_uniform_int(_rng.get(), n);
171 }
172 
173 // -- Mutators: computing random variates for various distributions --------
174 
175 double Random::flat(double const a, double const b) { return ::gsl_ran_flat(_rng.get(), a, b); }
176 
177 double Random::gaussian() { return ::gsl_ran_gaussian_ziggurat(_rng.get(), 1.0); }
178 
179 double Random::chisq(double nu) { return ::gsl_ran_chisq(_rng.get(), nu); }
180 
181 double Random::poisson(double mu) { return ::gsl_ran_poisson(_rng.get(), mu); }
182 }
183 }
184 } // lsst::afw::math
double poisson(double const mu)
Returns a random variate from the poisson distribution with mean mu.
Definition: Random.cc:181
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:125
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:90
static std::vector< std::string > const & getAlgorithmNames()
Definition: Random.cc:148
std::string getAlgorithmName() const
Definition: Random.cc:146
T end(T... args)
unsigned long uniformInt(unsigned long n)
Returns a uniformly distributed random integer from 0 to n-1.
Definition: Random.cc:166
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:129
A base class for image defects.
double chisq(double const nu)
Returns a random variate from the chi-squared distribution with nu degrees of freedom.
Definition: Random.cc:179
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:175
unsigned long getSeed() const
Definition: Random.cc:158
double gaussian()
Returns a gaussian random variate with mean 0 and standard deviation 1
Definition: Random.cc:177
double uniformPos()
Returns a uniformly distributed random double precision floating point number from the generator...
Definition: Random.cc:164
Random deepCopy() const
Creates a deep copy of this random number generator.
Definition: Random.cc:116
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:140
#define LSST_EXCEPT(type,...)
T begin(T... args)
double uniform()
Returns a uniformly distributed random double precision floating point number from the generator...
Definition: Random.cc:162
Algorithm getAlgorithm() const
Definition: Random.cc:144
A class that can be used to generate sequences of random numbers according to a number of different a...
Definition: Random.h:62