]> git.donarmstrong.com Git - rsem.git/blob - sampling.h
Modified the acknowledgement section of README.md
[rsem.git] / sampling.h
1 #ifndef SAMPLING
2 #define SAMPLING
3
4 #include<ctime>
5 #include<cstdio>
6 #include<cassert>
7 #include<vector>
8 #include<set>
9
10 #include "boost/random.hpp"
11
12 typedef unsigned int seedType;
13 typedef boost::mt19937 engine_type;
14 typedef boost::gamma_distribution<> gamma_dist;
15 typedef boost::uniform_01<engine_type> uniform01;
16 typedef boost::variate_generator<engine_type&, gamma_dist> gamma_generator;
17
18 class engineFactory {
19 public:
20         static engine_type *new_engine() {
21                 seedType seed;
22                 static engine_type seedEngine(time(NULL));
23                 static std::set<seedType> seedSet;                      // empty set of seeds
24                 std::set<seedType>::iterator iter;
25
26                 do {
27                         seed = seedEngine();
28                         iter = seedSet.find(seed);
29                 } while (iter != seedSet.end());
30                 seedSet.insert(seed);
31
32                 return new engine_type(seed);
33         }
34 };
35
36 // arr should be cumulative!
37 // interval : [,)
38 // random number should be in [0, arr[len - 1])
39 // If by chance arr[len - 1] == 0.0, one possibility is to sample uniformly from 0...len-1
40 int sample(uniform01& rg, std::vector<double>& arr, int len) {
41   int l, r, mid;
42   double prb = rg() * arr[len - 1];
43
44   l = 0; r = len - 1;
45   while (l <= r) {
46     mid = (l + r) / 2;
47     if (arr[mid] <= prb) l = mid + 1;
48     else r = mid - 1;
49   }
50
51   if (l >= len) { printf("%d %lf %lf\n", len, arr[len - 1], prb); }
52   assert(l < len);
53
54   return l;
55 }
56
57 #endif