Debian Codegraph @

current/clump/KmerSort.java

raw symbols SCIP
1 package clump;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.HashMap;
7
8 import bloom.KCountArray;
9 import fileIO.ReadWrite;
10 import jgi.BBMerge;
11 import shared.KillSwitch;
12 import shared.Shared;
13 import shared.Timer;
14 import shared.Tools;
15 import sort.ReadComparatorID;
16 import sort.ReadComparatorName;
17 import stream.ConcurrentReadInputStream;
18 import stream.FASTQ;
19 import stream.Read;
20 import structures.ListNum;
21 import structures.Quantizer;
22 import tracker.ReadStats;
23
24 /**
25 * @author Brian Bushnell
26 * @date June 20, 2014
27 *
28 */
29 public abstract class KmerSort {
30
31 /*--------------------------------------------------------------*/
32 /*---------------- Initialization ----------------*/
33 /*--------------------------------------------------------------*/
34
35
36 /*--------------------------------------------------------------*/
37 /*---------------- Outer Methods ----------------*/
38 /*--------------------------------------------------------------*/
39
40 /** Count kmers */
41 final void preprocess(){
42 if(minCount>1){
43 if(groups>1){
44 table=ClumpTools.table();
45 assert(table!=null);
46 }else{
47 Timer ctimer=new Timer();
48 if(verbose){ctimer.start("Counting pivots.");}
49 table=ClumpTools.getTable(in1, in2, k, minCount);
50 if(verbose){ctimer.stop("Count time: ");}
51 }
52 }
53 }
54
55 /** Create read streams and process all data */
56 abstract void process(Timer t);
57
58 final void printStats(Timer t){
59 table=null;
60 ClumpTools.clearTable();
61
62 errorState|=ReadStats.writeAll();
63
64 t.stop();
65
66 String rpstring2=readsProcessed+"";
67
68 String cpstring=""+(groups==1 ? clumpsProcessedThisPass : clumpsProcessedTotal);
69 String epstring=""+correctionsTotal;
70 String efstring=""+(entryFiltered);
71 String dpstring=""+(duplicatesTotal + entryFiltered);
72
73 String rostring=""+readsOut;
74 String bostring=""+basesOut;
75
76 lastReadsIn=readsProcessed;
77 lastBasesIn=basesProcessed;
78 lastReadsOut=readsOut;
79 lastBasesOut=basesOut;
80
81 while(rpstring2.length()<12){rpstring2=" "+rpstring2;}
82 while(cpstring.length()<12){cpstring=" "+cpstring;}
83 while(epstring.length()<12){epstring=" "+epstring;}
84 while(efstring.length()<12){efstring=" "+efstring;}
85 while(dpstring.length()<12){dpstring=" "+dpstring;}
86 dpstring+=String.format("\t%.3f%%", ((duplicatesTotal + entryFiltered)*100.0)/readsProcessed);
87
88 while(rostring.length()<12){rostring=" "+rostring;}
89 while(bostring.length()<12){bostring=" "+bostring;}
90
91 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 10));
92 outstream.println();
93
94 outstream.println("Reads In: "+rpstring2);
95 outstream.println("Clumps Formed: "+cpstring);
96 if(correct){
97 outstream.println("Errors Corrected: "+epstring);
98 }
99 if(dedupe || entryfilter){
100 outstream.println("Duplicates Found: "+dpstring);
101 if(entryfilter && verbose && false){
102 outstream.println(" -Entry Filtered: "+efstring);
103 }
104 outstream.println("Reads Out: "+rostring);
105 outstream.println("Bases Out: "+bostring);
106 }
107
108 if(errorState){
109 Clumpify.sharedErrorState=true;
110 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
111 }
112 }
113
114 final ArrayList<Read> runOnePass(ArrayList<Read> reads, KmerComparator kc){
115 Timer t=new Timer();
116
117 table=null;
118 if(minCount>1){
119 if(verbose){t.start("Counting pivots.");}
120 table=ClumpTools.getTable(reads, k, minCount);
121 if(verbose){t.stop("Count time: ");}
122 }
123
124 if(verbose){t.start("Hashing.");}
125 kc.hashThreaded(reads, table, minCount);
126 if(verbose){t.stop("Hash time: ");}
127
128 if(verbose){t.start("Sorting.");}
129 Shared.sort(reads, kc);
130 if(verbose){t.stop("Sort time: ");}
131
132 if(verbose){t.start("Making clumps.");}
133 readsProcessedThisPass=reads.size();
134 ClumpList cl=new ClumpList(reads, k, false);
135 reads.clear();
136 clumpsProcessedThisPass=cl.size();
137 clumpsProcessedTotal+=clumpsProcessedThisPass;
138 if(verbose){t.stop("Clump time: ");}
139
140 if(correct){
141 if(verbose){t.start("Correcting.");}
142 reads=processClumps(cl, ClumpList.CORRECT);
143 if(verbose){t.stop("Correct time: ");}
144 }else{
145 assert(dedupe);
146 if(verbose){t.start("Deduplicating.");}
147 reads=processClumps(cl, ClumpList.DEDUPE);
148 if(verbose){t.stop("Dedupe time: ");}
149 }
150
151 return reads;
152 }
153
154 static final ArrayList<Read> nameSort(ArrayList<Read> list, boolean pair){
155 Shared.sort(list, ReadComparatorName.comparator);
156 if(!pair){return list;}
157
158 ArrayList<Read> list2=new ArrayList<Read>(1+list.size()/2);
159
160 Read prev=null;
161 for(Read r : list){
162 if(prev==null){
163 prev=r;
164 assert(prev.mate==null);
165 }else{
166 if(prev.id.equals(r.id) || FASTQ.testPairNames(prev.id, r.id, true)){
167 prev.mate=r;
168 r.mate=prev;
169 prev.setPairnum(0);
170 r.setPairnum(1);
171 list2.add(prev);
172 prev=null;
173 }else{
174 list2.add(prev);
175 prev=r;
176 }
177 }
178 }
179 return list2;
180 }
181
182 static final ArrayList<Read> idSort(ArrayList<Read> list, boolean pair){
183 Shared.sort(list, ReadComparatorID.comparator);
184 if(!pair){return list;}
185
186 ArrayList<Read> list2=new ArrayList<Read>(1+list.size()/2);
187
188 Read prev=null;
189 for(Read r : list){
190 if(prev==null){
191 prev=r;
192 assert(prev.mate==null);
193 }else{
194 if(prev.numericID==r.numericID){
195 assert(prev.pairnum()==0 && r.pairnum()==1) : prev.id+"\n"+r.id;
196 prev.mate=r;
197 r.mate=prev;
198 prev.setPairnum(0);
199 r.setPairnum(1);
200 list2.add(prev);
201 prev=null;
202 }else{
203 list2.add(prev);
204 prev=r;
205 }
206 }
207 }
208 return list2;
209 }
210
211 static final ArrayList<Read> read1Only(ArrayList<Read> list){
212 ArrayList<Read> list2=new ArrayList<Read>(1+list.size()/2);
213 for(Read r : list){
214 assert(r.mate!=null) : r+"\n"+r.mate;
215 if(r.pairnum()==0){list2.add(r);}
216 }
217 return list2;
218 }
219
220 // @Deprecated
221 // //No longer needed
222 // public int countClumps(ArrayList<Read> list){
223 // int count=0;
224 // long currentKmer=-1;
225 // for(final Read r : list){
226 // final ReadKey key=(ReadKey)r.obj;
227 // if(key.kmer!=currentKmer){
228 // currentKmer=key.kmer;
229 // count++;
230 // }
231 // }
232 // return count;
233 // }
234
235 public final ArrayList<Read> processClumps(ClumpList cl, int mode){
236 long[] rvector=KillSwitch.allocLong1D(2);
237 ArrayList<Read> out=cl.process(Shared.threads(), mode, rvector);
238 correctionsThisPass=rvector[0];
239 correctionsTotal+=correctionsThisPass;
240 duplicatesThisPass=rvector[1];
241 duplicatesTotal+=duplicatesThisPass;
242 cl.clear();
243 return out;
244 }
245
246 /*--------------------------------------------------------------*/
247 /*---------------- Inner Methods ----------------*/
248 /*--------------------------------------------------------------*/
249
250 public final void hashAndSplit(ArrayList<Read> list, KmerComparator kc, ArrayList<Read>[] array){
251 int threads=Shared.threads();
252 ArrayList<HashSplitThread> alt=new ArrayList<HashSplitThread>(threads);
253 for(int i=0; i<threads; i++){alt.add(new HashSplitThread(i, threads, list, kc));}
254 for(HashSplitThread ht : alt){ht.start();}
255
256 /* Wait for threads to die */
257 for(HashSplitThread ht : alt){
258
259 /* Wait for a thread to die */
260 while(ht.getState()!=Thread.State.TERMINATED){
261 try {
262 ht.join();
263 } catch (InterruptedException e) {
264 e.printStackTrace();
265 }
266 }
267 for(int i=0; i<groups; i++){
268 array[i].addAll(ht.array[i]);
269 ht.array[i]=null;
270 }
271 }
272 }
273
274 ArrayList<Read> fetchReads1(final ConcurrentReadInputStream cris, final KmerComparator kc){
275 Timer t=new Timer();
276 if(verbose){t.start("Making fetch threads.");}
277 final int threads=Shared.threads();
278 ArrayList<FetchThread1> alft=new ArrayList<FetchThread1>(threads);
279 for(int i=0; i<threads; i++){alft.add(new FetchThread1(i, cris, kc, unpair));}
280
281 readsThisPass=memThisPass=entryFilteredThisPass=0;
282
283 if(verbose){outstream.println("Starting threads.");}
284 for(FetchThread1 ht : alft){ht.start();}
285
286
287 if(verbose){outstream.println("Waiting for threads.");}
288 /* Wait for threads to die */
289 for(FetchThread1 ht : alft){
290
291 /* Wait for a thread to die */
292 while(ht.getState()!=Thread.State.TERMINATED){
293 try {
294 ht.join();
295 } catch (InterruptedException e) {
296 e.printStackTrace();
297 }
298 }
299 entryFilteredThisPass+=ht.entryFilteredT;
300 readsThisPass+=ht.readsProcessedT;
301 basesProcessed+=ht.basesProcessedT;
302 diskProcessed+=ht.diskProcessedT;
303 memThisPass+=ht.memProcessedT;
304 }
305 readsProcessed+=readsThisPass;
306 memProcessed+=memThisPass;
307 entryFiltered+=entryFilteredThisPass;
308
309 if(verbose){t.stop("Fetch time: ");}
310 if(verbose){System.err.println("Closing input stream.");}
311 errorState=ReadWrite.closeStream(cris)|errorState;
312
313 if(verbose){t.start("Combining thread output.");}
314 long readsLeft=readsThisPass-entryFilteredThisPass;
315 long slotsLeft=cris.paired() && !unpair ? readsLeft/2 : readsLeft;
316 assert(slotsLeft<=Shared.MAX_ARRAY_LEN) :
317 "\nThe number of reads is greater than 2 billion, which is the limit for a single group. "
318 + "\nPlease rerun and manually specify 'groups=7' or similar, "
319 + "\nsuch that the number of reads per group is less than 2 billion.";
320 ArrayList<Read> list=new ArrayList<Read>((int)(slotsLeft));
321 for(int i=0; i<threads; i++){
322 FetchThread1 ft=alft.set(i, null);
323 list.addAll(ft.storage);
324 }
325 if(verbose){t.stop("Combine time: ");}
326
327 assert(list.size()==slotsLeft) : list.size()+", "+readsThisPass+", "+readsLeft+", "+slotsLeft+", "+cris.paired();
328 //assert(list.size()==readsLeft || (cris.paired() && list.size()*2==readsLeft)) : list.size()+", "+readsThisPass+", "+readsLeft+", "+cris.paired();
329 ecco=false;
330 return list;
331 }
332
333 /*--------------------------------------------------------------*/
334 /*---------------- Inner Classes ----------------*/
335 /*--------------------------------------------------------------*/
336
337 private class FetchThread1 extends Thread{
338
339 FetchThread1(int id_, ConcurrentReadInputStream cris_, KmerComparator kc_, boolean unpair_){
340 id=id_;
341 cris=cris_;
342 kc=kc_;
343 storage=new ArrayList<Read>();
344 unpairT=unpair_;
345 entryFilterTable=(entryfilter ? new HashMap<Long, Read>() : null);
346 }
347
348 @Override
349 public void run(){
350 ListNum<Read> ln=cris.nextList();
351 final boolean paired=cris.paired();
352 ArrayList<Read> reads=(ln!=null ? ln.list : null);
353
354 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
355
356 for(Read r : reads){
357 if(!r.validated()){
358 r.validate(true);
359 if(r.mate!=null){r.mate.validate(true);}
360 }
361 readsProcessedT+=1+r.mateCount();
362 basesProcessedT+=r.length()+r.mateLength();
363 // diskProcessedT+=r.countFastqBytes()+r.countMateFastqBytes();
364 // memProcessedT+=r.countBytes()+r.countMateBytes();
365 if(shrinkName){
366 Clumpify.shrinkName(r);
367 Clumpify.shrinkName(r.mate);
368 }else if(shortName){
369 Clumpify.shortName(r);
370 Clumpify.shortName(r.mate);
371 }
372
373 if(quantizeQuality){
374 Quantizer.quantize(r, r.mate);
375 }
376 }
377
378 if(ecco){
379 for(Read r : reads){
380 Read r2=r.mate;
381 assert(r.obj==null) : "TODO: Pivot should not have been generated yet, though it may be OK.";
382 assert(r2!=null) : "ecco requires paired reads.";
383 if(r2!=null){
384 int x=BBMerge.findOverlapStrict(r, r2, true);
385 if(x>=0){
386 r.obj=null;
387 r2.obj=null;
388 }
389 }
390 }
391 }
392
393 if(entryFilterTable!=null){
394 int removed=0;
395 for(int i=0; i<reads.size(); i++){
396 Read r=reads.get(i);
397 final long key=Hasher.hashPair(r);
398 final Long key2=Long.valueOf(key);
399 final Read old=entryFilterTable.get(key2);
400 if(old==null){
401 entryFilterTable.put(key2, r);
402 }else{
403 boolean same=Hasher.equalsPaired(r, old);
404 if(same){
405 removed++;
406 entryFilteredT+=r.pairCount();
407 reads.set(i, null);
408 }
409 }
410 }
411 if(removed>0){Tools.condenseStrict(reads);}
412 }
413
414 ArrayList<Read> hashList=reads;
415 if(paired && unpairT){
416 hashList=new ArrayList<Read>(reads.size()*2);
417 for(Read r1 : reads){
418 Read r2=r1.mate;
419 assert(r2!=null);
420 hashList.add(r1);
421 hashList.add(r2);
422 if(groups>1 || !repair || namesort){
423 r1.mate=null;
424 r2.mate=null;
425 }
426 }
427 }
428
429 kc.hash(hashList, table, minCount, true);
430 storage.addAll(hashList);
431 cris.returnList(ln.id, false);
432 ln=cris.nextList();
433 reads=(ln!=null ? ln.list : null);
434 }
435 if(ln!=null){
436 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
437 }
438
439 //Optimization for TimSort
440 if(parallelSort){
441 storage.sort(kc);
442 // Shared.sort(storage, kc); //Already threaded; this is not needed.
443 }else{
444 Collections.sort(storage, kc);
445 }
446 }
447
448 final int id;
449 final ConcurrentReadInputStream cris;
450 final KmerComparator kc;
451 final ArrayList<Read> storage;
452 final boolean unpairT;
453 final HashMap<Long, Read> entryFilterTable;
454 public long entryFilteredT=0;
455
456 protected long readsProcessedT=0;
457 protected long basesProcessedT=0;
458 protected long diskProcessedT=0;
459 protected long memProcessedT=0;
460 }
461
462 /*--------------------------------------------------------------*/
463 /*---------------- Inner Classes ----------------*/
464 /*--------------------------------------------------------------*/
465
466 private final class HashSplitThread extends Thread{
467
468 @SuppressWarnings("unchecked")
469 HashSplitThread(int id_, int threads_, ArrayList<Read> list_, KmerComparator kc_){
470 id=id_;
471 threads=threads_;
472 list=list_;
473 kc=kc_;
474 array=new ArrayList[groups];
475 for(int i=0; i<groups; i++){
476 array[i]=new ArrayList<Read>();
477 }
478 }
479
480 @Override
481 public void run(){
482 for(int i=id; i<list.size(); i+=threads){
483 Read r=list.get(i);
484 kc.hash(r, null, 0, true);
485 ReadKey key=(ReadKey)r.obj;
486 array[(int)(kc.hash(key.kmer)%groups)].add(r);
487 }
488 }
489
490 final int id;
491 final int threads;
492 final ArrayList<Read> list;
493 final KmerComparator kc;
494 final ArrayList<Read>[] array;
495 }
496
497 /*--------------------------------------------------------------*/
498 /*---------------- Fields ----------------*/
499 /*--------------------------------------------------------------*/
500
501 int k=31;
502 int minCount=0;
503
504 int groups=1;
505
506 KCountArray table=null;
507
508 /*--------------------------------------------------------------*/
509 /*---------------- I/O Fields ----------------*/
510 /*--------------------------------------------------------------*/
511
512 String in1=null;
513 String in2=null;
514
515 String out1=null;
516 String out2=null;
517
518 String extin=null;
519 String extout=null;
520
521 /*--------------------------------------------------------------*/
522
523 protected long readsProcessed=0;
524 protected long basesProcessed=0;
525 protected long diskProcessed=0;
526 protected long memProcessed=0;
527 protected static long entryFiltered=0;
528
529 protected long readsOut=0;
530 protected long basesOut=0;
531
532 protected long entryFilteredThisPass=0;
533 protected long readsThisPass=0;
534 protected long memThisPass=0;
535
536 protected long readsProcessedThisPass=0;
537 protected long clumpsProcessedThisPass=0;
538 protected long correctionsThisPass=0;
539
540 protected long duplicatesThisPass=0;
541 protected static long duplicatesTotal=0;
542
543 protected long clumpsProcessedTotal=0;
544 protected static long correctionsTotal=0;
545
546 protected int passes=1;
547
548 long maxReads=-1;
549 protected boolean addName=false;
550 boolean shortName=false;
551 boolean shrinkName=false;
552 boolean rcomp=false;
553 boolean condense=false;
554 boolean correct=false;
555 boolean dedupe=false;
556 boolean splitInput=false;
557 boolean ecco=false;
558 boolean unpair=false;
559 boolean repair=false;
560 boolean namesort=false;
561 boolean entryfilter=false;
562 final boolean parallelSort=Shared.parallelSort;
563 boolean memWarned=false;
564
565 boolean useSharedHeader=false;
566 int reorderMode=REORDER_FALSE;
567
568 /*--------------------------------------------------------------*/
569
570 public static long lastReadsIn=-1;
571 public static long lastBasesIn=-1;
572 public static long lastReadsOut=-1;
573 public static long lastBasesOut=-1;
574
575 static boolean quantizeQuality=false;
576 static final int REORDER_FALSE=0, REORDER_CONSENSUS=1, REORDER_PAIRED=2, REORDER_AUTO=3;
577
578 /*--------------------------------------------------------------*/
579 /*---------------- Common Fields ----------------*/
580 /*--------------------------------------------------------------*/
581
582 PrintStream outstream=System.err;
583 public static boolean verbose=true;
584 public static boolean doHashAndSplit=true;
585 public boolean errorState=false;
586 boolean overwrite=true;
587 boolean append=false;
588
589 }