/
sample.h
204 lines (190 loc) · 8.21 KB
/
sample.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
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; indent-tabs-mode: nil; -*-
/* :tabSize=4:indentSize=4:noTabs=false:folding=explicit:collapseFolds=1: */
//
// sample.h: Rcpp/Armadillo equivalent to R's sample().
// This is intended for use in C++ functions, and should *not* be called from R.
// It should yield identical results to R in most cases,
// and stop with errors when results are expected to differ.
//
// Copyright (C) 2012 - 2014 Christian Gunning
// Copyright (C) 2013 Romain Francois
//
// This file is part of RcppArmadillo.
//
// RcppArmadillo is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 2 of the License, or
// (at your option) any later version.
//
// RcppArmadillo is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with RcppArmadillo. If not, see <http://www.gnu.org/licenses/>.
#ifndef RCPPARMADILLO__EXTENSIONS__SAMPLE_H
#define RCPPARMADILLO__EXTENSIONS__SAMPLE_H
#include <RcppArmadilloExtensions/fixprob.h>
namespace Rcpp{
namespace RcppArmadillo{
void SampleNoReplace( IntegerVector &index, int nOrig, int size);
void SampleReplace( IntegerVector &index, int nOrig, int size);
void ProbSampleNoReplace(IntegerVector &index, int nOrig, int size, arma::vec &prob);
void ProbSampleReplace(IntegerVector &index, int nOrig, int size, arma::vec &prob);
void WalkerProbSampleReplace(IntegerVector &index, int nOrig, int size, arma::vec &prob);
template <class T>
T sample(const T &x, const int size, const bool replace, NumericVector prob_ = NumericVector(0) ) {
// Templated sample -- should work on any Rcpp Vector
int ii, jj;
int nOrig = x.size();
int probsize = prob_.size();
// Create return object
T ret(size);
if ( size > nOrig && !replace) throw std::range_error( "Tried to sample more elements than in x without replacement" ) ;
if ( !replace && (probsize==0) && nOrig > 1e+07 && size <= nOrig/2) {
throw std::range_error( "R uses .Internal(sample2(n, size) for this case, which is not implemented." ) ;
}
// Store the sample ids here, modify in-place
IntegerVector index(size);
if (probsize == 0) { // No probabilities given
if (replace) {
SampleReplace(index, nOrig, size);
} else {
SampleNoReplace(index, nOrig, size);
}
} else {
if (probsize != nOrig) throw std::range_error( "Number of probabilities must equal input vector length" ) ;
// copy probs once, pass-by-ref hereafter
NumericVector fixprob = clone(prob_);
// normalize, error-check probability vector
// fixprob will be modified in-place
FixProb(fixprob, size, replace);
// don't reallocate the (cloned, fixed) prob vec
arma::vec prob(fixprob.begin(), fixprob.size(), false);
//
if (replace) {
// check for walker alias conditions
int walker_test = sum( (prob * nOrig) > 0.1);
if (walker_test > 200) {
WalkerProbSampleReplace(index, nOrig, size, prob);
} else {
ProbSampleReplace(index, nOrig, size, prob);
}
} else {
ProbSampleNoReplace(index, nOrig, size, prob);
}
}
// copy the results into the return vector
for (ii=0; ii<size; ii++) {
jj = index[ii];
ret[ii] = x[jj];
}
return(ret);
}
// worker functions
void SampleReplace( IntegerVector &index, int nOrig, int size) {
int ii;
for (ii = 0; ii < size; ii++) {
index[ii] = nOrig * unif_rand();
}
}
void SampleNoReplace( IntegerVector &index, int nOrig, int size) {
int ii, jj;
IntegerVector sub(nOrig);
for (ii = 0; ii < nOrig; ii++) {
sub[ii] = ii;
}
for (ii = 0; ii < size; ii++) {
jj = nOrig * unif_rand();
index[ii] = sub[jj];
// replace sampled element with last, decrement
sub[jj] = sub[--nOrig];
}
}
// Unequal probability sampling with replacement
void ProbSampleReplace(IntegerVector &index, int nOrig, int size, arma::vec &prob){
double rU;
int ii, jj;
int nOrig_1 = nOrig - 1;
arma::uvec perm = arma::sort_index(prob, 1); //descending sort of index
prob = arma::sort(prob, 1); // descending sort of prob
// cumulative probabilities
prob = arma::cumsum(prob);
// compute the sample
for (ii = 0; ii < size; ii++) {
rU = unif_rand();
for (jj = 0; jj < nOrig_1; jj++) {
if (rU <= prob[jj])
break;
}
index[ii] = perm[jj];
}
}
// Unequal probability sampling with replacement, prob.size() large and sum(prob) >0.1
void WalkerProbSampleReplace(IntegerVector &index, int nOrig, int size, arma::vec &prob){
double rU;
int ii, jj, kk; // indices, ii for loops
// index tables, fill with zeros
IntegerVector HL_dat(nOrig);
IntegerVector alias_tab(nOrig);
IntegerVector::iterator H, L, H0, L0;
//HL0 = HL_dat.begin();
H0 = H = HL_dat.begin();
L0 = L = HL_dat.end();
//prob *= nOrig; // scale probability table
// fill HL_dat from beginning (small prob) and end (large prob) with indices
for (ii = 0; ii < nOrig; ii++) {
prob[ii] *= nOrig;
if( prob[ii] < 1.0) {
*(H++) = ii;
} else {
*(--L) = ii;
}
}
// some of both large and small
if ( (H > H0) && (L < L0) ) {
for (kk = 0; kk < nOrig; kk++) {
ii = HL_dat[kk];
jj = *L;
alias_tab[ii] = jj;
prob[jj] += (prob[ii] - 1);
if (prob[jj] < 1.) L++;
if(L == L0) break; // now all prob >= 1
}
}
for (ii = 0; ii < nOrig; ii++) prob[ii] += ii;
/* generate sample */
for (ii = 0; ii < size; ii++) {
rU = unif_rand() * nOrig;
kk = (int) rU;
index[ii] = (rU < prob[kk]) ? kk : alias_tab[kk];
}
}
// Unequal probability sampling without replacement
void ProbSampleNoReplace(IntegerVector &index, int nOrig, int size, arma::vec &prob){
int ii, jj, kk;
int nOrig_1 = nOrig - 1;
double rT, mass, totalmass = 1.0;
arma::uvec perm = arma::sort_index(prob, 1); //descending sort of index
prob = arma::sort(prob, 1); // descending sort of prob
// compute the sample
for (ii = 0; ii < size; ii++, nOrig_1--) {
rT = totalmass * unif_rand();
mass = 0;
for (jj = 0; jj < nOrig_1; jj++) {
mass += prob[jj];
if (rT <= mass)
break;
}
index[ii] = perm[jj];
totalmass -= prob[jj];
for ( kk = jj; kk < nOrig_1; kk++) {
prob[kk] = prob[kk+1];
perm[kk] = perm[kk+1];
}
}
}
}
}
#endif