IMP logo
IMP Reference Guide  2.20.0
The Integrative Modeling Platform
random.h
Go to the documentation of this file.
1 /**
2  * \file IMP/random.h \brief Random number generators used by IMP.
3  *
4  * Copyright 2007-2022 IMP Inventors. All rights reserved.
5  *
6  */
7 
8 #ifndef IMPKERNEL_RANDOM_H
9 #define IMPKERNEL_RANDOM_H
10 
11 #include <IMP/kernel_config.h>
12 #include <IMP/Vector.h>
13 #include <random>
14 
15 IMPKERNEL_BEGIN_NAMESPACE
16 
17 #ifndef SWIG // the RNG is defined explicitly in pyext/IMP_kernel.random.i
18 
19 class RandomNumberGenerator : public std::mt19937 {
20  typedef std::mt19937 T;
21  T::result_type last_seed_;
22  unsigned seed_counter_;
23 
24 public:
25  RandomNumberGenerator()
26  : T(default_seed), last_seed_(default_seed), seed_counter_(1) {}
27 
28  RandomNumberGenerator(T::result_type seed)
29  : T(seed), last_seed_(seed), seed_counter_(1) {}
30 
31  void seed() { seed(default_seed); }
32 
33  // Set a new seed
34  void seed(T::result_type seed) {
35  last_seed_ = seed;
36  seed_counter_++;
37  if (seed_counter_ == 0) {
38  seed_counter_ = 1;
39  }
40  T::seed(seed);
41  }
42 
43  // Get the last-set seed, either from when the class was constructed or
44  // from a previous call to seed()
45  T::result_type get_last_seed() const { return last_seed_; }
46 
47  // Get the counter value from when the seed was last set. This value
48  // will never be zero. This can be used to determine if the seed was
49  // changed since the last use.
50  unsigned get_seed_counter() const { return seed_counter_; }
51 };
52 
53 //! A shared non-GPU random number generator
54 /** The random number generator is seeded based on command line specified flag.
55  Otherwise, the default seed is retrieved from among either
56  boost::random_device, `/dev/urandom`, or the system clock, based on which
57  method is available in this priority order.
58 
59  To set the seed, call the `seed` method, which takes a single integer
60  argument. This object is also callable, and returns a new random integer
61  on each call.
62 
63 This generator can be used by the
64 [Boost.Random](https://www.boost.org/doc/libs/1_80_0/doc/html/boost_random.html)
65 distributions.
66  */
67 extern IMPKERNELEXPORT RandomNumberGenerator random_number_generator;
68 #endif
69 
70 //! Return the initial random seed.
71 /** To set the seed or get random values, see IMP::random_number_generator.
72  */
73 IMPKERNELEXPORT boost::uint64_t get_random_seed();
74 
75 
76 IMPKERNEL_END_NAMESPACE
77 
78 #endif /* IMPKERNEL_RANDOM_H */
boost::uint64_t get_random_seed()
Return the initial random seed.
A class for storing lists of IMP items.
RandomNumberGenerator random_number_generator
A shared non-GPU random number generator.