This repository was archived by the owner on Jul 7, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 552
Expand file tree
/
Copy pathCountMinSketch.java
More file actions
358 lines (312 loc) · 11.7 KB
/
Copy pathCountMinSketch.java
File metadata and controls
358 lines (312 loc) · 11.7 KB
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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.clearspring.analytics.stream.frequency;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.Serializable;
import java.util.Arrays;
import java.util.Random;
import com.clearspring.analytics.stream.membership.Filter;
import com.clearspring.analytics.util.Preconditions;
/**
* Count-Min Sketch datastructure.
* An Improved Data Stream Summary: The Count-Min Sketch and its Applications
* https://web.archive.org/web/20060907232042/http://www.eecs.harvard.edu/~michaelm/CS222/countmin.pdf
*/
public class CountMinSketch implements IFrequency, Serializable {
public static final long PRIME_MODULUS = (1L << 31) - 1;
private static final long serialVersionUID = -5084982213094657923L;
int depth;
int width;
long[][] table;
long[] hashA;
long size;
double eps;
double confidence;
CountMinSketch() {
}
public CountMinSketch(int depth, int width, int seed) {
this.depth = depth;
this.width = width;
this.eps = 2.0 / width;
this.confidence = 1 - 1 / Math.pow(2, depth);
initTablesWith(depth, width, seed);
}
public CountMinSketch(double epsOfTotalCount, double confidence, int seed) {
// 2/w = eps ; w = 2/eps
// 1/2^depth <= 1-confidence ; depth >= -log2 (1-confidence)
this.eps = epsOfTotalCount;
this.confidence = confidence;
this.width = (int) Math.ceil(2 / epsOfTotalCount);
this.depth = (int) Math.ceil(-Math.log(1 - confidence) / Math.log(2));
initTablesWith(depth, width, seed);
}
CountMinSketch(int depth, int width, long size, long[] hashA, long[][] table) {
this.depth = depth;
this.width = width;
this.eps = 2.0 / width;
this.confidence = 1 - 1 / Math.pow(2, depth);
this.hashA = hashA;
this.table = table;
Preconditions.checkState(size >= 0, "The size cannot be smaller than ZER0: " + size);
this.size = size;
}
@Override
public String toString() {
return "CountMinSketch{" +
"eps=" + eps +
", confidence=" + confidence +
", depth=" + depth +
", width=" + width +
", size=" + size +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final CountMinSketch that = (CountMinSketch) o;
if (depth != that.depth) {
return false;
}
if (width != that.width) {
return false;
}
if (Double.compare(that.eps, eps) != 0) {
return false;
}
if (Double.compare(that.confidence, confidence) != 0) {
return false;
}
if (size != that.size) {
return false;
}
if (!Arrays.deepEquals(table, that.table)) {
return false;
}
return Arrays.equals(hashA, that.hashA);
}
@Override
public int hashCode() {
int result;
long temp;
result = depth;
result = 31 * result + width;
result = 31 * result + Arrays.deepHashCode(table);
result = 31 * result + Arrays.hashCode(hashA);
result = 31 * result + (int) (size ^ (size >>> 32));
temp = Double.doubleToLongBits(eps);
result = 31 * result + (int) (temp ^ (temp >>> 32));
temp = Double.doubleToLongBits(confidence);
result = 31 * result + (int) (temp ^ (temp >>> 32));
return result;
}
private void initTablesWith(int depth, int width, int seed) {
this.table = new long[depth][width];
this.hashA = new long[depth];
Random r = new Random(seed);
// We're using a linear hash functions
// of the form (a*x+b) mod p.
// a,b are chosen independently for each hash function.
// However we can set b = 0 as all it does is shift the results
// without compromising their uniformity or independence with
// the other hashes.
for (int i = 0; i < depth; ++i) {
hashA[i] = r.nextInt(Integer.MAX_VALUE);
}
}
public double getRelativeError() {
return eps;
}
public double getConfidence() {
return confidence;
}
public int getDepth() {
return depth;
}
public int getWidth() {
return width;
}
int hash(long item, int i) {
long hash = hashA[i] * item;
// A super fast way of computing x mod 2^p-1
// See http://www.cs.princeton.edu/courses/archive/fall09/cos521/Handouts/universalclasses.pdf
// page 149, right after Proposition 7.
hash += hash >> 32;
hash &= PRIME_MODULUS;
// Doing "%" after (int) conversion is ~2x faster than %'ing longs.
return ((int) hash) % width;
}
private static void checkSizeAfterOperation(long previousSize, String operation, long newSize) {
if (newSize < previousSize) {
throw new IllegalStateException("Overflow error: the size after calling `" + operation +
"` is smaller than the previous size. " +
"Previous size: " + previousSize +
", New size: " + newSize);
}
}
private void checkSizeAfterAdd(String item, long count) {
long previousSize = size;
size += count;
checkSizeAfterOperation(previousSize, "add(" + item + "," + count + ")", size);
}
@Override
public void add(long item, long count) {
if (count < 0) {
// Actually for negative increments we'll need to use the median
// instead of minimum, and accuracy will suffer somewhat.
// Probably makes sense to add an "allow negative increments"
// parameter to constructor.
throw new IllegalArgumentException("Negative increments not implemented");
}
for (int i = 0; i < depth; ++i) {
table[i][hash(item, i)] += count;
}
checkSizeAfterAdd(String.valueOf(item), count);
}
@Override
public void add(String item, long count) {
if (count < 0) {
// Actually for negative increments we'll need to use the median
// instead of minimum, and accuracy will suffer somewhat.
// Probably makes sense to add an "allow negative increments"
// parameter to constructor.
throw new IllegalArgumentException("Negative increments not implemented");
}
int[] buckets = Filter.getHashBuckets(item, depth, width);
for (int i = 0; i < depth; ++i) {
table[i][buckets[i]] += count;
}
checkSizeAfterAdd(item, count);
}
@Override
public long size() {
return size;
}
/**
* The estimate is correct within 'epsilon' * (total item count),
* with probability 'confidence'.
*/
@Override
public long estimateCount(long item) {
long res = Long.MAX_VALUE;
for (int i = 0; i < depth; ++i) {
res = Math.min(res, table[i][hash(item, i)]);
}
return res;
}
@Override
public long estimateCount(String item) {
long res = Long.MAX_VALUE;
int[] buckets = Filter.getHashBuckets(item, depth, width);
for (int i = 0; i < depth; ++i) {
res = Math.min(res, table[i][buckets[i]]);
}
return res;
}
/**
* Merges count min sketches to produce a count min sketch for their combined streams
*
* @param estimators
* @return merged estimator or null if no estimators were provided
* @throws CMSMergeException if estimators are not mergeable (same depth, width and seed)
*/
public static CountMinSketch merge(CountMinSketch... estimators) throws CMSMergeException {
CountMinSketch merged = null;
if (estimators != null && estimators.length > 0) {
int depth = estimators[0].depth;
int width = estimators[0].width;
long[] hashA = Arrays.copyOf(estimators[0].hashA, estimators[0].hashA.length);
long[][] table = new long[depth][width];
long size = 0;
for (CountMinSketch estimator : estimators) {
if (estimator.depth != depth) {
throw new CMSMergeException("Cannot merge estimators of different depth");
}
if (estimator.width != width) {
throw new CMSMergeException("Cannot merge estimators of different width");
}
if (!Arrays.equals(estimator.hashA, hashA)) {
throw new CMSMergeException("Cannot merge estimators of different seed");
}
for (int i = 0; i < table.length; i++) {
for (int j = 0; j < table[i].length; j++) {
table[i][j] += estimator.table[i][j];
}
}
long previousSize = size;
size += estimator.size;
checkSizeAfterOperation(previousSize, "merge(" + estimator + ")", size);
}
merged = new CountMinSketch(depth, width, size, hashA, table);
}
return merged;
}
public static byte[] serialize(CountMinSketch sketch) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
DataOutputStream s = new DataOutputStream(bos);
try {
s.writeLong(sketch.size);
s.writeInt(sketch.depth);
s.writeInt(sketch.width);
for (int i = 0; i < sketch.depth; ++i) {
s.writeLong(sketch.hashA[i]);
for (int j = 0; j < sketch.width; ++j) {
s.writeLong(sketch.table[i][j]);
}
}
return bos.toByteArray();
} catch (IOException e) {
// Shouldn't happen
throw new RuntimeException(e);
}
}
public static CountMinSketch deserialize(byte[] data) {
ByteArrayInputStream bis = new ByteArrayInputStream(data);
DataInputStream s = new DataInputStream(bis);
try {
CountMinSketch sketch = new CountMinSketch();
sketch.size = s.readLong();
sketch.depth = s.readInt();
sketch.width = s.readInt();
sketch.eps = 2.0 / sketch.width;
sketch.confidence = 1 - 1 / Math.pow(2, sketch.depth);
sketch.hashA = new long[sketch.depth];
sketch.table = new long[sketch.depth][sketch.width];
for (int i = 0; i < sketch.depth; ++i) {
sketch.hashA[i] = s.readLong();
for (int j = 0; j < sketch.width; ++j) {
sketch.table[i][j] = s.readLong();
}
}
return sketch;
} catch (IOException e) {
// Shouldn't happen
throw new RuntimeException(e);
}
}
@SuppressWarnings("serial")
protected static class CMSMergeException extends FrequencyMergeException {
public CMSMergeException(String message) {
super(message);
}
}
}