Debian Codegraph @

current/hiseq/PlotFlowCell.java

raw symbols SCIP
1 package hiseq;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.concurrent.locks.ReadWriteLock;
7 import java.util.concurrent.locks.ReentrantReadWriteLock;
8
9 import aligner.MicroAligner3;
10 import aligner.MicroIndex3;
11 import barcode.BarcodeStats;
12 import bloom.BloomFilter;
13 import bloom.BloomFilterCorrector;
14 import bloom.KmerCountAbstract;
15 import dna.AminoAcid;
16 import dna.Data;
17 import fileIO.ByteFile;
18 import fileIO.FileFormat;
19 import fileIO.ReadWrite;
20 import jgi.Dedupe;
21 import kmer.AbstractKmerTable;
22 import kmer.HashArray1D;
23 import kmer.ScheduleMaker;
24 import shared.Parse;
25 import shared.Parser;
26 import shared.PreParser;
27 import shared.Shared;
28 import shared.Timer;
29 import shared.Tools;
30 import stream.ConcurrentReadInputStream;
31 import stream.FASTQ;
32 import stream.FastaReadInputStream;
33 import stream.Read;
34 import structures.IntList;
35 import structures.ListNum;
36 import structures.LongList;
37 import template.Accumulator;
38 import template.ThreadWaiter;
39
40 //Example command: plotflowcell.sh in=lane1.fq.gz size=999999 dump=dump.txt expected=expected.txt bloom multithreaded -Xmx40g
41
42 /**
43 * Analyzes a flow cell for low-quality areas.
44 * Removes reads in the low-quality areas.
45 *
46 * @author Brian Bushnell
47 * @date August 31, 2016
48 *
49 */
50 public class PlotFlowCell implements Accumulator<PlotFlowCell.WorkerThread> {
51
52 /*--------------------------------------------------------------*/
53 /*---------------- Initialization ----------------*/
54 /*--------------------------------------------------------------*/
55
56 /**
57 * Code entrance from the command line.
58 * @param args Command line arguments
59 */
60 public static void main(String[] args){
61 Timer t=new Timer();
62 PlotFlowCell x=new PlotFlowCell(args);
63 x.process(t);
64
65 //Close the print stream if it was redirected
66 Shared.closeStream(x.outstream);
67 }
68
69 /**
70 * Constructor.
71 * @param args Command line arguments
72 */
73 public PlotFlowCell(String[] args){
74
75 {//Preparse block for help, config files, and outstream
76 PreParser pp=new PreParser(args, getClass(), false);
77 args=pp.args;
78 outstream=pp.outstream;
79 }
80
81 //Set shared static variables
82 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
83 ReadWrite.setZipThreads(Shared.threads());
84
85 //Create a parser object
86 Parser parser=new Parser();
87 boolean setInterleaved=false; //Whether interleaved was explicitly set.
88
89 //Parse each argument
90 for(int i=0; i<args.length; i++){
91 String arg=args[i];
92
93 //Break arguments into their constituent parts, in the form of "a=b"
94 String[] split=arg.split("=");
95 String a=split[0].toLowerCase();
96 String b=split.length>1 ? split[1] : null;
97
98 if(a.equals("verbose")){
99 verbose=Parse.parseBoolean(b);
100 }else if(a.equals("divisor") || a.equals("size")){
101 Tile.xSize=Tile.ySize=Parse.parseIntKMG(b);
102 }else if(a.equals("xdivisor") || a.equals("xsize")){
103 Tile.xSize=Parse.parseIntKMG(b);
104 }else if(a.equals("ydivisor") || a.equals("ysize")){
105 Tile.ySize=Parse.parseIntKMG(b);
106 }else if(a.equals("target")){
107 targetAverageReads=Parse.parseIntKMG(b);
108 }else if(a.equals("dump") || a.equals("out")){
109 dump=b;
110 }else if(a.equals("indump") || a.equals("ind") || a.equals("dumpin")){
111 dumpIn=b;
112 }else if(a.equals("pound")){
113 pound=Parse.parseBoolean(b);
114 }else if(a.equals("loadkmers") || a.equals("usekmers")){
115 loadKmers=Parse.parseBoolean(b);
116 }else if(a.equals("allkmers")){
117 kmersPerRead=(Parse.parseBoolean(b) ? 0 : 1);
118 }else if(a.equals("kmersperread")){
119 kmersPerRead=Integer.parseInt(b);
120 }else if(a.equals("multithreaded")){
121 multithreadedLoad=multithreadedFill=Parse.parseBoolean(b);
122 }else if(a.equals("multiload")){
123 multithreadedLoad=Parse.parseBoolean(b);
124 }else if(a.equals("multifill")){
125 multithreadedFill=Parse.parseBoolean(b);
126 }else if(a.equals("bloom")){
127 bloomMode=Parse.parseBoolean(b);
128 }else if(a.equals("bits") || a.equals("cbits")){
129 cbits=Integer.parseInt(b);
130 }else if(a.equals("hashes")){
131 hashes=Integer.parseInt(b);
132 }else if(a.equals("ref")){
133 refPath=b;
134 }else if(a.equals("minid")){
135 minIdentity=Float.parseFloat(b);
136 if(minIdentity>1) {minIdentity/=100;}
137 }else if(a.equals("kalign") || a.equals("alignk")){
138 alignK=Integer.parseInt(b);
139 }else if(a.equals("expectedbarcodes") || a.equals("expected") || a.equals("barcodes")){
140 expectedBarcodes=b;
141 }else if(a.equals("shortheader")){
142 MicroTile.shortHeader=Parse.parseBoolean(b);
143 }else if(a.equals("longheader")){
144 MicroTile.shortHeader=!Parse.parseBoolean(b);
145 }
146
147 else if(a.equals("minpolyg")){
148 MicroTile.MIN_POLY_G=Integer.parseInt(b);
149 }else if(a.equals("trackcycles")){
150 MicroTile.TRACK_CYCLES=Parse.parseBoolean(b);
151 }else if(a.equals("extra")){
152 if(b!=null) {
153 for(String s : b.split(",")) {
154 extra.add(s);
155 }
156 }
157 }
158
159 else if(a.equals("parse_flag_goes_here")){
160 //Set a variable here
161 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
162 //do nothing
163 }else if(b==null && new File(arg).exists()){
164 extra.add(b);
165 }else{
166 outstream.println("Unknown parameter "+args[i]);
167 assert(false) : "Unknown parameter "+args[i];
168 // throw new RuntimeException("Unknown parameter "+args[i]);
169 }
170 }
171
172 {//Process parser fields
173 Parser.processQuality();
174
175 maxReads=parser.maxReads;
176
177 overwrite=parser.overwrite;
178 append=parser.append;
179 setInterleaved=parser.setInterleaved;
180
181 in1=parser.in1;
182 in2=parser.in2;
183
184 if(dump==null && parser.out1!=null){dump=parser.out1;}
185
186 extin=parser.extin;
187 }
188
189 if("phix".equalsIgnoreCase(refPath)) {
190 refPath=Data.findPath("?phix2.fa.gz");
191 }
192
193 //Do input file # replacement
194 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
195 in2=in1.replace("#", "2");
196 in1=in1.replace("#", "1");
197 }
198
199 //Adjust interleaved detection based on the number of input files
200 if(in2!=null){
201 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
202 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
203 }
204
205 assert(FastaReadInputStream.settingsOK());
206
207 //Ensure there is an input file
208 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
209
210 //Adjust the number of threads for input file reading
211 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
212 ByteFile.FORCE_MODE_BF2=true;
213 }
214
215 //Adjust interleaved settings based on number of output files
216 if(!setInterleaved){
217 assert(in1!=null) : "\nin1="+in1+"\nin2="+in2+"\n";
218 if(in2!=null){ //If there are 2 input streams.
219 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
220 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
221 }
222 }
223
224 //Ensure output files can be written
225 if(!Tools.testOutputFiles(overwrite, append, false, dump)){
226 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+dump+"\n");
227 }
228
229 //Ensure input files can be read
230 if(!Tools.testInputFiles(false, true, in1, in2)){
231 throw new RuntimeException("\nCan't read some input files.\n");
232 }
233
234 //Ensure that no file was specified multiple times
235 if(!Tools.testForDuplicateFiles(true, in1, in2, dump)){
236 throw new RuntimeException("\nSome file names were specified multiple times.\n");
237 }
238
239 //Create input FileFormat objects
240 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
241 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
242 }
243
244 /*--------------------------------------------------------------*/
245 /*---------------- Outer Methods ----------------*/
246 /*--------------------------------------------------------------*/
247
248 /** Create read streams and process all data */
249 public void process(Timer t){
250
251 final int oldThreads=Shared.threads();
252 Shared.capThreads(kmersPerRead>0 ? 64 : 64);
253
254 barcodeStats=loadBarcodes(expectedBarcodes);
255 //Reset counters
256 readsProcessed=0;
257 basesProcessed=0;
258
259 MicroIndex3 index=(refPath==null ? null : new MicroIndex3(alignK, 0, refPath, false));
260 mapper=(index==null ? null : new MicroAligner3(index, minIdentity, true));
261
262 if(dumpIn==null){
263 flowcell=new FlowCell(k);
264 if(loadKmers){loadKmers();}
265 fillTiles();
266 keySets=null;
267 bloomFilter=null;
268 bloomCorrector=null;
269 }else{
270 flowcell=new FlowCell(dumpIn);
271
272 if(flowcell.avgReads<targetAverageReads){
273 flowcell=flowcell.widenToTargetReads(targetAverageReads);
274 }
275 }
276
277 Shared.setThreads(oldThreads);
278 }
279
280 /** Create read streams and process all data */
281 void loadKmers(){
282 Timer t2=new Timer();
283 outstream.print("Loading kmers: \t");
284 if(bloomMode) {
285 BloomFilter.printMem=false;
286 KmerCountAbstract.KMERS_PER_READ=kmersPerRead;
287 }
288 if(bloomMode && multithreadedLoad) {
289 KmerCountAbstract.CANONICAL=true;
290 // ReadCounter rc=new ReadCounter(k, true, false, true, false);
291 bloomFilter=new BloomFilter(in1, in2, extra, k, k, cbits, hashes, 1, true, false, true, 0.7f);
292 }else {
293 //Create a read input stream
294 final ConcurrentReadInputStream cris;
295 {
296 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
297 cris.start(); //Start the stream
298 if(verbose){outstream.println("Started cris");}
299 }
300 boolean paired=cris.paired();
301 // if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
302
303 //Process the read stream
304 loadKmersInner(cris);
305
306 if(verbose){outstream.println("Finished; closing streams.");}
307
308 //Close the read streams
309 errorState|=ReadWrite.closeStreams(cris);
310 }
311
312 t2.stop();
313 outstream.println(t2);
314
315 if(bloomFilter!=null) {
316 bloomCorrector=new BloomFilterCorrector(bloomFilter, k, k);
317 double used=bloomFilter.filter.usedFraction();
318 long unique=(long)bloomFilter.filter.estimateUniqueKmersFromUsedFraction(hashes, used);
319 System.err.println(String.format("Bloom Occupancy:\t%.2f%%", 100*used));
320 System.err.println("Unique Kmers: \t"+unique);
321 // System.err.println("Cells: \t"+bloomFilter.filter.cells);
322 // System.err.println("Cells Used: \t"+bloomFilter.filter.cellsUsed());
323 assert(keySets==null);
324 BloomFilter.printMem=true;
325 }
326 KmerCountAbstract.KMERS_PER_READ=0;
327 }
328
329 BarcodeStats loadBarcodes(String expectedBarcodesFile) {
330 if(delimiter<0) {
331 delimiter=(byte)ffin1.barcodeDelimiter();
332 barcodesPerRead=ffin1.barcodesPerRead();
333 }
334 BarcodeStats bs=new BarcodeStats(delimiter, barcodesPerRead, extin);
335 if(bs.length1<1 && bs.length2<1) {
336 bs.length1=ffin1.barcodeLength(1);
337 bs.length2=ffin1.barcodeLength(2);
338 }
339 if(expectedBarcodesFile!=null) {
340 bs.loadBarcodeList(expectedBarcodesFile, barcodesPerRead>1 ? delimiter : 0, false, false);
341 }
342 return bs;
343 }
344
345 /** Create read streams and process all data */
346 void fillTiles(){
347
348 //Create a read input stream
349 final ConcurrentReadInputStream cris;
350 {
351 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
352 cris.start(); //Start the stream
353 if(verbose){outstream.println("Started cris");}
354 }
355 // boolean paired=cris.paired();
356 // if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
357
358 Timer t2=new Timer();
359
360 //Process the read stream
361 outstream.print("Filling tiles: \t");
362 if(multithreadedFill) {
363 spawnThreads(cris);
364 }else {
365 fillTilesInner(cris);
366 }
367
368 t2.stop();
369 outstream.println(t2);
370
371 ArrayList<MicroTile> mtList=flowcell.calcStats();
372 if(flowcell.avgReads<targetAverageReads){
373 flowcell=flowcell.widenToTargetReads(targetAverageReads);
374 mtList=flowcell.toList();
375 }
376
377 if(dump!=null){
378 flowcell.dump(dump, overwrite);
379 }
380
381 if(verbose){outstream.println("Finished; closing streams.");}
382
383 //Close the read streams
384 errorState|=ReadWrite.closeStreams(cris);
385 }
386
387 /*--------------------------------------------------------------*/
388 /*---------------- Inner Methods ----------------*/
389 /*--------------------------------------------------------------*/
390
391 /** Iterate through the reads */
392 private void loadKmersInner(final ConcurrentReadInputStream cris){
393
394 if(bloomMode) {
395 bloomFilter=new BloomFilter(k, k, cbits, hashes, 1, true, false, true, 0.7f);
396 }else {
397 keySets=new AbstractKmerTable[WAYS];
398
399 //Initialize tables
400 ScheduleMaker scheduleMaker=new ScheduleMaker(WAYS, 12, false, 0.8);
401 int[] schedule=scheduleMaker.makeSchedule();
402 for(int j=0; j<WAYS; j++){
403 keySets[j]=new HashArray1D(schedule, -1L);
404 }
405 }
406 //Do anything necessary prior to processing
407 loadKmersST(cris);
408 if(bloomMode) {bloomFilter.filter.shutdown();}
409 //Do anything necessary after processing
410 }
411
412 private void loadKmersST(final ConcurrentReadInputStream cris) {
413 //Grab the first ListNum of reads
414 ListNum<Read> ln=cris.nextList();
415 //Grab the actual read list from the ListNum
416 ArrayList<Read> reads=(ln!=null ? ln.list : null);
417
418 //Check to ensure pairing is as expected
419 if(reads!=null && !reads.isEmpty()){
420 Read r=reads.get(0);
421 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
422 }
423
424 LongList kmers=new LongList(300);
425
426 //As long as there is a nonempty read list...
427 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
428 if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}
429
430 //Loop through each read in the list
431 for(int idx=0; idx<reads.size(); idx++){
432 final Read r1=reads.get(idx);
433 final Read r2=r1.mate;
434
435 loadKmers(r1, kmers);
436 loadKmers(r2, kmers);
437 }
438
439 //Notify the input stream that the list was used
440 cris.returnList(ln);
441 if(verbose){outstream.println("Returned a list.");}
442
443 //Fetch a new list
444 ln=cris.nextList();
445 reads=(ln!=null ? ln.list : null);
446 }
447
448 //Notify the input stream that the final list was used
449 if(ln!=null){
450 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
451 }
452 }
453
454 private void loadKmers(Read r, LongList kmers) {
455 if(r==null || r.length()<k) {return;}
456 // if(!randy.nextBoolean()) {return;}//Speed optimization, I guess
457 if(kmersPerRead<1) {
458 kmers.clear();
459 BloomFilter.toKmers(r, kmers, k, 0, 0, true);
460 if(keySets!=null) {
461 for(int i=0; i<kmers.size; i++) {
462 long kmer=kmers.array[i];
463 AbstractKmerTable table=keySets[(int)(kmer%WAYS)];
464 table.increment(kmer, 1);
465 }
466 }else {
467 for(int i=0; i<kmers.size; i++) {
468 long kmer=kmers.array[i];
469 bloomFilter.filter.increment(kmer);
470 }
471 }
472 }else {
473 // final long kmer=toKmer(r.bases, randy.nextInt(r.length()-k2), k);
474 final long kmer=toKmer(r.bases, (int)(r.numericID%(r.length()-k2)), k);
475 if(kmer>=0){
476 if(keySets!=null) {
477 AbstractKmerTable table=keySets[(int)(kmer%WAYS)];
478 table.increment(kmer, 1);
479 }else {
480 bloomFilter.filter.increment(kmer);
481 }
482 }
483 }
484 }
485
486 /** Iterate through the reads */
487 private void fillTilesInner(final ConcurrentReadInputStream cris){
488
489 LongList kmers=new LongList();
490 IntList counts=new IntList();
491 {
492 //Grab the first ListNum of reads
493 ListNum<Read> ln=cris.nextList();
494 //Grab the actual read list from the ListNum
495 ArrayList<Read> reads=(ln!=null ? ln.list : null);
496
497 //Check to ensure pairing is as expected
498 if(reads!=null && !reads.isEmpty()){
499 Read r=reads.get(0);
500 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
501 }
502
503 //As long as there is a nonempty read list...
504 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
505 if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}
506
507 //Loop through each read in the list
508 for(int idx=0; idx<reads.size(); idx++){
509 final Read r1=reads.get(idx);
510 final Read r2=r1.mate;
511
512 //Track the initial length for statistics
513 final int initialLength1=r1.length();
514 final int initialLength2=r1.mateLength();
515
516 //Increment counters
517 readsProcessed+=r1.pairCount();
518 basesProcessed+=initialLength1+initialLength2;
519
520 final MicroTile mt=flowcell.getMicroTile(r1.id);
521
522 if(loadKmers){
523 processTileKmers(r1, mt, kmers, counts);
524 processTileKmers(r2, mt, kmers, counts);
525 }
526
527 if(mapper!=null) {
528 mapper.map(r1);
529 mapper.map(r2);
530 }
531
532 if(barcodeStats!=null) {
533 String code=r1.barcode(true);
534 int hdist=barcodeStats.calcHdist(code);
535 mt.barcodes+=barcodesPerRead;
536 mt.barcodeHDistSum+=hdist;
537 }
538
539 mt.add(r1);
540 mt.add(r2);
541 }
542
543 //Notify the input stream that the list was used
544 cris.returnList(ln);
545 if(verbose){outstream.println("Returned a list.");}
546
547 //Fetch a new list
548 ln=cris.nextList();
549 reads=(ln!=null ? ln.list : null);
550 }
551
552 //Notify the input stream that the final list was used
553 if(ln!=null){
554 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
555 }
556 }
557 }
558
559 void processTileKmers(Read r, MicroTile mt, LongList kmers, IntList counts) {
560 if(r==null || r.length()<k) {return;}
561
562 if(kmersPerRead<1 && bloomMode) {
563 processAllKmers(r, mt, kmers, counts);
564 }else {
565 processOneKmer(r, mt);
566 }
567 }
568
569 void processOneKmer(Read r, MicroTile mt) {
570 // final long kmer=toKmer(r.bases, randy.nextInt(r.length()-k2), k);
571 final long kmer=toKmer(r.bases, (int)((r.numericID+1)%(r.length()-k2)), k);
572 if(kmer<0) {
573 mt.misses++;
574 return;
575 }
576 final long key=(kmersPerRead<1 ? Tools.max(kmer, AminoAcid.reverseComplementBinaryFast(kmer, k)) : kmer);
577 final int value=(keySets==null ? bloomFilter.getCount(key) : keySets[(int)(key%WAYS)].getValue(key));
578 mt.depthSum+=value;
579 final int cutoff=(kmersPerRead<1 ? 2 : 1);
580 if(value>=cutoff) {mt.hits++;}
581 else {mt.misses++;}
582 }
583
584 void processAllKmers(Read r, MicroTile mt, LongList kmers, IntList counts) {
585 final byte[] bases=r.bases;
586 final byte[] quals=r.quality;
587
588 int valid=bloomCorrector.fillKmers(bases, kmers);
589 if(valid<2){return;}
590 // if(!r.containsUndefined() && !bloomCorrector.hasErrorsFast(kmers)){return;}
591
592
593 bloomCorrector.fillCounts(bases, kmers, counts);
594 final int depth=(counts.size<1 ? 0 : counts.get((int)((r.numericID+1)%counts.size)));
595 mt.depthSum+=depth;
596 if(depth>1) {mt.hits++;}
597 else {mt.misses++;}
598 final int possibleErrors=bloomCorrector.countErrors(counts, quals);
599 mt.kmerBaseErrorCount+=possibleErrors;
600 mt.kmerReadErrorCount+=(possibleErrors>0 ? 1 : 0);
601 }
602
603 /*--------------------------------------------------------------*/
604 /*---------------- Threading ----------------*/
605 /*--------------------------------------------------------------*/
606
607 /** Spawn process threads */
608 private void spawnThreads(final ConcurrentReadInputStream cris){
609
610 //Do anything necessary prior to processing
611
612 //Determine how many threads may be used
613 final int threads=Shared.threads();
614
615 //Fill a list with ProcessThreads
616 ArrayList<WorkerThread> alpt=new ArrayList<WorkerThread>(threads);
617 for(int i=0; i<threads; i++){
618 alpt.add(new WorkerThread(cris, i));
619 }
620
621 //Start the threads and wait for them to finish
622 boolean success=ThreadWaiter.startAndWait(alpt, this);
623 errorState&=!success;
624
625 //Do anything necessary after processing
626
627 }
628
629 @Override
630 public final void accumulate(WorkerThread pt){
631 // System.err.println("Accumulating "+pt.tid+": "+pt.readsProcessedT);
632 synchronized(pt) {
633 flowcell.add(pt.fc);
634 readsProcessed+=pt.readsProcessedT;
635 basesProcessed+=pt.basesProcessedT;
636 errorState|=(!pt.success);
637 }
638 // System.err.println("readsProcessed: "+readsProcessed+", "+flowcell.readsProcessed);
639 // pt.fc.dump(pt.tid+".txt", overwrite);
640 }
641
642 @Override
643 public final boolean success() {return !errorState;}
644
645 class WorkerThread extends Thread {
646
647 WorkerThread(ConcurrentReadInputStream cris_, int tid_){
648 cris=cris_;
649 tid=tid_;
650 fc=new FlowCell(k);
651 }
652
653 //Called by start()
654 @Override
655 public void run(){
656 //Do anything necessary prior to processing
657
658 //Process the reads
659 processInner();
660
661 //Do anything necessary after processing
662
663 //Indicate successful exit status
664 success=true;
665 }
666
667 /** Iterate through the reads */
668 void processInner(){
669
670 //Grab the first ListNum of reads
671 ListNum<Read> ln=cris.nextList();
672
673 //As long as there is a nonempty read list...
674 while(ln!=null && ln.size()>0){
675 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
676
677 processList(ln);
678
679 //Notify the input stream that the list was used
680 cris.returnList(ln);
681 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
682
683 //Fetch a new list
684 ln=cris.nextList();
685 }
686
687 //Notify the input stream that the final list was used
688 if(ln!=null){
689 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
690 }
691 }
692
693 void processList(ListNum<Read> ln){
694
695 //Grab the actual read list from the ListNum
696 final ArrayList<Read> reads=ln.list;
697
698 //Loop through each read in the list
699 for(int idx=0; idx<reads.size(); idx++){
700 final Read r1=reads.get(idx);
701 final Read r2=r1.mate;
702
703 //Validate reads in worker threads
704 if(!r1.validated()){r1.validate(true);}
705 if(r2!=null && !r2.validated()){r2.validate(true);}
706
707 {
708 //Reads are processed in this block.
709 processReadPair(r1, r2);
710 }
711 }
712
713 //Output reads to the output stream
714 // if(ros!=null){ros.add(reads, ln.id);}
715 }
716
717 /**
718 * Process a read or a read pair.
719 * @param r1 Read 1
720 * @param r2 Read 2 (may be null)
721 * @return True if the reads should be kept, false if they should be discarded.
722 */
723 void processReadPair(final Read r1, final Read r2){
724 //Increment counters
725 readsProcessedT+=r1.pairCount();
726 basesProcessedT+=r1.pairLength();
727
728 final MicroTile mt=fc.getMicroTile(r1.id);
729
730 if(loadKmers){
731 processTileKmers(r1, mt, kmers, counts);
732 processTileKmers(r2, mt, kmers, counts);
733 }
734
735 if(mapper!=null) {
736 mapper.map(r1);
737 mapper.map(r2);
738 }
739
740 if(barcodeStats!=null) {
741 String code=r1.barcode(true);
742 int hdist=barcodeStats.calcHdist(code);
743 mt.barcodes+=barcodesPerRead;
744 mt.barcodeHDistSum+=hdist;
745 }
746
747 mt.add(r1);
748 mt.add(r2);
749 }
750
751 /** Number of reads processed by this thread */
752 protected long readsProcessedT=0;
753 /** Number of bases processed by this thread */
754 protected long basesProcessedT=0;
755
756 /** True only if this thread has completed successfully */
757 boolean success=false;
758
759 /** Shared input stream */
760 private final ConcurrentReadInputStream cris;
761 /** Thread ID */
762 final int tid;
763
764 final FlowCell fc;
765
766 final LongList kmers=new LongList();
767 final IntList counts=new IntList();
768 }
769
770 /*--------------------------------------------------------------*/
771 /*---------------- Helper Methods ----------------*/
772 /*--------------------------------------------------------------*/
773
774 /**
775 * Generate a kmer from specified start location
776 * @param bases
777 * @param start
778 * @param klen kmer length
779 * @return kmer
780 */
781 private static final long toKmer(final byte[] bases, final int start, final int klen){
782 final int stop=start+klen;
783 assert(stop<=bases.length) : klen+", "+bases.length;
784 long kmer=0;
785
786 for(int i=start; i<stop; i++){
787 final byte b=bases[i];
788 final long x=Dedupe.baseToNumber[b];
789 kmer=((kmer<<2)|x);
790 }
791 return kmer;
792 }
793
794 /*--------------------------------------------------------------*/
795 /*---------------- Fields ----------------*/
796 /*--------------------------------------------------------------*/
797
798 /** Primary input file path */
799 private String in1=null;
800 /** Secondary input file path */
801 private String in2=null;
802
803 private ArrayList<String> extra=new ArrayList<String>();
804
805 /** Override input file extension */
806 private String extin=null;
807
808 private boolean pound=true;
809 private String dump=null;
810 private String dumpIn=null;
811
812 /*--------------------------------------------------------------*/
813
814 /** Number of reads processed */
815 public long readsProcessed=0;
816 /** Number of bases processed */
817 public long basesProcessed=0;
818
819 /** Quit after processing this many input reads; -1 means no limit */
820 private long maxReads=-1;
821
822 /** Hold kmers. A kmer X such that X%WAYS=Y will be stored in keySets[Y] */
823 private AbstractKmerTable[] keySets;
824
825 private BloomFilter bloomFilter;
826 private BloomFilterCorrector bloomCorrector;
827
828 private boolean bloomMode=false;
829 private boolean multithreadedLoad=false;
830 private boolean multithreadedFill=false;
831
832 private boolean loadKmers=true;
833 private int kmersPerRead=1;
834 private int cbits=4;
835 private int hashes=3;
836
837 private int targetAverageReads=800;
838
839 private static final int WAYS=31;
840 private static final int k=31, k2=30;
841
842 // private final Random randy=Shared.threadLocalRandom();
843 private FlowCell flowcell;
844
845 private String refPath="phix";
846 // private byte[] ref;
847 // private LongHashMap refIndex;
848 private MicroAligner3 mapper;
849 float minIdentity=0.65f;
850 int alignK=19; //Phix is unique down to k=13
851
852
853 private byte delimiter='+';
854 private int barcodesPerRead=2;
855 private String expectedBarcodes;
856 private BarcodeStats barcodeStats;
857 // private long minCountToUse=0;
858 //
859 // private boolean warned=false;
860
861 /*--------------------------------------------------------------*/
862 /*---------------- Final Fields ----------------*/
863 /*--------------------------------------------------------------*/
864
865 /** Primary input file */
866 private final FileFormat ffin1;
867 /** Secondary input file */
868 private final FileFormat ffin2;
869
870 @Override
871 public final ReadWriteLock rwlock() {return rwlock;}
872 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
873
874 /*--------------------------------------------------------------*/
875 /*---------------- Common Fields ----------------*/
876 /*--------------------------------------------------------------*/
877
878 /** Print status messages to this output stream */
879 private PrintStream outstream=System.err;
880 /** Print verbose messages */
881 public static boolean verbose=false;
882 /** True if an error was encountered */
883 public boolean errorState=false;
884 /** Overwrite existing output files */
885 private boolean overwrite=true;
886 /** Append to existing output files */
887 private boolean append=false;
888
889 }