-
Notifications
You must be signed in to change notification settings - Fork 2
/
discrete_distribution_ii.h
266 lines (206 loc) · 7.1 KB
/
discrete_distribution_ii.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/*
*
* Copyright (c) 2015, G.A. Kohring
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef DISCRETE_DISTRIBUTION_II_H
#define DISCRETE_DISTRIBUTION_II_H
/*
* A class for producing random integers i in [0,n) with prbability p(i).
*
* This implementation uses the square histrogram method in combination with a
* small look-up table.
*
* (see: "Fast Generation of Discrete Random Variables", by G. Marsaglia,
* W. W. Tsang and J. Wang, Journal of Statistical Software,
* July 2004, Vol. 11., Nr. 3. )
*/
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <deque>
#include <functional>
#include <map>
#include <cmath>
#include <numeric>
#include <random>
#include <vector>
namespace rng {
template<typename _IntType = int >
class discrete_distribution_30bit {
static_assert( std::is_integral<_IntType>::value,
"template argument not an integral type");
private:
std::vector<double> P;
std::vector<double> V;
std::vector<int> K;
int _J[256];
int size;
public:
typedef _IntType result_type;
/*
* The constructor takes as input iterators over probabilities. The
* probabilities should sum to one.
*
* Only the first thirty bits in the probabilities are used.
*/
template <class InputIterator>
discrete_distribution_30bit( InputIterator first, InputIterator last ):
P( first, last ) {
if ( P.size() == 0 ) {
perror( "no probablities." );
abort();
}
size = P.size();
K.resize( size, 0 );
V.resize( size, 0.0 );
double max_val = static_cast<double>( ( (1 << 30) - 1 ) );
double norm = 0.0;
for ( int n = 0; n < size; ++n ) {
P[n] = std::floor( ( P[n]*max_val ) );
norm += P[n];
}
for ( int n = 0; n < size; ++n ) P[n] /= norm;
init();
}
~discrete_distribution_30bit(){}
/*
* Generates the next random number in the sequence.
*
*/
template<typename _UniformRandomNumberGenerator>
result_type operator()( _UniformRandomNumberGenerator& _urng ) {
unsigned uran = _urng();
int d = _J[ uran & 255 ];
if ( d >= 0 ) {
return d;
} else {
double U = static_cast<double>(uran)*2.328306437e-10;
d = static_cast<int>( static_cast<double>( size )*U );
if ( U < V[d] ) {
return d;
} else {
return K[d];
}
}
}
void reset() {}
/*
* Returns a vector containing the probabilities used in this
* instance.
*
*/
std::vector<double> probabilities() const {
return std::vector<double>( P.begin(), P.end() );
}
/*
* Returns the minimum random integer.
*
*/
result_type min() const {
return result_type( 0 );
}
/*
* Returns the maximum random integer.
*
*/
result_type max() const {
return result_type( size - 1 );
}
/*
* Check for equality by checking that the probabilities are the same.
*
*/
friend bool operator==( const discrete_distribution_30bit& v1,
const discrete_distribution_30bit& v2) {
return v1.P == v2.P;
}
private:
/*
* Initialize the look-up table and the histogram.
*
*/
void init() {
std::vector<double> probs( P.begin(), P.end() );
// ensure the probabilities are normalized
double sum = 0.0;
for ( int i = 0; i < size; ++i ) sum += probs[i];
for ( int i = 0; i < size; ++i ) probs[i] /= sum;
// fill in the look-up table
int L = 0;
double p_sum = 0.0;
double a = 1.0/static_cast<double>( size );
for ( int i = 0; i < size; ++i ) {
int k = static_cast<int>( 256.0*probs[i] );
probs[i] = 256.0*probs[i] - static_cast<double>( k );
p_sum += probs[i];
for ( int j = 0; j < k; ++j ) _J[L+j] = i;
L += k;
}
// fill empty table slots with -1
for( int i = L; i < 256; ++i ) _J[i] = -1;
/*
fprintf(stderr,"Table is %5.2f percent full\n",
100.0*static_cast<double>(L)/256.0 );
*/
// Initialize K, V
for ( int j = 0; j < size; ++j ) {
K[j] = j;
V[j] = a*static_cast<double>(j + 1);
}
// normalize new probs
double p_norm = 1.0/p_sum;
for ( int i = 0; i < size; ++i ) probs[i] *= p_norm;
std::multimap<double,int> mp;
for ( int i = 0; i < size; ++i ) {
mp.insert( std::pair<double,int>( probs[i], i ) );
}
// Apply Robin Hood rule
for ( int i = 1; i <= size; ++i ) {
std::multimap<double,int>::iterator imin = mp.begin();
std::multimap<double,int>::iterator imax = std::prev( mp.end() );
double min_p = (*imin).first;
int min_i = (*imin).second;
double max_p = (*imax).first;
int max_i = (*imax).second;
V[min_i] = min_p + static_cast<double>(min_i)*a;
K[min_i] = max_i;
mp.erase( std::prev( mp.end() ) );
mp.erase( mp.begin() );
max_p = (max_p + min_p) - a;
mp.insert( std::pair<double,int>( a, min_i ) );
mp.insert( std::pair<double,int>( max_p, max_i ) );
}
}
};
template<typename _IntType>
inline bool operator!=( const rng::discrete_distribution_30bit<_IntType>& v1,
const rng::discrete_distribution_30bit<_IntType>& v2) {
return !(v1.P == v2.P);
}
}; // namespace rng
#endif // DISCRETE_DISTRIBUTION_II_H