Debian Codegraph @

current/bloom/KCountArray8MT.java

raw symbols SCIP
1 package bloom;
2
3 import java.util.Arrays;
4 import java.util.Random;
5 import java.util.concurrent.ArrayBlockingQueue;
6
7 import shared.Primes;
8 import shared.Shared;
9 import shared.Timer;
10 import shared.Tools;
11 import structures.ByteBuilder;
12
13
14 /**
15 *
16 * Uses prime numbers for array lengths.
17 * Supports a prefilter that is checked before looking at the main filter.
18 *
19 * @author Brian Bushnell
20 * @date Aug 17, 2012
21 *
22 */
23 public class KCountArray8MT extends KCountArray {
24
25 /**
26 *
27 */
28 private static final long serialVersionUID = -3146298383509476887L;
29
30 public static void main(String[] args){
31 long cells=Long.parseLong(args[0]);
32 int bits=Integer.parseInt(args[1]);
33 int hashes=Integer.parseInt(args[3]);
34
35 verbose=false;
36
37 KCountArray8MT kca=new KCountArray8MT(cells, bits, hashes, null);
38
39 System.out.println(kca.read(0));
40 kca.increment(0);
41 System.out.println(kca.read(0));
42 kca.increment(0);
43 System.out.println(kca.read(0));
44 System.out.println();
45
46 System.out.println(kca.read(1));
47 kca.increment(1);
48 System.out.println(kca.read(1));
49 kca.increment(1);
50 System.out.println(kca.read(1));
51 System.out.println();
52
53 System.out.println(kca.read(100));
54 kca.increment(100);
55 System.out.println(kca.read(100));
56 kca.increment(100);
57 System.out.println(kca.read(100));
58 kca.increment(100);
59 System.out.println(kca.read(100));
60 System.out.println();
61
62
63 System.out.println(kca.read(150));
64 kca.increment(150);
65 System.out.println(kca.read(150));
66 System.out.println();
67
68 }
69
70 public KCountArray8MT(long cells_, int bits_, int hashes_, KCountArray prefilter_){
71 super(getPrimeCells(cells_, bits_), bits_, getDesiredArrays(cells_, bits_));
72 // verbose=false;
73 // assert(false);
74 cellsPerArray=cells/numArrays;
75 wordsPerArray=(int)((cellsPerArray%cellsPerWord)==0 ? (cellsPerArray/cellsPerWord) : (cellsPerArray/cellsPerWord+1));
76 cellMod=cellsPerArray;
77 hashes=hashes_;
78 // System.out.println("cells="+cells+", words="+words+", wordsPerArray="+wordsPerArray+", numArrays="+numArrays+", hashes="+hashes);
79 // assert(false);
80 matrix=new int[numArrays][];
81 prefilter=prefilter_;
82 assert(prefilter!=null);
83 assert(hashes>0 && hashes<=hashMasks.length);
84 }
85
86 private static int getDesiredArrays(long desiredCells, int bits){
87
88 long words=Tools.max((desiredCells*bits+31)/32, minArrays);
89 int arrays=minArrays;
90 while(words/arrays>=Integer.MAX_VALUE){
91 arrays*=2;
92 }
93 return arrays;
94 }
95
96 private static long getPrimeCells(long desiredCells, int bits){
97
98 int arrays=getDesiredArrays(desiredCells, bits);
99
100 long x=(desiredCells+arrays-1)/arrays;
101 long x2=Primes.primeAtMost(x);
102 return x2*arrays;
103 }
104
105 @Override
106 public int read(final long rawKey){
107 assert(finished);
108 if(verbose){System.err.println("Reading raw key "+rawKey);}
109 int pre=0;
110 if(prefilter!=null){
111 pre=prefilter.read(rawKey);
112 if(pre<prefilter.maxValue){return pre;}
113 }
114 long key2=hash(rawKey, 0);
115 int min=readHashed(key2);
116 for(int i=1; i<hashes && min>0; i++){
117 if(verbose){System.err.println("Reading. i="+i+", key2="+key2);}
118 key2=Long.rotateRight(key2, hashBits);
119 key2=hash(key2, i);
120 if(verbose){System.err.println("Rot/hash. i="+i+", key2="+key2);}
121 min=min(min, readHashed(key2));
122 }
123 return min;
124 }
125
126 private int readHashed(long key){
127 if(verbose){System.err.print("Reading hashed key "+key);}
128 // System.out.println("key="+key);
129 int arrayNum=(int)(key&arrayMask);
130 key=(key>>>arrayBits)%(cellMod);
131 // key=(key>>>(arrayBits+1))%(cellMod);
132 // System.out.println("array="+arrayNum);
133 // System.out.println("key2="+key);
134 int[] array=matrix[arrayNum];
135 int index=(int)(key>>>indexShift);
136 // assert(false) : indexShift;
137 // System.out.println("index="+index);
138 int word=array[index];
139 // System.out.println("word="+Integer.toHexString(word));
140 assert(word>>>(cellBits*key) == word>>>(cellBits*(key&cellMask)));
141 // int cellShift=(int)(cellBits*(key&cellMask));
142 int cellShift=(int)(cellBits*key);
143 if(verbose){System.err.println(", array="+arrayNum+", index="+index+", cellShift="+(cellShift%32)+", value="+((int)((word>>>cellShift)&valueMask)));}
144 // System.out.println("cellShift="+cellShift);
145 return (int)((word>>>cellShift)&valueMask);
146 }
147
148 @Override
149 public void write(final long key, int value){
150 throw new RuntimeException("Not allowed for this class.");
151 }
152
153 @Override
154 /** This should increase speed by doing the first hash outside the critical section, but it does not seem to help. */
155 public void increment(long[] keys){
156 if(prefilter==null){
157 for(int i=0; i<keys.length; i++){
158 keys[i]=hash(keys[i], 0);
159 }
160 synchronized(buffers){
161 for(long key : keys){
162 incrementPartiallyHashed(key);
163 }
164 }
165 }else{
166 int j=0;
167 for(int i=0; i<keys.length; i++){
168 long key=keys[i];
169 int x=prefilter.read(key);
170 if(x==prefilter.maxValue){
171 keys[j]=hash(key, 0);
172 j++;
173 }
174 }
175 synchronized(buffers){
176 for(int i=0; i<j; i++){
177 incrementPartiallyHashed(keys[i]);
178 }
179 }
180 }
181 }
182
183 //Slow
184 @Override
185 public void increment(final long rawKey, int amt){
186 for(int i=0; i<amt; i++){increment0(rawKey);}
187 }
188
189 public void increment0(final long rawKey){
190 if(verbose){System.err.println("\n*** Incrementing raw key "+rawKey+" ***");}
191 if(prefilter!=null){
192 int pre=prefilter.read(rawKey);
193 if(pre<prefilter.maxValue){return;}
194 }
195
196 long key2=rawKey;
197 for(int i=0; i<hashes; i++){
198 key2=hash(key2, i);
199 if(verbose){System.err.println("key2="+key2+", value="+readHashed(key2));}
200 // assert(readHashed(key2)==0);
201
202 int bnum=(int)(key2&arrayMask);
203 long[] array=buffers[bnum];
204 int loc=bufferlen[bnum];
205 array[loc]=key2;
206 bufferlen[bnum]++;
207 if(verbose){System.err.println("bufferlen["+bnum+"] = "+bufferlen[bnum]);}
208 if(bufferlen[bnum]>=array.length){
209
210 if(verbose){System.err.println("Moving array.");}
211 bufferlen[bnum]=0;
212 buffers[bnum]=new long[array.length];
213
214 writers[bnum].add(array);
215 if(verbose){System.err.println("Moved.");}
216 }
217 // assert(read(rawKey)<=min+incr) : "i="+i+", original="+min+", new should be <="+(min+incr)+", new="+read(rawKey)+", max="+maxValue+", key="+rawKey;
218 // assert(readHashed(key2)>=min+incr) : "i="+i+", original="+min+", new should be <="+(min+incr)+", new="+read(rawKey)+", max="+maxValue+", key="+rawKey;
219 key2=Long.rotateRight(key2, hashBits);
220 }
221 }
222
223 private void incrementPartiallyHashed(final long pKey){
224 if(verbose){System.err.println("\n*** Incrementing key "+pKey+" ***");}
225
226 long key2=pKey;
227
228 {
229 int bnum=(int)(key2&arrayMask);
230 long[] array=buffers[bnum];
231 int loc=bufferlen[bnum];
232 array[loc]=key2;
233 bufferlen[bnum]++;
234 if(verbose){System.err.println("bufferlen["+bnum+"] = "+bufferlen[bnum]);}
235 if(bufferlen[bnum]>=array.length){
236
237 if(verbose){System.err.println("Moving array.");}
238 bufferlen[bnum]=0;
239 buffers[bnum]=new long[array.length];
240
241 writers[bnum].add(array);
242 if(verbose){System.err.println("Moved.");}
243 }
244 }
245
246 for(int i=1; i<hashes; i++){
247 key2=Long.rotateRight(key2, hashBits);
248 key2=hash(key2, i);
249 if(verbose){System.err.println("key2="+key2+", value="+readHashed(key2));}
250 // assert(readHashed(key2)==0);
251
252 int bnum=(int)(key2&arrayMask);
253 long[] array=buffers[bnum];
254 int loc=bufferlen[bnum];
255 array[loc]=key2;
256 bufferlen[bnum]++;
257 if(verbose){System.err.println("bufferlen["+bnum+"] = "+bufferlen[bnum]);}
258 if(bufferlen[bnum]>=array.length){
259
260 if(verbose){System.err.println("Moving array.");}
261 bufferlen[bnum]=0;
262 buffers[bnum]=new long[array.length];
263
264 writers[bnum].add(array);
265 if(verbose){System.err.println("Moved.");}
266 }
267 }
268 }
269
270 /** Returns unincremented value */
271 @Override
272 public int incrementAndReturnUnincremented(long key, int incr){
273 throw new RuntimeException("Operation not supported.");
274 }
275
276 @Override
277 public long[] transformToFrequency(){
278 return transformToFrequency(matrix);
279 }
280
281 @Override
282 public ByteBuilder toContentsString(){
283 ByteBuilder sb=new ByteBuilder();
284 sb.append('[');
285 String comma="";
286 for(int[] array : matrix){
287 for(int i=0; i<array.length; i++){
288 int word=array[i];
289 for(int j=0; j<cellsPerWord; j++){
290 int x=word&valueMask;
291 sb.append(comma);
292 sb.append(x);
293 word>>>=cellBits;
294 comma=", ";
295 }
296 }
297 }
298 sb.append(']');
299 return sb;
300 }
301
302 @Override
303 public double usedFraction(){return cellsUsed/(double)cells;}
304
305 @Override
306 public double usedFraction(int mindepth){return cellsUsed(mindepth)/(double)cells;}
307
308 @Override
309 public long cellsUsed(int mindepth){
310 long count=0;
311 // System.out.println("A: "+cellBits+", "+Integer.toBinaryString(valueMask));
312 for(int[] array : matrix){
313 // System.out.println("B");
314 if(array!=null){
315 // System.out.println("C");
316 for(int word : array){
317 // System.out.println("D: "+Integer.toBinaryString(word));
318 while(word>0){
319 int x=word&valueMask;
320 // System.out.println("E: "+x+", "+mindepth);
321 if(x>=mindepth){count++;}
322 word>>>=cellBits;
323 }
324 }
325 }
326 }
327 return count;
328 }
329
330 @Override
331 final long hash(long key, int row){
332 int cell=(int)((Long.MAX_VALUE&key)%(hashArrayLength-1));
333 // int cell=(int)(hashCellMask&(key));
334
335 if(row==0){//Doublehash only first time
336 key=key^hashMasks[(row+4)%hashMasks.length][cell];
337 cell=(int)(hashCellMask&(key>>5));
338 // cell=(int)(hashCellMask&(key>>hashBits));
339 // cell=(int)((Long.MAX_VALUE&key)%(hashArrayLength-1));
340 }
341
342 return key^hashMasks[row][cell];
343 }
344
345 /**
346 * @param i
347 * @param j
348 * @return
349 */
350 private static long[][] makeMasks(int rows, int cols) {
351
352 long seed;
353 synchronized(KCountArray8MT.class){
354 seed=counter;
355 counter++;
356 }
357
358 Timer t=new Timer();
359 long[][] r=new long[rows][cols];
360 Random randy=Shared.threadLocalRandom(seed);
361 for(int i=0; i<r.length; i++){
362 fillMasks(r[i], randy);
363 }
364 t.stop();
365 if(t.elapsed>200000000L){System.out.println("Mask-creation time: "+t);}
366 return r;
367 }
368
369 private static void fillMasks(long[] r, Random randy) {
370 // for(int i=0; i<r.length; i++){
371 // long x=0;
372 // while(Long.bitCount(x&0xFFFFFFFF)!=16){
373 // x=randy.nextLong();
374 // }
375 // r[i]=(x&Long.MAX_VALUE);
376 // }
377
378 final int hlen=(1<<hashBits);
379 assert(r.length==hlen);
380 int[] count1=new int[hlen];
381 int[] count2=new int[hlen];
382 final long mask=hlen-1;
383
384 for(int i=0; i<r.length; i++){
385 long x=0;
386 int y=0;
387 int z=0;
388 while(Long.bitCount(x&0xFFFFFFFFL)!=16){
389 x=randy.nextLong();
390 while(Long.bitCount(x&0xFFFFFFFFL)<16){
391 x|=(1L<<randy.nextInt(32));
392 }
393 while(Long.bitCount(x&0xFFFFFFFFL)>16){
394 x&=(~(1L<<randy.nextInt(32)));
395 }
396 while(Long.bitCount(x&0xFFFFFFFF00000000L)<16){
397 x|=(1L<<(randy.nextInt(32)+32));
398 }
399 while(Long.bitCount(x&0xFFFFFFFF00000000L)>16){
400 x&=(~(1L<<(randy.nextInt(32)+32)));
401 }
402
403 // System.out.print(".");
404 // y=(((int)(x&mask))^i);
405 y=(((int)(x&mask)));
406 z=(int)((x>>hashBits)&mask);
407 if(count1[y]>0 || count2[z]>0){
408 x=0;
409 }
410 }
411 // System.out.println(Long.toBinaryString(x));
412 r[i]=(x&Long.MAX_VALUE);
413 count1[y]++;
414 count2[z]++;
415 }
416
417 }
418
419
420 @Override
421 public void initialize(){
422 for(int i=0; i<writers.length; i++){
423 writers[i]=new WriteThread(i);
424 writers[i].start();
425
426 // while(!writers[i].isAlive()){
427 // System.out.print(".");
428 // }
429 }
430 }
431
432 @Override
433 public void shutdown(){
434 if(finished){return;}
435 synchronized(this){
436 if(finished){return;}
437
438 //Clear buffers
439 for(int i=0; i<numArrays; i++){
440 long[] array=buffers[i];
441 int len=bufferlen[i];
442 buffers[i]=null;
443 bufferlen[i]=0;
444
445 if(len<array.length){
446 array=Arrays.copyOf(array, len);
447 }
448
449 if(array.length>0){
450 writers[i].add(array);
451 }
452 }
453
454 //Add poison
455 for(WriteThread wt : writers){
456 wt.add(poison);
457 }
458
459 //Wait for termination
460 for(WriteThread wt : writers){
461 // System.out.println("wt"+wt.num+" is alive: "+wt.isAlive());
462 while(wt.isAlive()){
463 // System.out.println("wt"+wt.num+" is alive: "+wt.isAlive());
464 try {
465 wt.join(10000);
466 } catch (InterruptedException e) {
467 // TODO Auto-generated catch block
468 e.printStackTrace();
469 }
470 if(wt.isAlive()){System.err.println(wt.getClass().getCanonicalName()+" is taking a long time to die.");}
471 }
472 cellsUsed+=wt.cellsUsedPersonal;
473 // System.out.println("cellsUsed="+cellsUsed);
474 }
475
476 assert(!finished);
477 finished=true;
478 }
479 }
480
481 private class WriteThread extends Thread{
482
483 public WriteThread(int tnum){
484 num=tnum;
485 }
486
487 @Override
488 public void run(){
489 assert(matrix[num]==null);
490 array=new int[wordsPerArray]; //Makes NUMA systems use local memory.
491
492 matrix[num]=array;
493
494 long[] keys=null;
495 while(!shutdown){
496
497 if(verbose){System.err.println(" - Reading keys for wt"+num+".");}
498 while(keys==null){
499 try {
500 keys=writeQueue.take();
501 } catch (InterruptedException e) {
502 // TODO Auto-generated catch block
503 e.printStackTrace();
504 }
505 }
506 if(keys==poison){
507 // assert(false);
508 shutdown=true;
509 }else{
510 for(long key : keys){
511 incrementHashedLocal(key);
512 }
513 }
514 // System.out.println(" -- Read keys for wt"+num+". poison="+(keys==poison)+", len="+keys.length);
515 if(verbose){System.err.println(" -- Read keys for wt"+num+". (success)");}
516 keys=null;
517 if(verbose){System.err.println("shutdown="+shutdown);}
518 }
519
520 // System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> I died: "+shutdown+", "+(keys==null)+".");
521 // assert(false) : ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> I died: "+shutdown+", "+(keys==null)+".";
522
523 array=null;
524 }
525
526 void add(long[] keys){
527 // assert(isAlive());
528 assert(!shutdown);
529 if(shutdown){return;}
530 // assert(keys!=poison);
531 if(verbose){System.err.println(" + Adding keys to wt"+num+".");}
532 boolean success=false;
533 while(!success){
534 try {
535 writeQueue.put(keys);
536 success=true;
537 } catch (InterruptedException e) {
538 // TODO Auto-generated catch block
539 e.printStackTrace();
540 }
541 }
542 if(verbose){System.err.println(" ++ Added keys to wt"+num+". (success)");}
543 }
544
545 private int incrementHashedLocal(long key){
546 assert((key&arrayMask)==num);
547 key=(key>>>arrayBits)%(cellMod);
548 // key=(key>>>(arrayBits+1))%(cellMod);
549 int index=(int)(key>>>indexShift);
550 int word=array[index];
551 int cellShift=(int)(cellBits*key);
552 int value=((word>>>cellShift)&valueMask);
553 if(value==0){cellsUsedPersonal++;}
554 value=min(value+1, maxValue);
555 word=(value<<cellShift)|(word&~((valueMask)<<cellShift));
556 array[index]=word;
557 return value;
558 }
559
560 private int[] array;
561 private final int num;
562 public long cellsUsedPersonal=0;
563
564 public ArrayBlockingQueue<long[]> writeQueue=new ArrayBlockingQueue<long[]>(16);
565 public boolean shutdown=false;
566
567 }
568
569
570 public long cellsUsed(){return cellsUsed;}
571
572 private boolean finished=false;
573
574 private long cellsUsed;
575 final int[][] matrix;
576 private final WriteThread[] writers=new WriteThread[numArrays];
577 private final int hashes;
578 final int wordsPerArray;
579 private final long cellsPerArray;
580 final long cellMod;
581 private final long[][] hashMasks=makeMasks(8, hashArrayLength);
582
583 private final long[][] buffers=new long[numArrays][500];
584 private final int[] bufferlen=new int[numArrays];
585
586 public final KCountArray prefilter;
587
588 private static final int hashBits=6;
589 private static final int hashArrayLength=1<<hashBits;
590 private static final int hashCellMask=hashArrayLength-1;
591 static final long[] poison=new long[0];
592
593 private static long counter=0;
594
595 }