-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathreservoir.js
233 lines (198 loc) · 6.58 KB
/
reservoir.js
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
(function (root, factory) {
"use strict";
if (typeof exports === 'object') {
module.exports = factory();
} else if (typeof define === 'function' && define.amd) {
define(factory);
} else {
root.Reservoir = factory();
}
}(this, function () {
"use strict";
// We use the same constant specified in [Vitt85]
var switchToAlgorithmZConstant = 22;
// `debug` was used to test for correctness of the more complicated
// algorithms, X and Z, by comparing their results to baseline R
var debug = "none";
function _Reservoir(reservoirSize, randomNumberGen) {
var rng = randomNumberGen || Math.random;
// `reservoirSize` must be a number between 1 and 2^32
var reservoirSize =
Math.max(1, (Math.floor(reservoirSize) >> 0) || 1);
// `totalItemCount` contains the total number of items
// processed by `pushSome` against the reservoir
var totalItemCount = 0;
// `numToSkip` is the total number of elements to skip over
// before accepting one into the reservoir.
var numToSkip = -1;
// `currentAlgorithm` starts with algorithmX and switches to
// algorithmZ after `switchThreshold` items is reached
var currentAlgorithm = algorithmX;
// `switchThreshold` is the `totalItemCount` at which to switch
// over from algorithm X to Z
var switchThreshold =
switchToAlgorithmZConstant * reservoirSize;
if(debug === "R") {
currentAlgorithm = algorithmR;
} else if(debug === "X") {
switchThreshold = Infinity;
} else if(debug === "Z") {
currentAlgorithm = algorithmZ;
}
// `algorithmXCount` is the number of items processed by algorithmX
// ie. the `totalItemCount` minus `reservoirSize`
var algorithmXCount = 0;
// `W` is used in algorithmZ
var W = Math.exp(-Math.log(rng()) / reservoirSize);
// `evictNext` is used only by algorithmR
var evictNext = null;
// `targetArray` is the array to be returned by Reservoir()
var targetArray = [];
targetArray.pushSome = function() {
this.length = Math.min(this.length, reservoirSize);
for(var i = 0; i < arguments.length; i++) {
addSample.call(this, arguments[i]);
}
return this.length;
};
// `addSample` adds a single item at a time by using `numToSkip`
// to determine whether to include it in the reservoir
var addSample = function(sample) {
// Prefill the reservoir if it isn't full
if(totalItemCount < reservoirSize) {
this.push(sample);
} else {
if(numToSkip < 0) {
numToSkip = currentAlgorithm();
}
if(numToSkip === 0) {
replaceRandomSample(sample, this);
}
numToSkip--;
}
totalItemCount++;
return this;
};
// `replaceRandomSample` selects a single value from `reservoir`
// for eviction and replaces it with `sample`
function replaceRandomSample(sample, reservoir) {
// Typically, the new sample replaces the "evicted" sample
// but below we remove the evicted sample and push the
// new value to ensure that reservoir is sorted in the
// same order as the input data (ie. iterator or array).
var randomIndex;
if(evictNext !== null) {
randomIndex = evictNext;
evictNext = null;
} else {
randomIndex = Math.floor(rng() * reservoirSize);
}
reservoir.splice(randomIndex, 1);
reservoir.push(sample);
}
// From [Vitt85], "Algorithm R"
// Selects random elements from an unknown-length input.
// Has a time-complexity of:
// O(N)
// Number of random numbers required:
// N - n
// Where:
// n = the size of the reservoir
// N = the size of the input
function algorithmR() {
var localItemCount = totalItemCount + 1,
randomValue = Math.floor(rng() * localItemCount),
toSkip = 0;
while (randomValue >= reservoirSize) {
toSkip++;
localItemCount++;
randomValue = Math.floor(rng() * localItemCount);
}
evictNext = randomValue;
return toSkip;
}
// From [Vitt85], "Algorithm X"
// Selects random elements from an unknown-length input.
// Has a time-complexity of:
// O(N)
// Number of random numbers required:
// 2 * n * ln( N / n )
// Where:
// n = the size of the reservoir
// N = the size of the input
function algorithmX() {
var localItemCount = totalItemCount,
randomValue = rng(),
toSkip = 0,
quotient;
if (totalItemCount <= switchThreshold) {
localItemCount++;
algorithmXCount++;
quotient = algorithmXCount / localItemCount;
while (quotient > randomValue) {
toSkip++;
localItemCount++;
algorithmXCount++;
quotient = (quotient * algorithmXCount) / localItemCount;
}
return toSkip;
} else {
currentAlgorithm = algorithmZ;
return currentAlgorithm();
}
}
// From [Vitt85], "Algorithm Z"
// Selects random elements from an unknown-length input.
// Has a time-complexity of:
// O(n(1 + log (N / n)))
// Number of random numbers required:
// 2 * n * ln( N / n )
// Where:
// n = the size of the reservoir
// N = the size of the input
function algorithmZ() {
var term = totalItemCount - reservoirSize + 1,
denom,
numer,
numer_lim;
while(true) {
var randomValue = rng();
var x = totalItemCount * (W - 1);
var toSkip = Math.floor(x);
var subterm = ((totalItemCount + 1) / term);
subterm *= subterm;
var termSkip = term + toSkip;
var lhs = Math.exp(Math.log(((randomValue * subterm) * termSkip)/ (totalItemCount + x)) / reservoirSize);
var rhs = (((totalItemCount + x) / termSkip) * term) / totalItemCount;
if(lhs <= rhs) {
W = rhs / lhs;
break;
}
var y = (((randomValue * (totalItemCount + 1)) / term) * (totalItemCount + toSkip + 1)) / (totalItemCount + x);
if(reservoirSize < toSkip) {
denom = totalItemCount;
numer_lim = term + toSkip;
} else {
denom = totalItemCount - reservoirSize + toSkip;
numer_lim = totalItemCount + 1;
}
for(numer = totalItemCount + toSkip; numer >= numer_lim; numer--) {
y = (y * numer) / denom;
denom--;
}
W = Math.exp(-Math.log(rng()) / reservoirSize);
if(Math.exp(Math.log(y) / reservoirSize) <= (totalItemCount + x) / totalItemCount) {
break;
}
}
return toSkip;
}
return targetArray;
}
return _Reservoir;
// REFERENCES
// [Vitt85] Vitter, Jeffery S. "Random Sampling with a Reservoir." ACM
// Transactions on Mathematical Software, Vol. 11, No. 1, March
// 1985, pp. 37-57. Retrieved from
// http://www.cs.umd.edu/~samir/498/vitter.pdf
}));