Debian Codegraph @

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