Debian Codegraph @

current/clump/KmerComparator.java

raw symbols SCIP
1 package clump;
2
3 import java.util.ArrayList;
4 import java.util.Arrays;
5 import java.util.Comparator;
6
7 import bloom.KCountArray;
8 import dna.AminoAcid;
9 import jgi.BBMerge;
10 import shared.Shared;
11 import shared.Tools;
12 import sketch.SketchTool;
13 import stream.Read;
14
15 /**
16 * @author Brian Bushnell
17 * @date Nov 4, 2015
18 *
19 */
20 public class KmerComparator implements Comparator<Read> {
21
22 public KmerComparator(int k_, boolean addName_, boolean rcomp_){
23 this(k_, defaultSeed, defaultBorder, defaultHashes, addName_, rcomp_);
24 }
25
26 public KmerComparator(int k_, long seed_, int border_, int hashes_, boolean addName_, boolean rcomp_){
27 k=k_;
28 assert(k>0 && k<32);
29
30 shift=2*k;
31 shift2=shift-2;
32 mask=(shift>63 ? -1L : ~((-1L)<<shift));
33 seed=seed_;
34 border=Tools.max(0, border_);
35 hashes=Tools.mid(0, hashes_, 8);
36 codes=SketchTool.makeCodes(8, 256, seed_, true);
37 if(verbose){
38 System.err.println("Made a comparator with k="+k+", seed="+seed+", border="+border+", hashes="+hashes);
39 }
40 addName=addName_;
41 rcompReads=rcomp_;
42 }
43
44 public void hashThreaded(ArrayList<Read> list, KCountArray table, int minCount){
45 int threads=Shared.threads();
46 ArrayList<HashThread> alt=new ArrayList<HashThread>(threads);
47 for(int i=0; i<threads; i++){alt.add(new HashThread(i, threads, list, table, minCount));}
48 for(HashThread ht : alt){ht.start();}
49
50 /* Wait for threads to die */
51 for(HashThread ht : alt){
52
53 /* Wait for a thread to die */
54 while(ht.getState()!=Thread.State.TERMINATED){
55 try {
56 ht.join();
57 } catch (InterruptedException e) {
58 e.printStackTrace();
59 }
60 }
61 }
62 }
63
64 public void hash(ArrayList<Read> list, KCountArray table, int minCount, boolean setObject) {
65 for(Read r : list){hash(r, table, minCount, setObject);}
66 }
67
68 public long hash(Read r1, KCountArray table, int minCount, boolean setObject){
69 long x=hash_inner(r1, table, minCount, setObject);
70 if(Clump.containment && r1.mate!=null){hash_inner(r1.mate, table, minCount, setObject);}
71 return x;
72 }
73
74 private long hash_inner(Read r1, KCountArray table, int minCount, boolean setObject){
75 ReadKey key;
76 if(setObject){
77 if(r1.obj==null){
78 key=ReadKey.makeKey(r1, true);
79 }else{
80 key=(ReadKey)r1.obj;
81 key.clear();
82 }
83 }else{
84 key=getLocalKey();
85 }
86 assert(key.kmer==key.position && key.position==0);
87 return fillMax(r1, key, table, minCount);
88 }
89
90 // public void fuse(Read r1){
91 // Read r2=r1.mate;
92 // if(r2==null){return;}
93 // r1.mate=null;
94 // final int len1=r1.length(), len2=r2.length();
95 // int len=len1+len2+1;
96 // byte[] bases=new byte[len];
97 // for(int i=0; i<len1; i++){bases[i]=r1.bases[i];}
98 // bases[len1]='N';
99 // for(int i=0, j=len1+1; i<len2; i++){bases[j]=r2.bases[i];}
100 // }
101
102 /* (non-Javadoc)
103 * @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
104 */
105 @Override
106 public int compare(Read a, Read b) {
107 final ReadKey keyA, keyB;
108 if(a.obj==null){
109 keyA=ReadKey.makeKey(a, true);
110 fillMax(a, keyA, null, 0);
111 }else{keyA=(ReadKey)a.obj;}
112
113 if(b.obj==null){
114 keyB=ReadKey.makeKey(b, true);
115 fillMax(b, keyB, null, 0);
116 }else{keyB=(ReadKey)b.obj;}
117
118 int x=keyA.compareTo(keyB);
119 if(x==0 && compareSequence){
120 x=KmerComparator2.compareSequence(a, b, 0);
121 }
122 if(x==0){
123 float ea=a.expectedErrorsIncludingMate(true);
124 float eb=b.expectedErrorsIncludingMate(true);
125 if(ea!=eb){return ea>eb ? -1 : 1;}
126 }
127 return x==0 ? a.id.compareTo(b.id) : x;
128 }
129
130 /** Finds the global maximum */
131 public long fillMax(Read r, ReadKey key, KCountArray table, int minCount){
132 if(mergeFirst && r.pairnum()==0 && r.mate!=null){//This is probably unsafe in multithreaded mode unless the same thread handles both reads.
133 int x=BBMerge.findOverlapStrict(r, r.mate, false);
134 if(x>0){
135 if(r.swapped()==r.mate.swapped()){r.mate.reverseComplement();}
136 Read merged=r.joinRead(x);
137 if(r.swapped()==r.mate.swapped()){r.mate.reverseComplement();}
138 fillMax(merged, key, table, minCount);
139 if(key.flipped){
140 r.reverseComplement();
141 r.setSwapped(true);
142 }
143 return key.kmer;
144 }
145 }
146 if(r.length()<k){return fillShort(r, key);}
147 assert(minCount>0 || table==null) : minCount;
148 assert(table==null || minCount<=table.maxValue) : minCount;
149
150 key.set(0, k-1, false); //TODO: Why is this k-1 rather than 0?
151 final byte[] bases=r.bases, quals=r.quality;
152 long kmer=0;
153 long rkmer=0;
154 int len=0;
155 float prob=1;
156
157 if(bases==null || bases.length<k){return -1;}
158
159 long topCode=Long.MIN_VALUE;
160 int topCount=-2;
161 float topProb=0;
162 final int localBorder=(bases.length>k+4*border ? border : 0);
163
164 final int max=bases.length-localBorder;
165 for(int i=localBorder; i<max; i++){
166 byte b=bases[i];
167 long x=AminoAcid.baseToNumber[b];
168 long x2=AminoAcid.baseToComplementNumber[b];
169 kmer=((kmer<<2)|x)&mask;
170 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
171
172 if(minProb>0 && quals!=null){//Update probability
173 prob=prob*PROB_CORRECT[quals[i]];
174 if(len>k){
175 byte oldq=quals[i-k];
176 prob=prob*PROB_CORRECT_INVERSE[oldq];
177 }
178 }
179
180 if(x<0){
181 len=0;
182 prob=1;
183 }else{len++;}
184
185 if(len>=k){
186 final long kmax=Tools.max(kmer, rkmer);
187 final long code=hash(kmax);
188 boolean accept=false;
189 int count=0;
190 if(table!=null){
191 assert(minCount>=1);
192 if(code>topCode){
193 count=table.read(kmax);
194 accept=(count>=minCount || topCount<minCount);
195 }else if(topCount<minCount){
196 count=table.read(kmax);
197 accept=count>=minCount;
198 }
199 }else{
200 if(code>topCode){
201 accept=(prob>=minProb || topProb<minProb);
202 }else{
203 accept=(prob>=minProb && topProb<minProb);
204 }
205 }
206
207 if(accept){
208 topCode=code;
209 topCount=count;
210 topProb=minProb;
211 key.set(kmax, i, (kmax!=kmer));
212 }
213 }
214 }
215 if(topCode==Long.MIN_VALUE){
216 return fillShort(r, key);
217 }
218 // if(bases.length<k){
219 // final long kmax=Tools.max(kmer, rkmer);
220 // key.set(kmax, bases.length-1, (kmax!=kmer));
221 // }
222
223 // assert(minCount<2) : minCount+", "+topCode+", "+topCount;
224 // assert(minCount>0) : minCount+", "+topCode+", "+topCount;
225
226 // if(topCode<0 && minCount>1){//Not needed
227 // return fillMax(r, kmers, null, 0);
228 // }
229
230 // r.id+=" "+key.position+","+rcomp+","+(bases.length-key.position+k-2);
231 if(key.kmerMinusStrand && rcompReads){
232 key.flip(r, k);
233 }
234 // if(shortName){//This actually takes a lot of time!
235 // r.id=r.numericID+" 1:"+(rcomp ? "t" : "f");
236 // if(r.mate!=null){
237 // r.mate.id=r.numericID+" 2:f";
238 // }
239 // }else
240 if(addName){r.id+=" "+key;}
241
242 assert(key.kmer>=0 && key.position>=0) : key+"\n"+r;
243 return key.kmer;
244 }
245
246
247
248 /* For teaching */
249 /** Finds the global maximum, forward only */
250 public long example1(Read r){
251 //Handle degenerate reads shorter than kmer length
252 if(r.length()<k){return fillShort(r, null);}
253
254 final byte[] bases=r.bases;
255 long kmer=0;//Stores the current kmer being built and analyzed
256 int len=0;//Length bases since last N encountered
257
258 long topCode=Long.MIN_VALUE;//Maximal hash code encountered
259 long topKmer=Long.MIN_VALUE;//Kmer for maximal hash code
260
261 for(int i=0; i<bases.length; i++){
262 byte b=bases[i];//The base, A, C, G, T, or N
263 long x=AminoAcid.baseToNumber[b];//2-bit value, 0, 1, 2, 3, or -1
264 kmer=((kmer<<2)|x)&mask;//Shift the new 2 bits into the kmer
265
266 if(x<0){//If an N is encountered, reset the length
267 len=0;
268 }else{len++;}
269
270 if(len>=k){//If the kmer is valid and full length, hash it
271 final long code=hash(kmer);//Some arbitrary hash function
272
273 if(code>topCode){//If this is a new maximum, retain it
274 topKmer=kmer;
275 topCode=code;
276 }
277 }
278 }
279
280 //If for whatever reason it failed (e.g., Ns), use the short method
281 if(topCode==Long.MIN_VALUE){return fillShort(r, null);}
282
283 //Return the pivot kmer.
284 //It's also useful to store (and return) the position and orientation.
285 return topKmer;
286 }
287
288 /* For teaching */
289 /** Finds the global maximum, forward and reverse */
290 public long example2(Read r){
291 if(r.length()<k){return fillShort(r, null);}
292
293 final byte[] bases=r.bases;
294 long kmer=0;
295 long rkmer=0;
296 int len=0;
297
298 if(bases==null || bases.length<k){return -1;}
299
300 long topCode=Long.MIN_VALUE;
301 long topKmer=Long.MIN_VALUE;
302
303 for(int i=0; i<bases.length; i++){
304 byte b=bases[i];
305 long x=AminoAcid.baseToNumber[b];
306 long x2=AminoAcid.baseToComplementNumber[b];
307 kmer=((kmer<<2)|x)&mask;
308 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
309
310 if(x<0){
311 len=0;
312 }else{len++;}
313
314 if(len>=k){
315 final long kmax=Tools.max(kmer, rkmer);
316 final long code=hash(kmax);
317
318 if(code>topCode){
319 topKmer=kmax;
320 topCode=code;
321 }
322 }
323 }
324 if(topCode==Long.MIN_VALUE){
325 return fillShort(r, null);
326 }
327
328 return topKmer;
329 }
330
331 /* For teaching */
332 /** Finds the global maximum, forward and reverse, with qualities and border */
333 public long example3(Read r){
334 if(r.length()<k){return fillShort(r, null);}
335
336 final byte[] bases=r.bases, quals=r.quality;
337 long kmer=0;
338 long rkmer=0;
339 int len=0;
340 float prob=1;
341
342 if(bases==null || bases.length<k){return -1;}
343
344 long topCode=Long.MIN_VALUE;
345 long topKmer=Long.MIN_VALUE;
346 float topProb=0;
347 final int localBorder=(bases.length>k+4*border ? border : 0);
348
349 final int max=bases.length-localBorder;
350 for(int i=localBorder; i<max; i++){
351 byte b=bases[i];
352 long x=AminoAcid.baseToNumber[b];
353 long x2=AminoAcid.baseToComplementNumber[b];
354 kmer=((kmer<<2)|x)&mask;
355 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
356
357 if(minProb>0 && quals!=null){//Update probability
358 prob=prob*PROB_CORRECT[quals[i]];
359 if(len>k){
360 byte oldq=quals[i-k];
361 prob=prob*PROB_CORRECT_INVERSE[oldq];
362 }
363 }
364
365 if(x<0){
366 len=0;
367 prob=1;
368 }else{len++;}
369
370 if(len>=k){
371 final long kmax=Tools.max(kmer, rkmer);
372 final long code=hash(kmax);
373 boolean accept=false;
374
375 if(code>topCode){
376 accept=(prob>=minProb || topProb<minProb);
377 }else{
378 accept=(prob>=minProb && topProb<minProb);
379 }
380
381 if(accept){
382 topKmer=kmax;
383 topCode=code;
384 topProb=minProb;
385 }
386 }
387 }
388 if(topCode==Long.MIN_VALUE){
389 return fillShort(r, null);
390 }
391
392 return topKmer;
393 }
394
395 /** Generates a key when the read is shorter than k */
396 public long fillShort(Read r, ReadKey key){
397 final byte[] bases=r.bases;
398 final int max=Tools.min(bases.length, k);
399 key.set(0, max-1, false);
400 long kmer=0;
401 long rkmer=0;
402
403 for(int i=0; i<max; i++){
404 byte b=bases[i];
405 long x=AminoAcid.baseToNumber0[b];
406 long x2=AminoAcid.baseToComplementNumber0[b];
407 kmer=((kmer<<2)|x)&mask;
408 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
409 }
410
411 final long kmax=Tools.max(kmer, rkmer);
412 key.set(kmax, max-1, (kmax!=kmer));
413
414 if(key.kmerMinusStrand && rcompReads){
415 key.flip(r, k);
416 }
417 if(addName){r.id+=" "+key;}
418
419 return key.kmer;
420 }
421
422 public static synchronized void setHashes(int x){
423 defaultHashes=Tools.mid(0, x, 8);
424 }
425
426 //TODO: This can be swapped with BBSketch hashing code. Check speed.
427 public final long hash(long kmer){
428 long code=kmer;
429 for(int i=0; i<hashes; i++){//4 only half-hashes; 8 does full hashing
430 int x=(int)(kmer&0xFF);
431 kmer>>=8;
432 code^=codes[i][x];
433 }
434 return code&Long.MAX_VALUE;
435 }
436
437 private class HashThread extends Thread{
438
439 HashThread(int id_, int threads_, ArrayList<Read> list_, KCountArray table_, int minCount_){
440 id=id_;
441 threads=threads_;
442 list=list_;
443 table=table_;
444 minCount=minCount_;
445 }
446
447 @Override
448 public void run(){
449 for(int i=id; i<list.size(); i+=threads){
450 hash(list.get(i), table, minCount, true);
451 }
452 }
453
454 final int id;
455 final int threads;
456 final ArrayList<Read> list;
457 final KCountArray table;
458 final int minCount;
459 }
460
461 static ReadKey getLocalKey(){
462 ReadKey key=localReadKey.get();
463 if(key==null){
464 localReadKey.set(key=new ReadKey());
465 }
466 key.clear();
467 return key;
468 }
469
470 public final int k;
471
472 final int shift;
473 final int shift2;
474 final long mask;
475
476 final long seed;
477 final int border;
478 final int hashes;
479
480 final boolean addName;
481 final boolean rcompReads;
482
483 private final long[][] codes;
484
485 static long defaultSeed=1;
486 static int defaultHashes=4;
487 static int defaultBorder=1;
488 public static float minProb=0f;
489 public static boolean verbose=true;
490
491 public static boolean mergeFirst=false;
492 public static boolean compareSequence=true;
493
494 public static ThreadLocal<ReadKey> localReadKey=new ThreadLocal<ReadKey>();
495
496 public static final float[] PROB_CORRECT=Arrays.copyOf(align2.QualityTools.PROB_CORRECT, 127);
497 public static final float[] PROB_CORRECT_INVERSE=Arrays.copyOf(align2.QualityTools.PROB_CORRECT_INVERSE, 127);
498
499 }