Debian Codegraph @

current/cardinality/CardinalityTracker.java

raw symbols SCIP
1 package cardinality;
2
3 import java.util.Arrays;
4 import java.util.Random;
5
6 import dna.AminoAcid;
7 import fileIO.ByteStreamWriter;
8 import jgi.Dedupe;
9 import shared.Parser;
10 import shared.Shared;
11 import shared.Tools;
12 import stream.Read;
13 import structures.LongList;
14 import structures.SuperLongList;
15 import ukmer.Kmer;
16
17 /**
18 * Abstract superclass for cardinality-tracking structures like LogLog.
19 * @author Brian Bushnell
20 * @date Feb 20, 2020
21 *
22 */
23 public abstract class CardinalityTracker {
24
25 /*--------------------------------------------------------------*/
26 /*---------------- Initialization ----------------*/
27 /*--------------------------------------------------------------*/
28
29 /**
30 * Factory method; creates a tracker using default settings.
31 * Subclass is determined by static Parser.loglogType field.
32 */
33 public static CardinalityTracker makeTracker(){
34 if(trackCounts || "BBLog".equalsIgnoreCase(Parser.loglogType)){
35 return new BBLog();//Fastest, most accurate
36 }else if("LogLog".equalsIgnoreCase(Parser.loglogType)){
37 return new LogLog();//Least accurate
38 }else if("LogLog2".equalsIgnoreCase(Parser.loglogType)){
39 return new LogLog2();//Slowest, uses mantissa
40 }else if("LogLog16".equalsIgnoreCase(Parser.loglogType)){
41 return new LogLog16();//Uses 10-bit mantissa
42 }else if("LogLog8".equalsIgnoreCase(Parser.loglogType)){
43 return new LogLog8();//Lowest memory
44 }
45 assert(false) : "TODO: "+Parser.loglogType;
46 throw new RuntimeException(Parser.loglogType);
47 }
48
49 /**
50 * Factory method; creates a tracker using parsed settings.
51 * Subclass is determined by static Parser.loglogType field.
52 */
53 public static CardinalityTracker makeTracker(Parser p){
54 if(trackCounts || "BBLog".equalsIgnoreCase(Parser.loglogType)){
55 return new BBLog(p);
56 }else if("LogLog".equalsIgnoreCase(Parser.loglogType)){
57 return new LogLog(p);
58 }else if("LogLog2".equalsIgnoreCase(Parser.loglogType)){
59 return new LogLog2(p);
60 }else if("LogLog16".equalsIgnoreCase(Parser.loglogType)){
61 return new LogLog16(p);
62 }else if("LogLog8".equalsIgnoreCase(Parser.loglogType)){
63 return new LogLog8(p);
64 }
65 assert(false) : "TODO: "+Parser.loglogType;
66 throw new RuntimeException(Parser.loglogType);
67 }
68
69 /**
70 * Factory method; creates a tracker using specified settings.
71 * Subclass is determined by static Parser.loglogType field.
72 */
73 public static CardinalityTracker makeTracker(int buckets_, int k_, long seed, float minProb_){
74 if(trackCounts || "BBLog".equalsIgnoreCase(Parser.loglogType)){
75 return new BBLog(buckets_, k_, seed, minProb_);
76 }else if("LogLog".equalsIgnoreCase(Parser.loglogType)){
77 return new LogLog(buckets_, k_, seed, minProb_);
78 }else if("LogLog2".equalsIgnoreCase(Parser.loglogType)){
79 return new LogLog2(buckets_, k_, seed, minProb_);
80 }else if("LogLog16".equalsIgnoreCase(Parser.loglogType)){
81 return new LogLog16(buckets_, k_, seed, minProb_);
82 }else if("LogLog8".equalsIgnoreCase(Parser.loglogType)){
83 return new LogLog8(buckets_, k_, seed, minProb_);
84 }
85 assert(false) : "TODO: "+Parser.loglogType;
86 throw new RuntimeException(Parser.loglogType);
87 }
88
89 /*--------------------------------------------------------------*/
90 /*---------------- Constructors ----------------*/
91 /*--------------------------------------------------------------*/
92
93 /** Create a tracker with parsed parameters. */
94 public CardinalityTracker(Parser p){
95 this(p.loglogbuckets, p.loglogk, p.loglogseed, p.loglogMinprob);
96 }
97
98 /**
99 * Create a tracker with specified parameters.
100 * @param buckets_ Number of buckets (counters)
101 * @param k_ Kmer length
102 * @param seed Random number generator seed; -1 for a random seed
103 * @param minProb_ Ignore kmers with under this probability of being correct
104 */
105 public CardinalityTracker(int buckets_, int k_, long seed, float minProb_){
106 // if((buckets_&1)==0){buckets_=(int)Primes.primeAtLeast(buckets_);} //Legacy code, needed modulo operation
107 buckets=powerOf2AtLeast(buckets_);
108 assert(buckets>0 && Integer.bitCount(buckets)==1) : "Buckets must be a power of 2: "+buckets;
109 bucketMask=buckets-1;
110 k=Kmer.getKbig(k_);
111 minProb=minProb_;
112
113 //For old hash function
114 // tables=new long[numTables][][];
115 // for(int i=0; i<numTables; i++){
116 // tables[i]=makeCodes(steps, bits, (seed<0 ? -1 : seed+i));
117 // }
118
119 Random randy=Shared.threadLocalRandom(seed<0 ? -1 : seed);
120 hashXor=randy.nextLong();
121 }
122
123 /**
124 * Return the lowest power of 2 that is >= target.
125 * Provided because buckets must currently be a power of 2.
126 */
127 public static final int powerOf2AtLeast(int target){
128 if(target<1){return 1;}
129 int ret=1, limit=Tools.min(target, 0x40000000);
130 while(ret<limit){ret<<=1;}
131 return ret;
132 }
133
134 /*--------------------------------------------------------------*/
135 /*---------------- Methods ----------------*/
136 /*--------------------------------------------------------------*/
137
138 /** Deprecated; use LogLogWrapper */
139 public static final void main(String[] args){
140 LogLogWrapper llw=new LogLogWrapper(args);
141
142 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
143 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
144
145 llw.process();
146
147 Read.VALIDATE_IN_CONSTRUCTOR=vic;
148 }
149
150 /**
151 * Old table-based hash function.
152 * Slower than the new function.
153 */
154 public final long hash(final long value0, final long[][] table){
155 long value=value0, code=0;
156 long mask=(bits>63 ? -1L : ~((-1L)<<bits));
157
158 for(int i=0; i<steps; i++){//I could also do while value!=0
159 int x=(int)(value&mask);
160 value>>=bits;
161 code=code^table[i][x];
162 }
163 return code;
164 }
165
166 /** Hash and add a number to this tracker */
167 public final void add(long number){
168 hashAndStore(number);
169 }
170
171 /**
172 * Hash and track the Read
173 * */
174 public final void hash(Read r){
175 if(r==null){return;}
176 if(r.length()>=k){hash(r.bases, r.quality);}
177 if(r.mateLength()>=k){hash(r.mate.bases, r.mate.quality);}
178 }
179
180 /**
181 * Hash and track the sequence
182 * */
183 public final void hash(byte[] bases, byte[] quals){
184 if(k<32){hashSmall(bases, quals);}
185 else{hashBig(bases, quals);}
186 }
187
188 /**
189 * Hash and track the sequence using short kmers 0<k<32
190 * */
191 public final void hashSmall(byte[] bases, byte[] quals){
192 final int shift=2*k;
193 final int shift2=shift-2;
194 final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
195 int len=0;
196
197 long kmer=0, rkmer=0;
198
199 if(minProb>0 && quals!=null){//Debranched loop
200 assert(quals.length==bases.length) : quals.length+", "+bases.length;
201 float prob=1;
202 for(int i=0; i<bases.length; i++){
203 byte b=bases[i];
204 long x=AminoAcid.baseToNumber[b];
205 long x2=AminoAcid.baseToComplementNumber[b];
206 kmer=((kmer<<2)|x)&mask;
207 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
208
209 {//Update probability
210 byte q=quals[i];
211 prob=prob*PROB_CORRECT[q];
212 if(len>k){
213 byte oldq=quals[i-k];
214 prob=prob*PROB_CORRECT_INVERSE[oldq];
215 }
216 }
217 if(x>=0){
218 len++;
219 }else{
220 len=0;
221 kmer=rkmer=0;
222 prob=1;
223 }
224 if(len>=k && prob>=minProb){
225 add(Tools.max(kmer, rkmer));
226 }
227 }
228 }else{
229
230 for(int i=0; i<bases.length; i++){
231 byte b=bases[i];
232 long x=AminoAcid.baseToNumber[b];
233 long x2=AminoAcid.baseToComplementNumber[b];
234 kmer=((kmer<<2)|x)&mask;
235 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
236
237 if(x>=0){
238 len++;
239 }else{
240 len=0;
241 kmer=rkmer=0;
242 }
243 if(len>=k){
244 add(Tools.max(kmer, rkmer));
245 }
246 }
247 }
248 }
249
250 /**
251 * Hash and track the sequence using long kmers >31
252 * */
253 public final void hashBig(byte[] bases, byte[] quals){
254
255 Kmer kmer=getLocalKmer();
256 int len=0;
257 float prob=1;
258
259 for(int i=0; i<bases.length; i++){
260 byte b=bases[i];
261 long x=Dedupe.baseToNumber[b];
262 kmer.addRightNumeric(x);
263 if(minProb>0 && quals!=null){//Update probability
264 prob=prob*PROB_CORRECT[quals[i]];
265 if(len>k){
266 byte oldq=quals[i-k];
267 prob=prob*PROB_CORRECT_INVERSE[oldq];
268 }
269 }
270 if(AminoAcid.isFullyDefined(b)){
271 len++;
272 }else{
273 len=0;
274 prob=1;
275 }
276 if(len>=k && prob>=minProb){
277 add(kmer.xor());
278 }
279 }
280 }
281
282 /**
283 * Make a table of random bitmasks for hashing.
284 * Superceded by new hash method.
285 * */
286 private static final long[][] makeCodes(int length, int bits, long seed){
287 if(true) {return null;}//Short circuit
288 Random randy=Shared.threadLocalRandom(seed);
289 int modes=1<<bits;
290 long[][] r=new long[length][modes];
291 for(int i=0; i<length; i++){
292 for(int j=0; j<modes; j++){
293 long x=randy.nextLong();
294 while(Long.bitCount(x)>33){
295 x&=(~(1L<<randy.nextInt(64)));
296 }
297 while(Long.bitCount(x)<31){
298 x|=(1L<<randy.nextInt(64));
299 }
300 r[i][j]=x;
301
302 }
303 }
304 return r;
305 }
306
307 public final float compensationFactorBuckets(){
308 assert(Integer.bitCount(buckets)==1) : buckets;
309 int zeros=Integer.numberOfTrailingZeros(buckets);
310 return compensationFactorLogBuckets(zeros);
311 }
312
313 /**
314 * Multiplier to compensate for overestimating genome size
315 * when the number of buckets is too small,
316 * as a function of log2(buckets)
317 * @param logBuckets
318 * @return Multiplier for final estimate
319 */
320 public final float compensationFactorLogBuckets(int logBuckets){
321 float[] array=compensationFactorLogBucketsArray();
322 return (array!=null && logBuckets<array.length) ? array[logBuckets] : 1/(1+(1<<logBuckets));
323 }
324
325 public SuperLongList toFrequency(){
326 SuperLongList list=new SuperLongList(1000);
327 int[] counts=getCounts();
328 for(int x : counts){
329 if(x>0){list.add(x);}
330 }
331 list.sort();
332 return list;
333 }
334
335 /**
336 * Print a kmer frequency histogram.
337 * @param path File to which to print
338 * @param overwrite
339 * @param append
340 * @param supersample Adjust counts for the effect of subsampling
341 */
342 public void printKhist(String path, boolean overwrite, boolean append, boolean supersample, int decimals){
343 SuperLongList sll=toFrequency();
344 ByteStreamWriter bsw=new ByteStreamWriter(path, overwrite, append, false);
345 bsw.start();
346 bsw.print("#Depth\tCount\n");
347 final double mult=Tools.max(1.0, (supersample ? cardinality()/(double)buckets : 1));
348 final long[] array=sll.array();
349 final LongList list=sll.list();
350
351 for(int depth=0; depth<array.length; depth++){
352 long count=array[depth];
353 if(count>0){
354 bsw.print(depth).tab();
355 if(supersample){
356 if(decimals>0){
357 bsw.print(count*mult, decimals).nl();
358 }else{
359 bsw.print(Tools.max(1, Math.round(count*mult))).nl();
360 }
361 }else{
362 bsw.print(count).nl();
363 }
364 }
365 }
366 int count=0;
367 long prevDepth=-1;
368 for(int i=0; i<list.size; i++){
369 long depth=list.get(i);
370 if(depth!=prevDepth && count>0){
371 assert(depth>prevDepth);
372 bsw.print(prevDepth).tab();
373 if(supersample){
374 if(decimals>0){
375 bsw.print(count*mult, decimals).nl();
376 }else{
377 bsw.print(Tools.max(1, Math.round(count*mult))).nl();
378 }
379 }else{
380 bsw.print(count).nl();
381 }
382 count=0;
383 }else{
384 count++;
385 }
386 prevDepth=depth;
387 }
388 if(count>0){
389 bsw.print(prevDepth).tab();
390 if(supersample){
391 if(decimals>0){
392 bsw.print(count*mult, decimals).nl();
393 }else{
394 bsw.print(Tools.max(1, Math.round(count*mult))).nl();
395 }
396 }else{
397 bsw.print(count).nl();
398 }
399 }
400 bsw.poisonAndWait();
401 }
402
403 /** Sum of counts array, if present */
404 public final long countSum(){
405 int[] counts=getCounts();
406 return counts==null ? 0 : shared.Vector.sum(counts);
407 }
408
409 /*--------------------------------------------------------------*/
410 /*---------------- Abstract Methods ----------------*/
411 /*--------------------------------------------------------------*/
412
413 /*--------------------------------------------------------------*/
414 /*---------------- Abstract Methods ----------------*/
415 /*--------------------------------------------------------------*/
416
417 /** Calculate cardinality estimate from this tracker */
418 public abstract long cardinality();
419
420 /** Counts array, if present.
421 * Should be overridden for classes that track counts. */
422 public int[] getCounts(){
423 return null;
424 }
425
426 /** Add another tracker to this one */
427 public abstract void add(CardinalityTracker log);
428
429 /** Generate a 64-bit hashcode from a number, and add it to this tracker */
430 public abstract void hashAndStore(final long number);
431
432 /** TODO: Deprecate?
433 * Designed to compensate for overestimate with small numbers of buckets.
434 * Appears to be handled by using the harmonic mean in the case of multiple trials. */
435 public abstract float[] compensationFactorLogBucketsArray();
436
437 /*--------------------------------------------------------------*/
438 /*---------------- Fields ----------------*/
439 /*--------------------------------------------------------------*/
440
441 /** Kmer length */
442 public final int k;
443
444 /** Ignore kmers under this probability of correctness */
445 public final float minProb;
446
447 /**
448 * Number of buckets for tracking.
449 * Must be a power of 2.
450 * Larger is slower and uses more memory, but more accurate.
451 */
452 public final int buckets;
453
454 /** Mask for lower bits of hashcode to yield bucket; bucketMask==buckets-1. */
455 final int bucketMask;
456
457 /** Reusable kmer for hashing. */
458 private final ThreadLocal<Kmer> localKmer=new ThreadLocal<Kmer>();
459
460 /** The hash function will yield a different mapping for each mask here. */
461 private final long hashXor;
462
463 /** For long kmer mode */
464 protected Kmer getLocalKmer(){
465 Kmer kmer=localKmer.get();
466 if(kmer==null){
467 localKmer.set(new Kmer(k));
468 kmer=localKmer.get();
469 }
470 kmer.clearFast();
471 return kmer;
472 }
473
474 /*--------------------------------------------------------------*/
475 /*---------------- Deprecated Table Fields ----------------*/
476 /*--------------------------------------------------------------*/
477
478 static final int numTables=4;
479 static final int numTablesMask=numTables-1;
480 /** Bits hashed per cycle; no longer needed */
481 private static final int bits=8;
482 private static final int steps=(63+bits)/bits;;
483 // final long[][][] tables;
484
485 /*--------------------------------------------------------------*/
486 /*---------------- Statics ----------------*/
487 /*--------------------------------------------------------------*/
488
489 /** Converts quality score to probability of correctness */
490 public static final float[] PROB_CORRECT=Arrays.copyOf(align2.QualityTools.PROB_CORRECT, 128);
491 /** Inverse of PROB_CORRECT */
492 public static final float[] PROB_CORRECT_INVERSE=Arrays.copyOf(align2.QualityTools.PROB_CORRECT_INVERSE, 128);
493
494 /** Atomic mode allows less memory when multithreaded, but lower peak concurrency due to contention. */
495 public static final boolean atomic=false;//non-atomic is faster.
496 /** Track number of times the value in each bucket was seen. */
497 public static boolean trackCounts=false;
498 /** Ignores kmers such that x%SKIPMOD!=0, to skip expensive hash and store functions */
499 static final long SKIPMOD=1;//No longer used; requires a modulo operation
500 /** Records the last cardinality tracked, for use in static contexts (RQCFilter) */
501 public static long lastCardinality=-1;
502 // /** Ignore hashed values above this, to skip expensive read and store functions. */
503 // static final long maxHashedValue=((-1L)>>>3);//No longer used
504
505 /** These determine how to combine multiple buckets to yield a value.
506 * Mean is best even though mwa is pretty close. Median is much worse. */
507 public static boolean USE_MEAN=true;//Arithmetic mean
508 public static boolean USE_MEDIAN=false;
509 public static boolean USE_MWA=false;//Median-weighted-average
510 public static boolean USE_HMEAN=false;//Harmonic mean
511 public static boolean USE_GMEAN=false;//Geometric mean
512
513 }