LSSTApplications  19.0.0-14-gb0260a2+72efe9b372,20.0.0+7927753e06,20.0.0+8829bf0056,20.0.0+995114c5d2,20.0.0+b6f4b2abd1,20.0.0+bddc4f4cbe,20.0.0-1-g253301a+8829bf0056,20.0.0-1-g2b7511a+0d71a2d77f,20.0.0-1-g5b95a8c+7461dd0434,20.0.0-12-g321c96ea+23efe4bbff,20.0.0-16-gfab17e72e+fdf35455f6,20.0.0-2-g0070d88+ba3ffc8f0b,20.0.0-2-g4dae9ad+ee58a624b3,20.0.0-2-g61b8584+5d3db074ba,20.0.0-2-gb780d76+d529cf1a41,20.0.0-2-ged6426c+226a441f5f,20.0.0-2-gf072044+8829bf0056,20.0.0-2-gf1f7952+ee58a624b3,20.0.0-20-geae50cf+e37fec0aee,20.0.0-25-g3dcad98+544a109665,20.0.0-25-g5eafb0f+ee58a624b3,20.0.0-27-g64178ef+f1f297b00a,20.0.0-3-g4cc78c6+e0676b0dc8,20.0.0-3-g8f21e14+4fd2c12c9a,20.0.0-3-gbd60e8c+187b78b4b8,20.0.0-3-gbecbe05+48431fa087,20.0.0-38-ge4adf513+a12e1f8e37,20.0.0-4-g97dc21a+544a109665,20.0.0-4-gb4befbc+087873070b,20.0.0-4-gf910f65+5d3db074ba,20.0.0-5-gdfe0fee+199202a608,20.0.0-5-gfbfe500+d529cf1a41,20.0.0-6-g64f541c+d529cf1a41,20.0.0-6-g9a5b7a1+a1cd37312e,20.0.0-68-ga3f3dda+5fca18c6a4,20.0.0-9-g4aef684+e18322736b,w.2020.45
LSSTDataManagementBasePackage
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 
41 namespace ex = lsst::pex::exceptions;
42 
43 namespace lsst {
44 namespace afw {
45 namespace math {
46 
47 // -- Static data --------
48 
49 ::gsl_rng_type const *const Random::_gslRngTypes[Random::NUM_ALGORITHMS] = {
50  ::gsl_rng_mt19937, ::gsl_rng_ranlxs0, ::gsl_rng_ranlxs1, ::gsl_rng_ranlxs2, ::gsl_rng_ranlxd1,
51  ::gsl_rng_ranlxd2, ::gsl_rng_ranlux, ::gsl_rng_ranlux389, ::gsl_rng_cmrg, ::gsl_rng_mrg,
52  ::gsl_rng_taus, ::gsl_rng_taus2, ::gsl_rng_gfsr4};
53 
54 char const *const Random::_algorithmNames[Random::NUM_ALGORITHMS] = {
55  "MT19937", "RANLXS0", "RANLXS1", "RANLXS2", "RANLXD1", "RANLXD2", "RANLUX",
56  "RANLUX389", "CMRG", "MRG", "TAUS", "TAUS2", "GFSR4"};
57 
58 char const *const Random::_algorithmEnvVarName = "LSST_RNG_ALGORITHM";
59 char const *const Random::_seedEnvVarName = "LSST_RNG_SEED";
60 
61 // -- Private helper functions --------
62 
63 void Random::initialize() {
64  ::gsl_rng *rng = ::gsl_rng_alloc(_gslRngTypes[_algorithm]);
65  if (rng == 0) {
66  throw std::bad_alloc();
67  }
68  // This seed is guaranteed to be non-zero.
69  // We want to give a non-zero seed to GSL to avoid it choosing its own.
70  unsigned long int useSeed = _seed == 0 ? std::numeric_limits<unsigned long int>::max() : _seed;
71  ::gsl_rng_set(rng, useSeed);
72  _rng.reset(rng, ::gsl_rng_free);
73 }
74 
75 void Random::initialize(std::string const &algorithm) {
76  // linear search (the number of algorithms is small)
77  for (int i = 0; i < NUM_ALGORITHMS; ++i) {
78  if (_algorithmNames[i] == algorithm) {
79  _algorithm = static_cast<Algorithm>(i);
80  initialize();
81  return;
82  }
83  }
84  throw LSST_EXCEPT(ex::InvalidParameterError, "RNG algorithm " + algorithm + " is not supported");
85 }
86 
87 // -- Constructor --------
88 
89 Random::Random(Algorithm const algorithm, unsigned long seed) : _rng(), _seed(seed), _algorithm(algorithm) {
90  if (_algorithm < 0 || _algorithm >= NUM_ALGORITHMS) {
91  throw LSST_EXCEPT(ex::InvalidParameterError, "Invalid RNG algorithm");
92  }
93  initialize();
94 }
95 
96 Random::Random(std::string const &algorithm, unsigned long seed) : _rng(), _seed(seed) {
97  initialize(algorithm);
98 }
99 
101  Random rng = *this;
102  rng._rng.reset(::gsl_rng_clone(_rng.get()), ::gsl_rng_free);
103  if (!rng._rng) {
104  throw std::bad_alloc();
105  }
106  return rng;
107 }
108 
110  return State(static_cast<char *>(::gsl_rng_state(_rng.get())), getStateSize());
111 }
112 
113 void Random::setState(State const &state) {
114  if (state.size() != getStateSize()) {
115  throw LSST_EXCEPT(
117  (boost::format("Size of given state vector (%d) does not match expected size (%d)") %
118  state.size() % getStateSize())
119  .str());
120  }
121  std::copy(state.begin(), state.end(), static_cast<char *>(::gsl_rng_state(_rng.get())));
122 }
123 
124 std::size_t Random::getStateSize() const { return ::gsl_rng_size(_rng.get()); }
125 
126 // -- Accessors --------
127 
128 Random::Algorithm Random::getAlgorithm() const { return _algorithm; }
129 
130 std::string Random::getAlgorithmName() const { return std::string(_algorithmNames[_algorithm]); }
131 
133  static std::vector<std::string> names;
134  if (names.size() == 0) {
135  for (int i = 0; i < NUM_ALGORITHMS; ++i) {
136  names.push_back(_algorithmNames[i]);
137  }
138  }
139  return names;
140 }
141 
142 unsigned long Random::getSeed() const { return _seed; }
143 
144 // -- Mutators: generating random numbers --------
145 
146 double Random::uniform() { return ::gsl_rng_uniform(_rng.get()); }
147 
148 double Random::uniformPos() { return ::gsl_rng_uniform_pos(_rng.get()); }
149 
150 unsigned long Random::uniformInt(unsigned long n) {
151  if (n > ::gsl_rng_max(_rng.get()) - ::gsl_rng_min(_rng.get())) {
152  throw LSST_EXCEPT(ex::RangeError, "Desired random number range exceeds generator range");
153  }
154  return ::gsl_rng_uniform_int(_rng.get(), n);
155 }
156 
157 // -- Mutators: computing random variates for various distributions --------
158 
159 double Random::flat(double const a, double const b) { return ::gsl_ran_flat(_rng.get(), a, b); }
160 
161 double Random::gaussian() { return ::gsl_ran_gaussian_ziggurat(_rng.get(), 1.0); }
162 
163 double Random::chisq(double nu) { return ::gsl_ran_chisq(_rng.get(), nu); }
164 
165 double Random::poisson(double mu) { return ::gsl_ran_poisson(_rng.get(), mu); }
166 } // namespace math
167 } // namespace afw
168 } // namespace lsst
lsst::afw::math::Random::flat
double flat(double const a, double const b)
Returns a random variate from the flat (uniform) distribution on [a, b).
Definition: Random.cc:159
std::string
STL class.
lsst::afw::math::Random::uniformPos
double uniformPos()
Returns a uniformly distributed random double precision floating point number from the generator.
Definition: Random.cc:148
lsst::afw::math::Random::getAlgorithmName
std::string getAlgorithmName() const
Definition: Random.cc:130
std::bad_alloc
STL class.
std::vector< std::string >
std::string::size
T size(T... args)
lsst.pex::exceptions::RangeError
Reports when the result of an operation cannot be represented by the destination type.
Definition: Runtime.h:115
lsst::afw::math::Random::Random
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:89
lsst::afw
Definition: imageAlgorithm.dox:1
std::shared_ptr::get
T get(T... args)
lsst.pex.config.history.format
def format(config, name=None, writeSourceLine=True, prefix="", verbose=False)
Definition: history.py:174
lsst::afw::math::Random::getStateSize
std::size_t getStateSize() const
Definition: Random.cc:124
lsst::afw::math::Random::uniform
double uniform()
Returns a uniformly distributed random double precision floating point number from the generator.
Definition: Random.cc:146
std::shared_ptr::reset
T reset(T... args)
lsst::afw::math::Random::getSeed
unsigned long getSeed() const
Definition: Random.cc:142
lsst::afw::math::Random::uniformInt
unsigned long uniformInt(unsigned long n)
Returns a uniformly distributed random integer from 0 to n-1.
Definition: Random.cc:150
std::vector::push_back
T push_back(T... args)
lsst::afw::math::Random::getAlgorithm
Algorithm getAlgorithm() const
Definition: Random.cc:128
lsst::afw::math::Random::getAlgorithmNames
static std::vector< std::string > const & getAlgorithmNames()
Definition: Random.cc:132
lsst.pex::exceptions::LengthError
Reports attempts to exceed implementation-defined length limits for some classes.
Definition: Runtime.h:76
lsst::afw::math::Random::chisq
double chisq(double const nu)
Returns a random variate from the chi-squared distribution with nu degrees of freedom.
Definition: Random.cc:163
lsst::afw::math::Random::Algorithm
Algorithm
Identifiers for the list of supported algorithms.
Definition: Random.h:60
std::copy
T copy(T... args)
b
table::Key< int > b
Definition: TransmissionCurve.cc:467
lsst::afw::math::Random::State
std::string State
Accessors for the opaque state of the random number generator.
Definition: Random.h:154
lsst
A base class for image defects.
Definition: imageAlgorithm.dox:1
LSST_EXCEPT
#define LSST_EXCEPT(type,...)
Create an exception with a given type.
Definition: Exception.h:48
lsst::afw::math::Random::NUM_ALGORITHMS
@ NUM_ALGORITHMS
Number of supported algorithms.
Definition: Random.h:92
lsst::afw::math::Random::setState
void setState(State const &state)
Definition: Random.cc:113
lsst::afw::math::Random::getState
State getState() const
Definition: Random.cc:109
lsst::afw::math::Random
A class that can be used to generate sequences of random numbers according to a number of different a...
Definition: Random.h:57
lsst.pex::exceptions::InvalidParameterError
Reports invalid arguments.
Definition: Runtime.h:66
a
table::Key< int > a
Definition: TransmissionCurve.cc:466
lsst::afw::math::Random::gaussian
double gaussian()
Returns a gaussian random variate with mean 0 and standard deviation 1
Definition: Random.cc:161
std::string::begin
T begin(T... args)
lsst.pex::exceptions
Definition: Exception.h:37
std::size_t
std::string::end
T end(T... args)
Random.h
std::numeric_limits::max
T max(T... args)
lsst::afw::math::Random::deepCopy
Random deepCopy() const
Creates a deep copy of this random number generator.
Definition: Random.cc:100
lsst::afw::math::Random::poisson
double poisson(double const mu)
Returns a random variate from the poisson distribution with mean mu.
Definition: Random.cc:165
exceptions.h