Debian Codegraph @

current/var2/FilterSam.java

raw symbols SCIP
1 package var2;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5
6 import fileIO.ByteFile;
7 import fileIO.FileFormat;
8 import fileIO.ReadWrite;
9 import shared.Parse;
10 import shared.Parser;
11 import shared.PreParser;
12 import shared.Shared;
13 import shared.Timer;
14 import shared.Tools;
15 import stream.ConcurrentReadInputStream;
16 import stream.ConcurrentReadOutputStream;
17 import stream.FastaReadInputStream;
18 import stream.Read;
19 import stream.SamLine;
20 import stream.SamReadStreamer;
21 import stream.SamStreamer;
22 import structures.ListNum;
23 import tracker.ReadStats;
24
25 /**
26 * Removes lines with unsupported variations from a sam file.
27 *
28 * @author Brian Bushnell
29 * @date January 25, 2018
30 *
31 */
32 public class FilterSam {
33
34 /*--------------------------------------------------------------*/
35 /*---------------- Initialization ----------------*/
36 /*--------------------------------------------------------------*/
37
38 /**
39 * Code entrance from the command line.
40 * @param args Command line arguments
41 */
42 public static void main(String[] args){
43 //Start a timer immediately upon code entrance.
44 Timer t=new Timer();
45
46 //Create an instance of this class
47 FilterSam x=new FilterSam(args);
48
49 //Run the object
50 x.process(t);
51
52 //Close the print stream if it was redirected
53 Shared.closeStream(x.outstream);
54 }
55
56 /**
57 * Constructor.
58 * @param args Command line arguments
59 */
60 public FilterSam(String[] args){
61
62 {//Preparse block for help, config files, and outstream
63 PreParser pp=new PreParser(args, getClass(), false);
64 args=pp.args;
65 outstream=pp.outstream;
66 }
67
68 //Set shared static variables
69 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
70 ReadWrite.setZipThreads(Shared.threads());
71 SamLine.SET_FROM_OK=true;
72 Var.CALL_INS=false;
73 Var.CALL_DEL=false;
74
75 //Create a parser object
76 Parser parser=new Parser();
77
78 //Parse each argument
79 for(int i=0; i<args.length; i++){
80 String arg=args[i];
81
82 //Break arguments into their constituent parts, in the form of "a=b"
83 String[] split=arg.split("=");
84 String a=split[0].toLowerCase();
85 String b=split.length>1 ? split[1] : null;
86
87 if(a.equals("verbose")){
88 verbose=Parse.parseBoolean(b);
89 }else if(a.equals("ordered")){
90 ordered=Parse.parseBoolean(b);
91 }else if(a.equals("ss") || a.equals("streamer")){
92 useStreamer=Parse.parseBoolean(b);
93 }else if(a.equals("ploidy")){
94 ploidy=Integer.parseInt(b);
95 }else if(a.equals("prefilter")){
96 prefilter=Parse.parseBoolean(b);
97 }else if(a.equals("ref")){
98 ref=b;
99 }else if(a.equals("outbad") || a.equals("outb")){
100 outBad=b;
101 }else if(a.equals("vars") || a.equals("variants") || a.equals("varfile") || a.equals("inv")){
102 varFile=b;
103 }else if(a.equals("vcf") || a.equals("vcffile")){
104 vcfFile=b;
105 }else if(a.equals("maxsubs") || a.equals("subfilter")){
106 maxSubs=Integer.parseInt(b);
107 }else if(a.equals("maxvars") || a.equals("varfilter")){
108 maxVars=Integer.parseInt(b);
109 }else if(a.equals("maxbadsubs") || a.equals("maxbadvars") || a.equals("mbv")){
110 maxBadVars=Integer.parseInt(b);
111 }else if(a.equals("maxbadsubdepth") || a.equals("maxbadvardepth") || a.equals("maxbadsuballeledepth")
112 || a.equals("maxbadvaralleledepth") || a.equals("mbsad") || a.equals("mbvad") || a.equals("mbad")){
113 maxBadAlleleDepth=Integer.parseInt(b);
114 }else if(a.equals("maxbadallelefraction") || a.equals("mbaf")){
115 maxBadAlleleFraction=Float.parseFloat(b);
116 }else if(a.equals("minbadsubreaddepth") || a.equals("minbadreaddepth") || a.equals("mbsrd") || a.equals("mbrd")){
117 minBadReadDepth=Integer.parseInt(b);
118 }else if(a.equals("sub") || a.equals("subs")){
119 Var.CALL_SUB=Parse.parseBoolean(b);
120 }else if(a.equals("ins") || a.equals("inss")){
121 Var.CALL_INS=Parse.parseBoolean(b);
122 }else if(a.equals("del") || a.equals("dels")){
123 Var.CALL_DEL=Parse.parseBoolean(b);
124 }else if(a.equals("indel") || a.equals("indels")){
125 Var.CALL_INS=Var.CALL_DEL=Parse.parseBoolean(b);
126 }else if(a.equals("minedist") || a.equals("minenddist") || a.equals("border")){
127 minEDist=Integer.parseInt(b);
128 }else if(a.equals("parse_flag_goes_here")){
129 long fake_variable=Parse.parseKMG(b);
130 //Set a variable here
131 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
132 //do nothing
133 }else{
134 outstream.println("Unknown parameter "+args[i]);
135 assert(false) : "Unknown parameter "+args[i];
136 }
137 }
138
139 {//Process parser fields
140 Parser.processQuality();
141
142 maxReads=parser.maxReads;
143
144 overwrite=ReadStats.overwrite=parser.overwrite;
145 append=ReadStats.append=parser.append;
146
147 in1=parser.in1;
148
149 outGood=parser.out1;
150 }
151
152 assert(FastaReadInputStream.settingsOK());
153
154 //Ensure there is an input file
155 // if(in1==null){throw new RuntimeException("Error - an input file and a VCF file are required.");}
156 if(in1==null){throw new RuntimeException("Error - an input file is required.");}
157
158 //Adjust the number of threads for input file reading
159 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
160 ByteFile.FORCE_MODE_BF2=true;
161 }
162
163 //Ensure output files can be written
164 if(!Tools.testOutputFiles(overwrite, append, false, outGood, outBad)){
165 outstream.println((outGood==null)+", "+(outBad==null));
166 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+outGood+", "+outBad+"\n");
167 }
168
169 //Ensure input files can be read
170 if(!Tools.testInputFiles(false, true, in1, vcfFile, varFile)){
171 throw new RuntimeException("\nCan't read some input files.\n");
172 }
173
174 //Ensure that no file was specified multiple times
175 if(!Tools.testForDuplicateFiles(true, in1, vcfFile, varFile, outBad, outGood)){
176 throw new RuntimeException("\nSome file names were specified multiple times.\n");
177 }
178
179 //Create output FileFormat objects
180 ffoutGood=FileFormat.testOutput(outGood, FileFormat.SAM, null, true, overwrite, append, ordered);
181 ffoutBad=FileFormat.testOutput(outBad, FileFormat.SAM, null, true, overwrite, append, ordered);
182
183 //Create input FileFormat objects
184 ffin1=FileFormat.testInput(in1, FileFormat.SAM, null, true, true);
185
186 Timer t=new Timer(outstream, true);
187 {
188 t.start();
189 outstream.print("Loading scaffolds: ");
190 if(ref==null){
191 scafMap=ScafMap.loadSamHeader(in1);
192 }else{
193 scafMap=ScafMap.loadReference(ref, true);
194 }
195 assert(scafMap!=null && scafMap.size()>0) : "No scaffold names were loaded.";
196 t.stop(pad(scafMap.size(), 12)+" \t");
197 }
198 t.start();
199 if(varFile!=null){
200 outstream.print("Loading vars: ");
201 varMap=VcfLoader.loadVarFile(varFile, scafMap);
202 t.stop(pad(varMap.size(), 12)+" \t");
203 }else if(vcfFile!=null){t.start();
204 outstream.print("Loading vcf: ");
205 varMap=VcfLoader.loadVcfFile(vcfFile, scafMap, true, false);
206 t.stop(pad(varMap.size(), 12)+" \t");
207 }else{
208 outstream.print("Calling variants:\n");
209 String inString="in="+in1;
210
211 // private int maxBadAlleleDepth=2;
212 // /** Maximum allele fraction for variants considered unsupported */
213 // private float maxBadAlleleFraction=0.01f;
214
215 String[] cvargs=new String[] {inString, "ref="+ref, "clearfilters", "minreads="+(maxBadAlleleDepth),
216 "minallelefraction="+maxBadAlleleFraction, "printexecuting=f"};
217
218 boolean trd=Shared.TRIM_READ_COMMENTS;
219 boolean trn=Shared.TRIM_RNAME;
220 CallVariants cv=new CallVariants(cvargs);
221 Shared.TRIM_READ_COMMENTS=trd;
222 Shared.TRIM_RNAME=trn;
223
224 cv.prefilter=prefilter;
225 cv.ploidy=ploidy;
226
227 varMap=cv.process(new Timer());
228 scafMap=cv.scafMap;
229 t.stop(/*pad(varMap.size(), 12)+" \t"*/);
230 }
231
232 assert(Var.CALL_INS || Var.CALL_DEL || Var.CALL_SUB) : "Must enable at least one of subs, insertions, or deletions.";
233 subsOnly=!Var.CALL_INS && !Var.CALL_DEL;
234 }
235
236 /*--------------------------------------------------------------*/
237 /*---------------- Outer Methods ----------------*/
238 /*--------------------------------------------------------------*/
239
240 /** Create read streams and process all data */
241 void process(Timer t){
242
243 //Turn off read validation in the input threads to increase speed
244 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
245 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
246
247
248 final SamReadStreamer ss;
249 //Create a read input stream
250 final ConcurrentReadInputStream cris;
251 if(useStreamer){
252 cris=null;
253 ss=new SamReadStreamer(ffin1, streamerThreads, true, maxReads);
254 ss.start();
255 if(verbose){outstream.println("Started streamer");}
256 }else{
257 ss=null;
258 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, null);
259 cris.start(); //Start the stream
260 if(verbose){outstream.println("Started cris");}
261 }
262
263 //Optionally create a read output stream
264 final ConcurrentReadOutputStream ros, rosb;
265 if(ffoutGood!=null){
266 //Select output buffer size based on whether it needs to be ordered
267 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
268
269 ros=ConcurrentReadOutputStream.getStream(ffoutGood, null, null, null, buff, null, true);
270 ros.start(); //Start the stream
271 }else{ros=null;}
272 if(ffoutBad!=null){
273 //Select output buffer size based on whether it needs to be ordered
274 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
275
276 rosb=ConcurrentReadOutputStream.getStream(ffoutBad, null, null, null, buff, null, false);
277 rosb.start(); //Start the stream
278 }else{rosb=null;}
279
280 //Reset counters
281 readsProcessed=0;
282 basesProcessed=0;
283
284 //Process the reads in separate threads
285 spawnThreads(cris, ss, ros, rosb);
286
287 if(verbose){outstream.println("Finished; closing streams.");}
288
289 //Write anything that was accumulated by ReadStats
290 errorState|=ReadStats.writeAll();
291 //Close the read streams
292 errorState|=ReadWrite.closeStreams(cris, ros, rosb);
293
294 //Reset read validation
295 Read.VALIDATE_IN_CONSTRUCTOR=vic;
296
297 //Report timing and results
298 {
299 t.stop();
300
301 //Calculate units per nanosecond
302 double rpnano=readsProcessed/(double)(t.elapsed);
303 double bpnano=basesProcessed/(double)(t.elapsed);
304
305 final long rg=readsOut, rb=readsProcessed-readsOut;
306 final long bg=basesOut, bb=basesProcessed-basesOut;
307
308 //Add "k" and "m" for large numbers
309 // String rpstring=(readsProcessed<100000 ? ""+readsProcessed : readsProcessed<100000000 ? (readsProcessed/1000)+"k" : (readsProcessed/1000000)+"m");
310 // String bpstring=(basesProcessed<100000 ? ""+basesProcessed : basesProcessed<100000000 ? (basesProcessed/1000)+"k" : (basesProcessed/1000000)+"m");
311 // String rgstring=(rg<100000 ? ""+rg : rg<100000000 ? (rg/1000)+"k" : (rg/1000000)+"m");
312 // String bgstring=(bg<100000 ? ""+bg : bg<100000000 ? (bg/1000)+"k" : (bg/1000000)+"m");
313 // String rbstring=(rb<100000 ? ""+rb : rb<100000000 ? (rb/1000)+"k" : (rb/1000000)+"m");
314 // String bbstring=(bb<100000 ? ""+bb : bb<100000000 ? (bb/1000)+"k" : (bb/1000000)+"m");
315
316 final int len=12;
317
318 final String rpstring=pad(readsProcessed, len);
319 final String bpstring=pad(basesProcessed, len);
320 final String rgstring=pad(rg, len);
321 final String bgstring=pad(bg, len);
322 final String rbstring=pad(rb, len);
323 final String bbstring=pad(bb, len);
324
325 final double mappedReadsDiscarded=mappedReadsProcessed-mappedReadsRetained;
326 double avgQGood=(bqSumGood/(double)mappedReadsRetained);
327 double avgQBad=(bqSumBad/(double)mappedReadsDiscarded);
328 double avgMapQGood=(mapqSumGood/(double)mappedReadsRetained);
329 double avgMapQBad=(mapqSumBad/(double)mappedReadsDiscarded);
330 double avgVarsGood=(varSumGood/(double)mappedReadsRetained);
331 double avgVarsBad=(varSumBad/(double)mappedReadsDiscarded);
332 final String avgQGoodS=pad(Tools.format("%.2f", avgQGood), len);
333 final String avgQBadS=pad(Tools.format("%.2f", avgQBad), len);
334 final String avgMapQGoodS=pad(Tools.format("%.2f", avgMapQGood), len);
335 final String avgMapQBadS=pad(Tools.format("%.2f", avgMapQBad), len);
336 final String avgVarsGoodS=pad(Tools.format("%.2f", avgVarsGood), len);
337 final String avgVarsBadS=pad(Tools.format("%.2f", avgVarsBad), len);
338
339 outstream.println("Time: \t\t"+t);
340 outstream.println("Reads Processed: "+rpstring+" \t"+Tools.format("%.2fk reads/sec", rpnano*1000000));
341 outstream.println("Bases Processed: "+bpstring+" \t"+Tools.format("%.2fm bases/sec", bpnano*1000));
342 outstream.println();
343 outstream.println("Reads Retained: "+rgstring+" \t"+Tools.format("%.2f%%", (rg*100.0/readsProcessed)));
344 outstream.println("Bases Retained: "+bgstring+" \t"+Tools.format("%.2f%%", (bg*100.0/basesProcessed)));
345 outstream.println("Avg. Qual Retained: "+avgQGoodS);
346 outstream.println("Avg. MapQ Retained: "+avgMapQGoodS);
347 outstream.println("Avg. Vars Retained: "+avgVarsGoodS);
348 outstream.println();
349 outstream.println("Reads Discarded: "+rbstring+" \t"+Tools.format("%.2f%%", (rb*100.0/readsProcessed)));
350 outstream.println("Bases Discarded: "+bbstring+" \t"+Tools.format("%.2f%%", (bb*100.0/basesProcessed)));
351 outstream.println("Avg. Qual Discarded:"+avgQBadS);
352 outstream.println("Avg. MapQ Discarded:"+avgMapQBadS);
353 outstream.println("Avg. Vars Discarded:"+avgVarsBadS);
354 }
355
356 //Throw an exception of there was an error in a thread
357 if(errorState){
358 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
359 }
360 }
361
362 private static String pad(long s, int len){
363 return pad(""+s, len);
364 }
365
366 private static String pad(String s, int len){
367 while(s.length()<len){s=" "+s;}
368 return s;
369 }
370
371 /** Spawn process threads */
372 private void spawnThreads(final ConcurrentReadInputStream cris, final SamStreamer ss, final ConcurrentReadOutputStream ros, final ConcurrentReadOutputStream rosb){
373
374 //Do anything necessary prior to processing
375
376 //Determine how many threads may be used
377 final int threads=Shared.threads();
378
379 //Fill a list with ProcessThreads
380 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
381 for(int i=0; i<threads; i++){
382 alpt.add(new ProcessThread(cris, ss, ros, rosb, i));
383 }
384
385 //Start the threads
386 for(ProcessThread pt : alpt){
387 pt.start();
388 }
389
390 //Wait for completion of all threads
391 boolean success=true;
392 for(ProcessThread pt : alpt){
393
394 //Wait until this thread has terminated
395 while(pt.getState()!=Thread.State.TERMINATED){
396 try {
397 //Attempt a join operation
398 pt.join();
399 } catch (InterruptedException e) {
400 //Potentially handle this, if it is expected to occur
401 e.printStackTrace();
402 }
403 }
404
405 //Accumulate per-thread statistics
406 readsProcessed+=pt.readsProcessedT;
407 basesProcessed+=pt.basesProcessedT;
408 mappedReadsProcessed+=pt.mappedReadsProcessedT;
409 mappedBasesProcessed+=pt.mappedBasesProcessedT;
410 mappedReadsRetained+=pt.mappedReadsRetainedT;
411 mappedBasesRetained+=pt.mappedBasesRetainedT;
412 readsOut+=pt.readsOutT;
413 basesOut+=pt.basesOutT;
414 bqSumGood+=pt.qSumGoodT;
415 bqSumBad+=pt.qSumBadT;
416 // adSumGood+=pt.adSumGoodT;
417 // adSumBad+=pt.adSumBadT;
418 // rdSumGood+=pt.rdSumGoodT;
419 // rdSumBad+=pt.rdSumBadT;
420 varSumGood+=pt.varSumGoodT;
421 varSumBad+=pt.varSumBadT;
422 mapqSumGood+=pt.mapqSumGoodT;
423 mapqSumBad+=pt.mapqSumBadT;
424 success&=pt.success;
425 }
426
427 //Track whether any threads failed
428 if(!success){errorState=true;}
429
430 //Do anything necessary after processing
431
432 }
433
434 /*--------------------------------------------------------------*/
435 /*---------------- Inner Methods ----------------*/
436 /*--------------------------------------------------------------*/
437
438 /*--------------------------------------------------------------*/
439 /*---------------- Inner Classes ----------------*/
440 /*--------------------------------------------------------------*/
441
442 /** This class is static to prevent accidental writing to shared variables.
443 * It is safe to remove the static modifier. */
444 private class ProcessThread extends Thread {
445
446 //Constructor
447 ProcessThread(final ConcurrentReadInputStream cris_, final SamStreamer ss_, final ConcurrentReadOutputStream ros_, final ConcurrentReadOutputStream rosb_, final int tid_){
448 cris=cris_;
449 ss=ss_;
450 ros=ros_;
451 rosb=rosb_;
452 tid=tid_;
453 }
454
455 //Called by start()
456 @Override
457 public void run(){
458 //Do anything necessary prior to processing
459
460 //Process the reads
461 if(useStreamer){
462 processSS();
463 }else{
464 processCris();
465 }
466
467 //Do anything necessary after processing
468
469 //Indicate successful exit status
470 success=true;
471 }
472
473 /** Iterate through the reads */
474 void processCris(){
475
476 //Grab the first ListNum of reads
477 ListNum<Read> ln=cris.nextList();
478 //Grab the actual read list from the ListNum
479 ArrayList<Read> reads=(ln!=null ? ln.list : null);
480
481 //Check to ensure pairing is as expected
482 if(reads!=null && !reads.isEmpty()){
483 Read r=reads.get(0);
484 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
485 }
486
487 //As long as there is a nonempty read list...
488 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
489 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
490
491 ArrayList<Read> good=new ArrayList<Read>(reads.size());
492 ArrayList<Read> bad=new ArrayList<Read>(Tools.max(1, reads.size()/4));
493
494 //Loop through each read in the list
495 for(int idx=0; idx<reads.size(); idx++){
496 final Read r1=reads.get(idx);
497
498 //Validate reads in worker threads
499 if(!r1.validated()){r1.validate(true);}
500
501 //Track the initial length for statistics
502 final int initialLength1=r1.length();
503
504 //Increment counters
505 readsProcessedT++;
506 basesProcessedT+=initialLength1;
507
508 {
509 //Reads are processed in this block.
510 boolean keep=processRead(r1);
511 if(keep){
512 //Increment counters
513 readsOutT++;
514 basesOutT+=initialLength1;
515 good.add(r1);
516 }else{
517 bad.add(r1);
518 }
519 }
520 }
521
522 //Output reads to the output stream
523 if(ros!=null){ros.add(good, ln.id);}
524 if(rosb!=null){rosb.add(bad, ln.id);}
525
526 //Notify the input stream that the list was used
527 cris.returnList(ln);
528 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
529
530 //Fetch a new list
531 ln=cris.nextList();
532 reads=(ln!=null ? ln.list : null);
533 }
534
535 //Notify the input stream that the final list was used
536 if(ln!=null){
537 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
538 }
539 }
540
541 /** Iterate through the reads */
542 void processSS(){
543
544 //Grab the first ListNum of reads
545 ListNum<Read> ln=ss.nextList();
546 //Grab the actual read list from the ListNum
547 ArrayList<Read> reads=(ln!=null ? ln.list : null);
548
549 //Check to ensure pairing is as expected
550 if(reads!=null && !reads.isEmpty()){
551 Read r=reads.get(0);
552 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
553 }
554
555 //As long as there is a nonempty read list...
556 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
557 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
558
559 ArrayList<Read> good=new ArrayList<Read>(reads.size());
560 ArrayList<Read> bad=new ArrayList<Read>(Tools.max(1, reads.size()/4));
561
562 //Loop through each read in the list
563 for(int idx=0; idx<reads.size(); idx++){
564 final Read r1=reads.get(idx);
565
566 //Validate reads in worker threads
567 if(!r1.validated()){r1.validate(true);}
568
569 //Track the initial length for statistics
570 final int initialLength1=r1.length();
571
572 //Increment counters
573 readsProcessedT++;
574 basesProcessedT+=initialLength1;
575
576 {
577 //Reads are processed in this block.
578 boolean keep=processRead(r1);
579 if(keep){
580 //Increment counters
581 readsOutT++;
582 basesOutT+=initialLength1;
583 good.add(r1);
584 }else{
585 bad.add(r1);
586 }
587 }
588 }
589
590 //Output reads to the output stream
591 if(ros!=null){ros.add(good, ln.id);}
592 if(rosb!=null){rosb.add(bad, ln.id);}
593
594 //Fetch a new list
595 ln=ss.nextList();
596 reads=(ln!=null ? ln.list : null);
597 }
598
599 //Notify the input stream that the final list was used
600 if(ln!=null){
601 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
602 }
603 }
604
605 /**
606 * Process a read.
607 * @param r1 Read 1
608 * @return True if the read should be kept, false if it should be discarded.
609 */
610 boolean processRead(final Read r1){
611 return passesVariantFilter(r1);
612 }
613
614 private final boolean passesVariantFilter(Read r){
615 if(!r.mapped() || r.bases==null || r.samline==null || r.match==null){return true;}
616 final int vars=(subsOnly ? Read.countSubs(r.match) : Read.countVars(r.match, Var.CALL_SUB, Var.CALL_INS, Var.CALL_DEL));
617 final int len=r.length();
618 final double q=r.avgQualityByProbabilityDouble(false, r.length());
619 final SamLine sl=r.samline;
620 mappedReadsProcessedT++;
621 mappedBasesProcessedT+=len;
622
623 if(vars==0){
624 varSumGoodT+=vars;
625 qSumGoodT+=q;
626 mapqSumGoodT+=sl.mapq;
627 mappedReadsRetainedT++;
628 mappedBasesRetainedT+=len;
629 return true;
630 }
631
632 if((maxVars>=0 && vars>maxVars) ||
633 (maxSubs>=0 && vars>maxSubs && ((subsOnly ? vars : Read.countSubs(r.match))>maxSubs))){
634 varSumBadT+=vars;
635 qSumBadT+=q;
636 mapqSumBadT+=sl.mapq;
637 return false;
638 }
639
640 if(vars<=maxBadVars){
641 varSumGoodT+=vars;
642 qSumGoodT+=q;
643 mapqSumGoodT+=sl.mapq;
644 mappedReadsRetainedT++;
645 mappedBasesRetainedT+=len;
646 return true;
647 }
648
649 final ArrayList<Var> list;
650 if(subsOnly){
651 list=CallVariants.findUniqueSubs(r, sl, varMap, scafMap, maxBadAlleleDepth, maxBadAlleleFraction, minBadReadDepth, minEDist);
652 }else{
653 list=CallVariants.findUniqueVars(r, sl, varMap, scafMap, maxBadAlleleDepth, maxBadAlleleFraction, minBadReadDepth, minEDist);
654 }
655 if(list==null || list.size()<=maxBadVars){
656 varSumGoodT+=vars;
657 qSumGoodT+=q;
658 mapqSumGoodT+=sl.mapq;
659 mappedReadsRetainedT++;
660 mappedBasesRetainedT+=len;
661 return true;
662 }else{
663 assert(list.size()>maxBadVars) : list.size()+", "+maxBadVars;
664 for(Var v : list){
665 assert(v!=null) : sl.cigar+"\n"+vars+"\n"+v+"\n"+list;
666 assert((v.type()==Var.SUB && Var.CALL_SUB) || (v.type()==Var.INS && Var.CALL_INS) || (v.type()==Var.DEL && Var.CALL_DEL)) :
667 list.size()+", "+maxBadVars+"\n"+sl.cigar+"\n"+v+"\n"+list;
668 }
669 varSumBadT+=vars;
670 qSumBadT+=q;
671 mapqSumBadT+=sl.mapq;
672 return false;
673 }
674 }
675
676 /** Number of reads processed by this thread */
677 protected long readsProcessedT=0;
678 /** Number of reads processed by this thread */
679 protected long basesProcessedT=0;
680 /** Number of mapped reads processed by this thread */
681 protected long mappedReadsProcessedT=0;
682 /** Number of mapped bases processed by this thread */
683 protected long mappedBasesProcessedT=0;
684 /** Number of mapped reads retained by this thread */
685 protected long mappedReadsRetainedT=0;
686 /** Number of mapped bases retained by this thread */
687 protected long mappedBasesRetainedT=0;
688 /** Number of good reads processed by this thread */
689 protected long readsOutT=0;
690 /** Number of good bases processed by this thread */
691 protected long basesOutT=0;
692 protected double qSumGoodT=0;
693 protected double qSumBadT=0;
694 protected long varSumGoodT=0;
695 protected long varSumBadT=0;
696 protected long mapqSumGoodT=0;
697 protected long mapqSumBadT=0;
698
699 /** True only if this thread has completed successfully */
700 boolean success=false;
701
702 /** Shared input stream */
703 private final ConcurrentReadInputStream cris;
704 /** Shared input stream */
705 private final SamStreamer ss;
706 /** Good output stream */
707 private final ConcurrentReadOutputStream ros;
708 /** Bad output stream */
709 private final ConcurrentReadOutputStream rosb;
710 /** Thread ID */
711 final int tid;
712 }
713
714 /*--------------------------------------------------------------*/
715 /*---------------- Fields ----------------*/
716 /*--------------------------------------------------------------*/
717
718 /** Primary input file path */
719 private String in1=null;
720
721 /** Optional reference */
722 private String ref=null;
723
724 /** Good output file path */
725 private String outGood=null;
726 /** Bad output file path */
727 private String outBad=null;
728
729 /** VCF file path */
730 private String varFile=null;
731 /** Variant file path */
732 private String vcfFile=null;
733 private VarMap varMap=null;
734 private ScafMap scafMap=null;
735
736 /*--------------------------------------------------------------*/
737
738 /** Maximum allowed substitutions in a read */
739 private int maxSubs=-1;
740 /** Maximum allowed variations in a read */
741 private int maxVars=-1;
742
743 /** Maximum allowed unsupported substitutions in a read */
744 private int maxBadVars=1;
745 /** Maximum variant depth for a variant to be considered unsupported */
746 private int maxBadAlleleDepth=2;
747 /** Maximum allele fraction for variants considered unsupported */
748 private float maxBadAlleleFraction=0.01f;
749 /** Minimum read depth for a variant to be considered unsupported */
750 private int minBadReadDepth=2;
751 /** Ignore vars within this distance of the ends */
752 private int minEDist=5;
753 private int ploidy=1;
754 private boolean prefilter=false;
755
756 /** Number of reads processed */
757 protected long readsProcessed=0;
758 /** Number of bases processed */
759 protected long basesProcessed=0;
760 /** Number of mapped reads processed by this thread */
761 protected long mappedReadsProcessed=0;
762 /** Number of mapped bases processed by this thread */
763 protected long mappedBasesProcessed=0;
764 /** Number of mapped reads retained by this thread */
765 protected long mappedReadsRetained=0;
766 /** Number of mapped bases retained by this thread */
767 protected long mappedBasesRetained=0;
768 /** Number of good reads processed */
769 protected long readsOut=0;
770 /** Number of good bases processed */
771 protected long basesOut=0;
772
773 protected double bqSumGood=0;
774 protected double bqSumBad=0;
775 // protected double adSumGood=0;
776 // protected double adSumBad=0;
777 // protected double rdSumGood=0;
778 // protected double rdSumBad=0;
779
780 protected long varSumGood=0;
781 protected long varSumBad=0;
782 protected long mapqSumGood=0;
783 protected long mapqSumBad=0;
784
785 /** Quit after processing this many input reads; -1 means no limit */
786 private long maxReads=-1;
787
788 static boolean useStreamer=true;
789 static int streamerThreads=3;
790
791 /*--------------------------------------------------------------*/
792 /*---------------- Final Fields ----------------*/
793 /*--------------------------------------------------------------*/
794
795 /** Primary input file */
796 private final FileFormat ffin1;
797
798 /** Primary output file */
799 private final FileFormat ffoutGood;
800 /** Secondary output file */
801 private final FileFormat ffoutBad;
802
803 private final boolean subsOnly;
804
805 /*--------------------------------------------------------------*/
806 /*---------------- Common Fields ----------------*/
807 /*--------------------------------------------------------------*/
808
809 /** Print status messages to this output stream */
810 private PrintStream outstream=System.err;
811 /** Print verbose messages */
812 public static boolean verbose=false;
813 /** True if an error was encountered */
814 public boolean errorState=false;
815 /** Overwrite existing output files */
816 private boolean overwrite=true;
817 /** Append to existing output files */
818 private boolean append=false;
819 /** Reads are output in input order */
820 private boolean ordered=true;
821
822 }