Remove PrivateImplPointer in favour of std::unique_ptr
[alexxy/gromacs.git] / src / gromacs / random / uniformintdistribution.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2015,2016,2018,2019,2021, by the GROMACS development team, led by
5  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6  * and including many others, as listed in the AUTHORS file in the
7  * top-level source directory and at http://www.gromacs.org.
8  *
9  * GROMACS is free software; you can redistribute it and/or
10  * modify it under the terms of the GNU Lesser General Public License
11  * as published by the Free Software Foundation; either version 2.1
12  * of the License, or (at your option) any later version.
13  *
14  * GROMACS is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  * Lesser General Public License for more details.
18  *
19  * You should have received a copy of the GNU Lesser General Public
20  * License along with GROMACS; if not, see
21  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
23  *
24  * If you want to redistribute modifications to GROMACS, please
25  * consider that scientific software is very special. Version
26  * control is crucial - bugs must be traceable. We will be happy to
27  * consider code for inclusion in the official distribution, but
28  * derived work must not be called official GROMACS. Details are found
29  * in the README & COPYING files - if they are missing, get the
30  * official version at http://www.gromacs.org.
31  *
32  * To help us fund GROMACS development, we humbly ask that you cite
33  * the research papers on the package. Check out http://www.gromacs.org.
34  */
35
36 /*! \file
37  * \brief The uniform integer distribution
38  *
39  * Portable version of the uniform integer that generates the same sequence
40  * on all platforms. Since stdlibc++ and libc++ provide different sequences
41  * we prefer this one so unit tests produce the same values on all platforms.
42  *
43  * \author Erik Lindahl <erik.lindahl@gmail.com>
44  * \inpublicapi
45  * \ingroup module_random
46  */
47
48 #ifndef GMX_RANDOM_UNIFORMINTDISTRIBUTION_H
49 #define GMX_RANDOM_UNIFORMINTDISTRIBUTION_H
50
51 #include <limits>
52 #include <memory>
53
54 #include "gromacs/math/functions.h"
55 #include "gromacs/utility/basedefinitions.h"
56 #include "gromacs/utility/classhelpers.h"
57 #include "gromacs/utility/gmxassert.h"
58
59 namespace gmx
60 {
61
62 /*! \brief Uniform integer distribution
63  *
64  *  The C++ standard library does provide this distribution, but even
65  *  though they all sample from the correct distribution different standard
66  *  library implementations appear to return different sequences of numbers
67  *  for the same random number generator. To make it easier to use GROMACS
68  *  unit tests that depend on random numbers we have our own implementation.
69  *
70  * \tparam IntType Integer type, int by default.
71  */
72 template<class IntType = int>
73 class UniformIntDistribution
74 {
75 public:
76     /*! \brief Type of values returned */
77     typedef IntType result_type;
78
79     /*! \brief Uniform int distribution parameters */
80     class param_type
81     {
82         /*! \brief Lower end of range (inclusive) */
83         result_type a_;
84         /*! \brief Upper end of range (inclusive) */
85         result_type b_;
86
87     public:
88         /*! \brief Reference back to the distribution class */
89         typedef UniformIntDistribution distribution_type;
90
91         /*! \brief Construct parameter block
92          *
93          * \param a   Lower end of range (inclusive)
94          * \param b   Upper end of range (inclusive)
95          */
96         explicit param_type(result_type a = 0, result_type b = std::numeric_limits<result_type>::max()) :
97             a_(a),
98             b_(b)
99         {
100             GMX_RELEASE_ASSERT(a <= b, "The uniform integer distribution requires a<=b");
101         }
102
103         /*! \brief Return lower range */
104         result_type a() const { return a_; }
105         /*! \brief Return upper range */
106         result_type b() const { return b_; }
107
108         /*! \brief True if two parameter sets will return the same uniform int distribution.
109          *
110          * \param x  Instance to compare with.
111          */
112         bool operator==(const param_type& x) const
113         {
114             // rangeBits is a function of a & b, so it does not have to be tested
115             return a_ == x.a_ && b_ == x.b_;
116         }
117
118         /*! \brief True if two parameter sets will return different uniform int distributions
119          *
120          * \param x  Instance to compare with.
121          */
122         bool operator!=(const param_type& x) const { return !operator==(x); }
123     };
124
125 public:
126     /*! \brief Construct new distribution with given integer parameters.
127      *
128      * \param a   Lower end of range (inclusive)
129      * \param b   Upper end of range (inclusive)
130      */
131     explicit UniformIntDistribution(result_type a = 0,
132                                     result_type b = std::numeric_limits<result_type>::max()) :
133         param_(param_type(a, b)),
134         savedRandomBits_(0),
135         savedRandomBitsLeft_(0)
136     {
137     }
138
139     /*! \brief Construct new distribution from parameter class
140      *
141      * \param param  Parameter class as defined inside gmx::UniformIntDistribution.
142      */
143     explicit UniformIntDistribution(const param_type& param) :
144         param_(param),
145         savedRandomBits_(0),
146         savedRandomBitsLeft_(0)
147     {
148     }
149
150     /*! \brief Flush all internal saved values  */
151     void reset() { savedRandomBitsLeft_ = 0; }
152
153     /*! \brief Return values from uniform int distribution with internal parameters
154      *
155      * \tparam Rng  Uniform random engine class
156      *
157      * \param  g    Random engine
158      */
159     template<class Rng>
160     result_type operator()(Rng& g)
161     {
162         return (*this)(g, param_);
163     }
164
165     /*! \brief Return value from uniform int distribution with given parameters
166      *
167      * \tparam Rng   Uniform random engine class
168      *
169      * \param  g     Random engine
170      * \param  param Parameters to use
171      */
172     template<class Rng>
173     result_type operator()(Rng& g, const param_type& param)
174     {
175         static_assert(sizeof(typename Rng::result_type) >= sizeof(uint32_t),
176                       "The random engine result_type should be 32 or 64 bits");
177
178         result_type  range = param.b() - param.a();
179         unsigned int rangeBits;
180         result_type  result;
181
182         if (range == 0)
183         {
184             return param.a();
185         }
186         else if (range == std::numeric_limits<result_type>::max())
187         {
188             rangeBits = std::numeric_limits<result_type>::digits; // Use all bits in type
189         }
190         else
191         {
192             if (sizeof(result_type) == sizeof(uint32_t))
193             {
194                 rangeBits = log2I(static_cast<uint32_t>(range));
195             }
196             else
197             {
198                 rangeBits = log2I(range);
199             }
200             rangeBits += ((range >> rangeBits) > 0);
201         }
202
203         do
204         {
205             if (savedRandomBitsLeft_ < rangeBits)
206             {
207                 savedRandomBits_     = static_cast<uint64_t>(g());
208                 savedRandomBitsLeft_ = std::numeric_limits<typename Rng::result_type>::digits;
209
210                 if (sizeof(typename Rng::result_type) == sizeof(uint32_t))
211                 {
212                     savedRandomBits_ <<= std::numeric_limits<uint32_t>::digits;
213                     savedRandomBits_ |= g();
214                     savedRandomBitsLeft_ += std::numeric_limits<uint32_t>::digits;
215                 }
216             }
217             result = savedRandomBits_;
218             savedRandomBits_ >>= rangeBits;
219             result = result - (savedRandomBits_ << rangeBits);
220             savedRandomBitsLeft_ -= rangeBits;
221         } while (result > range);
222
223         return result + param.a();
224     }
225
226     /*! \brief Return the lower range uniform int distribution */
227     result_type a() const { return param_.a(); }
228
229     /*! \brief Return the upper range of the uniform int distribution */
230     result_type b() const { return param_.b(); }
231
232     /*! \brief Return the full parameter class of the uniform int distribution */
233     param_type param() const { return param_; }
234
235     /*! \brief Smallest value that can be returned from uniform int distribution */
236     result_type min() const { return a(); }
237
238     /*! \brief Largest value that can be returned from uniform int distribution */
239     result_type max() const { return b(); }
240
241     /*! \brief True if two uniform int distributions will produce the same values.
242      *
243      * \param  x     Instance to compare with.
244      */
245     bool operator==(const UniformIntDistribution& x) const { return param_ == x.param_; }
246
247     /*! \brief True if two uniform int distributions will produce different values.
248      *
249      * \param  x     Instance to compare with.
250      */
251     bool operator!=(const UniformIntDistribution& x) const { return !operator==(x); }
252
253 private:
254     /*! \brief Internal value for parameters, can be overridden at generation time. */
255     param_type param_;
256     /*! \brief Saved output from random engine, shifted tableBits right each time */
257     uint64_t savedRandomBits_;
258     /*! \brief Number of valid bits remaining i savedRandomBits_ */
259     unsigned int savedRandomBitsLeft_;
260
261     GMX_DISALLOW_COPY_AND_ASSIGN(UniformIntDistribution);
262 };
263
264 } // namespace gmx
265
266 #endif // GMX_RANDOM_UNIFORMINTDISTRIBUTION_H