Debian Codegraph @

current/var2/CallVariants.java

raw symbols SCIP
1 package var2;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7 import java.util.HashMap;
8
9 import bloom.KCountArray7MTA;
10 import dna.Data;
11 import fileIO.ByteFile;
12 import fileIO.FileFormat;
13 import fileIO.ReadWrite;
14 import fileIO.TextFile;
15 import fileIO.TextStreamWriter;
16 import shared.Parse;
17 import shared.Parser;
18 import shared.PreParser;
19 import shared.Shared;
20 import shared.Timer;
21 import shared.Tools;
22 import shared.TrimRead;
23 import stream.ConcurrentReadInputStream;
24 import stream.FastaReadInputStream;
25 import stream.Read;
26 import stream.SamLine;
27 import stream.SamReadStreamer;
28 import stream.SamStreamer;
29 import stream.SamStreamerMF;
30 import structures.ListNum;
31
32 /**
33 * Calls variants from one or more sam or bam files.
34 *
35 * @author Brian Bushnell
36 * @date November 4, 2016
37 *
38 */
39 public class CallVariants {
40
41 /*--------------------------------------------------------------*/
42 /*---------------- Initialization ----------------*/
43 /*--------------------------------------------------------------*/
44
45 /**
46 * Code entrance from the command line.
47 * @param args Command line arguments
48 */
49 public static void main(String[] args){
50
51 //Execute CallVariants2 instead if multisample variant-calling is needed
52 if(preparseMulti(args)){
53 CallVariants2.main(args);
54 return;
55 }
56
57 //Start a timer immediately upon code entrance.
58 Timer t=new Timer();
59
60 //Create an instance of this class
61 CallVariants x=new CallVariants(args);
62
63 //Run the object
64 x.process(t);
65
66 //Close the print stream if it was redirected
67 Shared.closeStream(x.outstream);
68 }
69
70 private static boolean preparseMulti(String[] args){
71 boolean multi=false;
72 for(String arg : args){
73 if(arg.contains("multi")){
74 String[] split=arg.split("=");
75 String a=split[0].toLowerCase();
76 String b=split.length>1 ? split[1] : null;
77 if(b==null || b.equalsIgnoreCase("null")){b=null;}
78 while(a.startsWith("-")){a=a.substring(1);} //Strip leading hyphens
79
80 if(a.equals("multi") || a.equals("multisample")){
81 multi=Parse.parseBoolean(b);
82 }
83 }
84 }
85 return multi;
86 }
87
88 /**
89 * Constructor.
90 * @param args Command line arguments
91 */
92 public CallVariants(String[] args){
93
94 {//Preparse block for help, config files, and outstream
95 PreParser pp=new PreParser(args, getClass(), false);
96 args=pp.args;
97 outstream=pp.outstream;
98 }
99
100 SamLine.PARSE_0=false;
101 // SamLine.PARSE_2=false;
102 // SamLine.PARSE_5=false;
103 // SamLine.PARSE_6=false;
104 // SamLine.PARSE_7=false;
105 SamLine.PARSE_8=false;
106 // SamLine.PARSE_10=false;
107 // SamLine.PARSE_OPTIONAL=false;
108 SamLine.PARSE_OPTIONAL_MD_ONLY=true; //I only need the MD tag..
109
110 SamLine.RNAME_AS_BYTES=false;
111 // ReadWrite.SAMTOOLS_IGNORE_UNMAPPED_INPUT=true;
112
113 //Set shared static variables
114 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
115 ReadWrite.setZipThreads(Shared.threads());
116 ReadWrite.USE_BGZIP=true;
117
118 //Create a parser object
119 Parser parser=new Parser();
120 parser.qtrimLeft=qtrimLeft;
121 parser.qtrimRight=qtrimRight;
122 parser.trimq=trimq;
123 Shared.TRIM_READ_COMMENTS=Shared.TRIM_RNAME=true;
124 Read.IUPAC_TO_N=true;
125
126 samFilter.includeUnmapped=false;
127 samFilter.includeSupplimentary=false;
128 samFilter.includeDuplicate=false;
129 samFilter.includeNonPrimary=false;
130 samFilter.includeQfail=false;
131 samFilter.minMapq=4;
132 String atomic="auto";
133
134 //Parse each argument
135 for(int i=0; i<args.length; i++){
136 String arg=args[i];
137
138 //Break arguments into their constituent parts, in the form of "a=b"
139 String[] split=arg.split("=");
140 String a=split[0].toLowerCase();
141 String b=split.length>1 ? split[1] : null;
142
143 if(a.equals("verbose")){
144 verbose=Parse.parseBoolean(b);
145 }else if(a.equals("multi") || a.equals("multisample")){
146 boolean multi=Parse.parseBoolean(b);
147 assert(!multi) : "\nThis program does not support multi-sample variant calling.\n";
148 }else if(a.equals("ploidy")){
149 ploidy=Integer.parseInt(b);
150 }else if(a.equals("parse_flag_goes_here")){
151 long fake_variable=Parse.parseKMG(b);
152 //Set a variable here
153 }else if(a.equals("ss") || a.equals("samstreamer") || a.equals("streamer")){
154 if(b!=null && Tools.isDigit(b.charAt(0))){
155 useStreamer=true;
156 streamerThreads=Tools.max(1, Integer.parseInt(b));
157 }else{
158 useStreamer=Parse.parseBoolean(b);
159 }
160 }else if(a.equals("ssmf") || a.equals("samstreamermf") || a.equals("streamermf")){
161 if(b!=null && Tools.isDigit(b.charAt(0))){
162 SamStreamerMF.MAX_FILES=Integer.parseInt(b);
163 useStreamerMF=SamStreamerMF.MAX_FILES>1;
164 if(useStreamerMF){useStreamer=true;}
165 }else{
166 useStreamerMF=Parse.parseBoolean(b);
167 if(useStreamerMF){
168 SamStreamerMF.MAX_FILES=Tools.max(2, SamStreamerMF.MAX_FILES);
169 useStreamer=true;
170 }
171 }
172 }else if(a.equals("sslistsize")){
173 SamStreamer.LIST_SIZE=Parse.parseIntKMG(b);
174 assert(SamStreamer.LIST_SIZE>0);
175 }else if(a.equals("cc") || a.equals("calccoverage") || a.equals("coverage")){
176 calcCoverage=Parse.parseBoolean(b);
177 }else if(a.equals("parsename")){
178 SamLine.PARSE_0=Parse.parseBoolean(b);
179 }else if(a.equalsIgnoreCase("noPassDotGenotype") || a.equalsIgnoreCase("noPassDot")){
180 Var.noPassDotGenotype=Parse.parseBoolean(b);
181 }else if(a.equalsIgnoreCase("minVarCopies")){
182 Var.MIN_VAR_COPIES=Integer.parseInt(b);
183 }else if(a.equals("extended")){
184 Var.extendedText=Parse.parseBoolean(b);
185 }else if(a.equals("useidentity")){
186 Var.useIdentity=Parse.parseBoolean(b);
187 }else if(a.equals("usehomopolymer") || a.equals("homopolymer")){
188 Var.useHomopolymer=Parse.parseBoolean(b);
189 }else if(a.equals("usepairing")){
190 Var.usePairing=Parse.parseBoolean(b);
191 }else if(a.equals("usebias")){
192 Var.useBias=Parse.parseBoolean(b);
193 }else if(a.equals("nscan") || a.equals("donscan")){
194 Var.doNscan=Parse.parseBoolean(b);
195 }else if(a.equals("useedist")){
196 Var.useEdist=Parse.parseBoolean(b);
197 }else if(a.equals("prefilter")){
198 prefilter=Parse.parseBoolean(b);
199 }else if(a.equals("ref")){
200 ref=b;
201 if(ref!=null && !Tools.isReadableFile(ref)) {
202 if(ref.equalsIgnoreCase("phix")) {
203 ref=Data.findPath("?phix2.fa.gz");
204 }
205 }
206 }else if(a.equals("vcf") || a.equals("vcfout") || a.equals("outvcf")){
207 vcf=b;
208 }else if(a.equals("invcf") || a.equals("vcfin") || a.equals("forced")){
209 vcfin=b;
210 }else if(a.equals("gff") || a.equals("gffout") || a.equals("outgff")){
211 gffout=b;
212 }else if(a.equals("scorehist") || a.equals("shist")){
213 scoreHistFile=b;
214 }else if(a.equals("zygosityhist") || a.equals("ploidyhist") || a.equals("zhist") || a.equals("phist")){
215 zygosityHistFile=b;
216 }else if(a.equals("qualityhist") || a.equals("qualhist") || a.equals("qhist")){
217 qualityHistFile=b;
218 }else if(a.equals("border")){
219 border=Integer.parseInt(b);
220 }else if(a.equals("sample") || a.equals("samplename")){
221 sampleName=b;
222 }
223
224 else if(a.equals("ca3") || a.equals("32bit")){
225 Scaffold.setCA3(Parse.parseBoolean(b));
226 }else if(a.equals("atomic")){
227 atomic=b;
228 }else if(a.equals("strandedcov") || a.equals("trackstrand") || a.equals("stranded")){
229 Scaffold.setTrackStrand(Parse.parseBoolean(b));
230 }
231
232 else if(a.equals("realign")){
233 realign=Parse.parseBoolean(b);
234 }else if(a.equals("unclip")){
235 unclip=Parse.parseBoolean(b);
236 }else if(a.equals("realignrows") || a.equals("rerows")){
237 Realigner.defaultMaxrows=Integer.parseInt(b);
238 }else if(a.equals("realigncols") || a.equals("recols")){
239 Realigner.defaultColumns=Integer.parseInt(b);
240 }else if(a.equals("realignpadding") || a.equals("repadding") || a.equals("padding")){
241 Realigner.defaultPadding=Integer.parseInt(b);
242 }else if(a.equals("msa")){
243 Realigner.defaultMsaType=b;
244 }else if(a.equals("vmtlimit")){
245 vmtSizeLimit=Parse.parseIntKMG(b);
246 }
247
248 else if(samFilter.parse(arg, a, b)){
249 //do nothing
250 }
251
252 else if(a.equalsIgnoreCase("countNearbyVars")){
253 countNearbyVars=Parse.parseBoolean(b);
254 }
255
256 else if(a.equals("in") || a.equals("in1") || a.equals("in2")){
257 assert(b!=null) : "Bad parameter: "+arg;
258 if(new File(b).exists()){in.add(b);}
259 else{
260 for(String s : b.split(",")){in.add(s);}
261 }
262 }else if(a.equals("list")){
263 for(String line : TextFile.toStringLines(b)){
264 in.add(line);
265 }
266 }else if(a.equals("clearfilters")){
267 if(Parse.parseBoolean(b)){
268 varFilter.clear();
269 samFilter.clear();
270 }
271 }else if(varFilter.parse(a, b, arg)){
272 //do nothing
273 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
274 //do nothing
275 }else if(arg.indexOf('=')<0 && (new File(arg).exists() || arg.indexOf(',')>0)){
276 if(new File(arg).exists()){
277 if(FileFormat.isSamOrBamFile(arg)){
278 in.add(arg);
279 }else if(FileFormat.isFastaFile(arg) && (ref==null || ref.equals(arg))){
280 ref=arg;
281 }else{
282 assert(false) : "Unknown parameter "+arg;
283 outstream.println("Warning: Unknown parameter "+arg);
284 }
285 }else{
286 for(String s : arg.split(",")){
287 if(FileFormat.isSamOrBamFile(s)){
288 in.add(s);
289 }else{
290 assert(false) : "Unknown parameter "+arg+" part "+s;
291 outstream.println("Warning: Unknown parameter "+arg+" part "+s);
292 }
293 }
294 }
295 }else{
296 assert(false) : "Unknown parameter "+args[i];
297 outstream.println("Warning: Unknown parameter "+args[i]);
298 }
299 }
300
301 if("auto".equalsIgnoreCase(atomic)){Scaffold.setCA3A(Shared.threads()>8);}
302 else{Scaffold.setCA3A(Parse.parseBoolean(atomic));}
303
304 if(ploidy<1){System.err.println("WARNING: ploidy not set; assuming ploidy=1."); ploidy=1;}
305 samFilter.setSamtoolsFilter();
306
307 streamerThreads=Tools.max(1, Tools.min(streamerThreads, Shared.threads()));
308 assert(streamerThreads>0) : streamerThreads;
309
310 {//Process parser fields
311 Parser.processQuality();
312
313 maxReads=parser.maxReads;
314 overwrite=parser.overwrite;
315 append=parser.append;
316
317 out=parser.out1;
318 if(vcf==null && out!=null){
319 if(ReadWrite.rawExtension(out).equals("vcf")){
320 vcf=out;
321 out=null;
322 }
323 }
324
325 extin=parser.extin;
326 extout=parser.extout;
327
328 qtrimLeft=parser.qtrimLeft;
329 qtrimRight=parser.qtrimRight;
330 trimq=parser.trimq;
331 trimE=parser.trimE();
332
333 trimWhitespace=Shared.TRIM_READ_COMMENTS;
334 }
335 if(vcf==null){Scaffold.setTrackStrand(false);}
336
337 ploidyArray=new long[ploidy+1];
338
339 assert(FastaReadInputStream.settingsOK());
340
341 //Ensure there is an input file
342 if(in.isEmpty()){throw new RuntimeException("Error - at least one input file is required.");}
343
344 //Adjust the number of threads for input file reading
345 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
346 ByteFile.FORCE_MODE_BF2=true;
347 }
348
349 //Ensure output files can be written
350 if(!Tools.testOutputFiles(overwrite, append, false, out, vcf, gffout)){
351 outstream.println((out==null)+", "+out);
352 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out+"\n");
353 }
354
355 in=Tools.fixExtension(in);
356 ref=Tools.fixExtension(ref);
357
358 //Ensure input files can be read
359 if(!Tools.testInputFiles(false, true, in.toArray(new String[0]))){
360 throw new RuntimeException("\nCan't read some input files.\n");
361 }
362
363 if(vcfin!=null && !Tools.testInputFiles(false, true, vcfin.split(","))){
364 throw new RuntimeException("\nCan't read vcfin: "+vcfin+"\n");
365 }
366
367 // //Ensure that no file was specified multiple times
368 // if(!Tools.testForDuplicateFiles(true, out, in.toArray(new String[0]))){
369 // throw new RuntimeException("\nSome file names were specified multiple times.\n");
370 // }
371
372 //Create output FileFormat objects
373 ffout=FileFormat.testOutput(out, FileFormat.VAR, extout, true, overwrite, append, true);
374
375 //Create input FileFormat objects
376 for(String s : in){
377 FileFormat ff=FileFormat.testInput(s, FileFormat.SAM, extin, true, false);
378 ffin.add(ff);
379 }
380
381 if(sampleName==null){
382 sampleName=ReadWrite.stripToCore(ffin.get(0).name());
383 }
384
385 assert(ref!=null) : "Please specify a reference fasta.";
386 }
387
388 /*--------------------------------------------------------------*/
389 /*---------------- Outer Methods ----------------*/
390 /*--------------------------------------------------------------*/
391
392 private void loadReference(){
393 if(loadedRef){return;}
394 assert(ref!=null);
395 scafMap=ScafMap.loadReference(ref, scafMap, samFilter, true);
396 if(realign){Realigner.map=scafMap;}
397 loadedRef=true;
398 }
399
400 private KCountArray7MTA prefilter(int minReads, VarMap vm){
401 int cbits=2;
402 while((1L<<cbits)-1<minReads){
403 cbits*=2;
404 }
405
406 long mem=Shared.memAvailable(4);
407 long prebits=mem; //1 bit per byte; 1/8th of the memory
408
409 long precells=prebits/cbits;
410 if(precells<100000){ //Not enough memory - no point.
411 return null;
412 }
413
414 KCountArray7MTA kca=new KCountArray7MTA(precells, cbits, 2, null, minReads);
415 if(!useStreamer || !useStreamerMF || ffin.size()<2 || Shared.threads()<5 || (maxReads>=0 && maxReads<Long.MAX_VALUE)){
416 prefilter_SF(kca);
417 }else{
418 prefilter_MF(kca);
419 }
420
421 if(vm!=null && vm.size()>0){//For forced vars from an input VCF
422 for(Var v : vm){
423 final long key=v.toKey();
424 kca.incrementAndReturnUnincremented(key, minReads);
425 }
426 }
427
428 kca.shutdown();
429 return kca;
430 }
431
432 private void prefilter_SF(final KCountArray7MTA kca){
433 for(FileFormat ff : ffin){
434
435 final SamReadStreamer ss;
436 //Create a read input stream
437 final ConcurrentReadInputStream cris;
438 if(useStreamer){
439 cris=null;
440 ss=new SamReadStreamer(ff, streamerThreads, false, maxReads);
441 ss.start();
442 if(verbose){outstream.println("Started streamer");}
443 }else{
444 ss=null;
445 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, false, ff, null);
446 cris.start(); //Start the stream
447 if(verbose){outstream.println("Started cris");}
448 }
449
450 final int threads=Shared.threads();
451
452 //Fill a list with ProcessThreads
453 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
454 for(int i=0; i<threads; i++){
455 alpt.add(new ProcessThread(cris, ss, null, i, kca, true));
456 }
457
458 //Start the threads
459 for(ProcessThread pt : alpt){
460 pt.start();
461 }
462
463 //Wait for completion of all threads
464 boolean success=true;
465 for(ProcessThread pt : alpt){
466
467 //Wait until this thread has terminated
468 while(pt.getState()!=Thread.State.TERMINATED){
469 try {
470 //Attempt a join operation
471 pt.join();
472 } catch (InterruptedException e) {
473 //Potentially handle this, if it is expected to occur
474 e.printStackTrace();
475 }
476 }
477 varsProcessed+=pt.varsProcessedT;
478
479 //Accumulate per-thread statistics
480 success&=pt.success;
481 }
482
483 //Track whether any threads failed
484 if(!success){errorState=true;}
485 }
486 }
487
488 private void prefilter_MF(final KCountArray7MTA kca){
489 SamStreamerMF ssmf=new SamStreamerMF(ffin.toArray(new FileFormat[0]), streamerThreads, false, maxReads);
490 ssmf.start();
491
492 final int threads=Shared.threads();
493
494 //Fill a list with ProcessThreads
495 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
496 for(int i=0; i<threads; i++){
497 alpt.add(new ProcessThread(null, null, ssmf, i, kca, true));
498 }
499
500 //Start the threads
501 for(ProcessThread pt : alpt){
502 pt.start();
503 }
504
505 //Wait for completion of all threads
506 boolean success=true;
507 for(ProcessThread pt : alpt){
508
509 //Wait until this thread has terminated
510 while(pt.getState()!=Thread.State.TERMINATED){
511 try {
512 //Attempt a join operation
513 pt.join();
514 } catch (InterruptedException e) {
515 //Potentially handle this, if it is expected to occur
516 e.printStackTrace();
517 }
518 }
519 varsProcessed+=pt.varsProcessedT;
520
521 //Accumulate per-thread statistics
522 success&=pt.success;
523 }
524
525 //Track whether any threads failed
526 if(!success){errorState=true;}
527 }
528
529 /** Create read streams and process all data */
530 public VarMap process(Timer t){
531
532 //Turn off read validation in the input threads to increase speed
533 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
534 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
535
536 //Reset counters
537 readsProcessed=0;
538 basesProcessed=0;
539 trimmedBasesProcessed=0;
540
541 Timer t2=new Timer();
542
543 if(ref!=null){
544 t2.start("Loading reference.");
545 loadReference();
546 t2.stop("Time: ");
547 }else{
548 for(FileFormat ff : ffin){
549 ScafMap.loadSamHeader(ff, scafMap);
550 }
551 }
552 varMap=new VarMap(scafMap);
553
554 if(vcfin!=null){//For forced vars from an input VCF
555 loadForcedVCF(vcfin);
556 }
557
558 final KCountArray7MTA kca;
559 if(prefilter){
560 t2.start("Loading the prefilter.");
561 kca=prefilter(varFilter.minAlleleDepth, vcfin==null ? null : varMap);
562 double used=(100.0*kca.cellsUsed())/kca.cells;
563 outstream.println("Added "+varsProcessed+" events to prefilter; approximately "+(long)(kca.estimateUniqueKmers(2))+" were unique.");
564 outstream.println(Tools.format("The prefilter is %.2f%% full.", used));
565 varsProcessed=0;
566 t2.stop("Time: ");
567 outstream.println();
568 }else{
569 kca=null;
570 }
571
572 t2.start("Processing input files.");
573
574 if(Shared.threads()>4 && useStreamer && useStreamerMF){
575 processInput_MF(ffin.toArray(new FileFormat[0]), kca);
576 }else{
577 for(FileFormat ff : ffin){
578 processInput_SF(ff, kca);
579 }
580 }
581 final double properPairRate=properlyPairedReadsProcessed/(double)Tools.max(1, readsProcessed-readsDiscarded);
582 final double pairedInSequencingRate=pairedInSequencingReadsProcessed/(double)Tools.max(1, readsProcessed-readsDiscarded);
583 final double totalQualityAvg=totalQualitySum/(double)Tools.max(1, trimmedBasesProcessed);
584 final double totalMapqAvg=totalMapqSum/(double)Tools.max(1, readsProcessed-readsDiscarded);
585 // System.err.println(properlyPairedReadsProcessed+", "+readsProcessed+", "+readsDiscarded);
586 varMap.ploidy=ploidy;
587 varMap.properPairRate=properPairRate;
588 varMap.pairedInSequencingRate=pairedInSequencingRate;
589 varMap.totalQualityAvg=totalQualityAvg;
590 varMap.totalMapqAvg=totalMapqAvg;
591 varMap.readLengthAvg=trimmedBasesProcessed/(double)Tools.max(1, readsProcessed-readsDiscarded);
592 t2.stop("Time: ");
593 Shared.printMemory();
594 outstream.println();
595
596 // assert(false) : filter.toString(properPairRate, ploidy);
597
598 long initialCount=varMap.size();
599
600 t2.start("Processing variants.");
601 final long[] types=processVariants();
602 t2.stop("Time: ");
603 outstream.println();
604
605 if(countNearbyVars){
606 t2.start("Counting nearby variants.");
607 int x=varMap.countNearbyVars(varFilter);
608 if(x>0 && varFilter.failNearby){
609 Arrays.fill(types, 0);
610 for(Var v : varMap.toArray(false)){
611 if(!v.forced() && v.nearbyVarCount>varFilter.maxNearbyCount){
612 varMap.removeUnsynchronized(v);
613 }else{
614 //TODO:
615 //Recalculate passing statistics
616 //Only relevant in failNearby mode... not really important.
617 }
618 }
619 }
620 t2.stop("Time: ");
621 outstream.println();
622 // assert(false) : varFilter.failNearby+", "+varFilter.maxNearbyCount;
623 }
624
625 if(ffout!=null || vcf!=null || gffout!=null || scoreHistFile!=null || zygosityHistFile!=null || qualityHistFile!=null){
626 // t2.start("Writing output.");
627 if(ffout!=null || vcf!=null || gffout!=null){
628 Timer t3=new Timer("Sorting variants.");
629 VcfWriter vw=new VcfWriter(varMap, varFilter, readsProcessed-readsDiscarded,
630 pairedInSequencingReadsProcessed, properlyPairedReadsProcessed,
631 trimmedBasesProcessed, ref, trimWhitespace, sampleName);
632 t3.stop("Time: ");
633 if(ffout!=null){
634 t3.start("Writing Var file.");
635 vw.writeVarFile(ffout);
636 t3.stop("Time: ");
637 }
638 if(vcf!=null){
639 t3.start("Writing VCF file.");
640 vw.writeVcfFile(vcf);
641 t3.stop("Time: ");
642 }
643 if(gffout!=null){
644 t3.start("Writing GFF file.");
645 vw.writeGffFile(gffout);
646 t3.stop("Time: ");
647 }
648 }
649 if(scoreHistFile!=null || zygosityHistFile!=null || qualityHistFile!=null){
650 Timer t3=new Timer("Writing histograms.");
651 if(scoreHistFile!=null){
652 writeScoreHist(scoreHistFile, scoreArray[0]);
653 }
654 if(zygosityHistFile!=null){
655 writeZygosityHist(zygosityHistFile, ploidyArray);
656 }
657 if(qualityHistFile!=null){
658 writeQualityHist(qualityHistFile, avgQualityArray[0], maxQualityArray);
659 }
660 t3.stop("Time: ");
661 }
662 // t2.stop("Output Time: ");
663 }
664
665 //Reset read validation
666 Read.VALIDATE_IN_CONSTRUCTOR=vic;
667
668 //Report timing and results
669 {
670 t.stop();
671
672 long size=scafMap.lengthSum();
673 long a=initialCount, b=varMap.size(), c=varsPrefiltered, d=varsProcessed;
674 double amult=100.0/a;
675 double bmult=100.0/b;
676 long homozygousCount=(ploidy<2 ? shared.Vector.sum(ploidyArray) : ploidyArray[ploidyArray.length-1]);
677 // System.err.println(Arrays.toString(ploidyArray));
678 double homozygousRate=homozygousCount*1.0/shared.Vector.sum(ploidyArray);
679 // outstream.println();
680 if(prefilter){
681 outstream.println(c+" of "+d+" events were screened by the prefilter ("+Tools.format("%.4f%%", c*100.0/d)+").");
682 }
683 outstream.println(b+" of "+a+" variants passed primary filters ("+Tools.format("%.4f%%", b*amult)+").");
684 outstream.println();
685 final long sub=types[Var.SUB], del=types[Var.DEL], ins=types[Var.INS];
686 final double smult=1.0/Tools.max(1, sub), dmult=1.0/Tools.max(1, del), imult=1.0/Tools.max(1, ins);
687 final long jun=types[Var.LJUNCT]+types[Var.RJUNCT]+types[Var.BJUNCT];
688 final double subAD=ADArray[0][Var.SUB]*smult, delAD=ADArray[0][Var.DEL]*dmult, insAD=ADArray[0][Var.INS]*imult;
689 final double subRD=ADArray[1][Var.SUB]*smult, delRD=ADArray[1][Var.DEL]*dmult, insRD=ADArray[1][Var.INS]*imult;
690 final double subAF=AFArray[Var.SUB]*smult, delAF=AFArray[Var.DEL]*dmult, insAF=AFArray[Var.INS]*imult;
691 final double subScore=Tools.sumHistogram(scoreArray[Var.SUB+1])*smult;
692 final double delScore=Tools.sumHistogram(scoreArray[Var.DEL+1])*dmult;
693 final double insScore=Tools.sumHistogram(scoreArray[Var.INS+1])*imult;
694 final double subQual=Tools.sumHistogram(avgQualityArray[Var.SUB+1])*smult;
695 final double delQual=Tools.sumHistogram(avgQualityArray[Var.DEL+1])*dmult;
696 final double insQual=Tools.sumHistogram(avgQualityArray[Var.INS+1])*imult;
697
698 outstream.println("Type \tCount\tRate\tAD\tDepth\tAF\tScore\tQual");
699 outstream.println("Substitutions: \t"+sub+Tools.format("\t%.1f%%\t%."+(subAD>1000 ? 0 : 1)+"f\t%."+(subRD>1000 ? 0 : 1)+"f\t%.3f\t%.1f\t%.1f",
700 sub*bmult, subAD, subRD, subAF, subScore, subQual));
701 outstream.println("Deletions: \t"+del+Tools.format("\t%.1f%%\t%."+(delAD>1000 ? 0 : 1)+"f\t%."+(delRD>1000 ? 0 : 1)+"f\t%.3f\t%.1f\t%.1f",
702 del*bmult, delAD, delRD, delAF, delScore, delQual));
703 outstream.println("Insertions: \t"+ins+Tools.format("\t%.1f%%\t%."+(insAD>1000 ? 0 : 1)+"f\t%."+(insRD>1000 ? 0 : 1)+"f\t%.3f\t%.1f\t%.1f",
704 ins*bmult, insAD, insRD, insAF, insScore, insQual));
705 if(var2.Var.CALL_JUNCTION){
706 outstream.println("Junctions: \t"+jun+Tools.format("\t%.1f%%", jun*bmult));
707 }
708 outstream.println("Variation Rate:\t"+(b==0 ? 0 : 1)+"/"+(size/Tools.max(1,b)));
709 outstream.println("Homozygous: \t"+homozygousCount+Tools.format("\t%.1f%%", homozygousRate*100)+"\n");
710
711 if(realign){
712 outstream.println("Realignments: \t"+realignmentsAttempted);
713 outstream.println("Successes: \t"+realignmentsSucceeded);
714 outstream.println("Improvements: \t"+realignmentsImproved);
715 outstream.println("Retained: \t"+realignmentsRetained);
716 outstream.println();
717 }
718
719 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
720 }
721
722 //Throw an exception of there was an error in a thread
723 if(errorState){
724 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
725 }
726
727 return varMap;
728 }
729
730 private VarMap loadForcedVCF(String fnames){
731 if(fnames==null){return null;}
732
733 Timer t2=new Timer(outstream, true);
734 // VarMap varMap=new VarMap(scafMap);
735 String[] array=(fnames.indexOf(',')>=0 ? fnames.split(",") : new String[] {fnames});
736 for(String fname : array){
737 FileFormat ff=FileFormat.testInput(fname, FileFormat.VCF, null, true, false);
738 VarMap varMap2=VcfLoader.loadFile(ff, scafMap, false, false);
739
740 for(Var v : varMap2){
741 v.clear();
742 v.setForced(true);
743 varMap.addUnsynchronized(v);
744 }
745 }
746
747 t2.stop("Vars: \t"+varMap.size()+"\nTime: ");
748 return varMap;
749 }
750
751 /** Create read streams and process all data */
752 void processInput_SF(FileFormat ff, KCountArray7MTA kca){
753 assert(ff.samOrBam());
754
755 final SamReadStreamer ss;
756 //Create a read input stream
757 final ConcurrentReadInputStream cris;
758 if(useStreamer){
759 cris=null;
760 ss=new SamReadStreamer(ff, streamerThreads, false, maxReads);
761 ss.start();
762 if(verbose){outstream.println("Started streamer");}
763 }else{
764 ss=null;
765 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, false, ff, null);
766 cris.start(); //Start the stream
767 if(verbose){outstream.println("Started cris");}
768 }
769
770 //Process the reads in separate threads
771 spawnThreads(cris, ss, null, kca);
772
773 if(verbose){outstream.println("Finished; closing streams.");}
774
775 //Close the read streams
776 errorState|=ReadWrite.closeStreams(cris);
777 }
778
779 /** Create read streams and process all data */
780 void processInput_MF(FileFormat[] ff, KCountArray7MTA kca){
781 assert(useStreamer);
782 assert(ff[0].samOrBam());
783
784 final SamStreamerMF ssmf;
785 assert(useStreamer);
786 ssmf=new SamStreamerMF(ff, streamerThreads, false, maxReads);
787 ssmf.start();
788 if(verbose){outstream.println("Started streamer");}
789
790 //Process the reads in separate threads
791 spawnThreads(null, null, ssmf, kca);
792
793 if(verbose){outstream.println("Finished; closing streams.");}
794 }
795
796 private long[] processVariants(){
797 return varMap.processVariantsMT(varFilter, scoreArray, ploidyArray, avgQualityArray, maxQualityArray, ADArray, AFArray);
798 }
799
800 /** Spawn process threads */
801 private void spawnThreads(final ConcurrentReadInputStream cris, final SamReadStreamer ss, final SamStreamerMF ssmf, final KCountArray7MTA kca){
802
803 //Do anything necessary prior to processing
804
805 //Determine how many threads may be used
806 final int threads=Shared.threads();
807
808 //Fill a list with ProcessThreads
809 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
810 for(int i=0; i<threads; i++){
811 alpt.add(new ProcessThread(cris, ss, ssmf, i, kca, false));
812 }
813
814 //Start the threads
815 for(ProcessThread pt : alpt){
816 pt.start();
817 }
818
819 //Wait for completion of all threads
820 boolean success=true;
821 for(ProcessThread pt : alpt){
822
823 //Wait until this thread has terminated
824 while(pt.getState()!=Thread.State.TERMINATED){
825 try {
826 //Attempt a join operation
827 pt.join();
828 } catch (InterruptedException e) {
829 //Potentially handle this, if it is expected to occur
830 e.printStackTrace();
831 }
832 }
833
834 //Accumulate per-thread statistics
835 readsProcessed+=pt.readsProcessedT;
836 basesProcessed+=pt.basesProcessedT;
837 trimmedBasesProcessed+=pt.trimmedBasesProcessedT;
838 readsDiscarded+=pt.readsDiscardedT;
839 pairedInSequencingReadsProcessed+=pt.pairedInSequencingReadsProcessedT;
840 properlyPairedReadsProcessed+=pt.properlyPairedReadsProcessedT;
841 varsPrefiltered+=pt.prefilteredT;
842 varsProcessed+=pt.varsProcessedT;
843 totalQualitySum+=pt.totalQualitySumT;
844 totalMapqSum+=pt.totalMapqSumT;
845 success&=pt.success;
846 if(pt.realigner!=null){
847 realignmentsAttempted+=pt.realigner.realignmentsAttempted;
848 realignmentsImproved+=pt.realigner.realignmentsImproved;
849 realignmentsSucceeded+=pt.realigner.realignmentsSucceeded;
850 realignmentsRetained+=pt.realigner.realignmentsRetained;
851 }
852 }
853
854 //Track whether any threads failed
855 if(!success){errorState=true;}
856 }
857
858 /*--------------------------------------------------------------*/
859 /*---------------- Inner Methods ----------------*/
860 /*--------------------------------------------------------------*/
861
862 private int dumpVars(HashMap<Var, Var> mapT){
863 int added=varMap.dumpVars(mapT);
864 assert(mapT.size()==0);
865 return added;
866 }
867
868 static boolean writeScoreHist(String fname, long[] array){
869 int max=array.length-1;
870 for(; max>=0; max--){
871 if(array[max]!=0){break;}
872 }
873 long sum=0, sum2=0;
874 for(int i=0; i<=max; i++){
875 sum+=array[i];
876 sum2+=(i*array[i]);
877 }
878 TextStreamWriter tsw=new TextStreamWriter(fname, true, false, false);
879 tsw.start();
880 tsw.println("#ScoreHist");
881 tsw.println("#Vars\t"+sum);
882 tsw.println("#Mean\t"+Tools.format("%.2f", sum2*1.0/sum));
883 tsw.println("#Median\t"+Tools.medianHistogram(array));
884 tsw.println("#Mode\t"+Tools.calcModeHistogram(array));
885 tsw.println("#Quality\tCount");
886 for(int i=0; i<=max; i++){
887 tsw.println(i+"\t"+array[i]);
888 }
889 tsw.poisonAndWait();
890 return tsw.errorState;
891 }
892
893 static boolean writeZygosityHist(String fname, long[] array){
894 int max=array.length-1;
895 long sum=0, sum2=0;
896 for(int i=0; i<=max; i++){
897 sum+=array[i];
898 sum2+=(i*array[i]);
899 }
900 TextStreamWriter tsw=new TextStreamWriter(fname, true, false, false);
901 tsw.start();
902 tsw.println("#ZygoHist");
903 tsw.println("#Vars\t"+sum);
904 tsw.println("#Mean\t"+Tools.format("%.3f", sum2*1.0/sum));
905 tsw.println("#HomozygousFraction\t"+Tools.format("%.3f", array[max]*1.0/sum));
906 tsw.println("#Zygosity\tCount");
907 for(int i=0; i<=max; i++){
908 tsw.println(i+"\t"+array[i]);
909 }
910 tsw.poisonAndWait();
911 return tsw.errorState;
912 }
913
914 static boolean writeQualityHist(String fname, long[] avgQualArray, long[] maxQualArray){
915 int max=avgQualArray.length-1;
916 for(; max>=0; max--){
917 if(avgQualArray[max]!=0 || maxQualArray[max]!=0){break;}
918 }
919 long avgsum=0, avgsum2=0;
920 for(int i=0; i<=max; i++){
921 avgsum+=avgQualArray[i];
922 avgsum2+=(i*avgQualArray[i]);
923 }
924 TextStreamWriter tsw=new TextStreamWriter(fname, true, false, false);
925 tsw.start();
926 tsw.println("#BaseQualityHist");
927 tsw.println("#Vars\t"+avgsum);
928 tsw.println("#Mean\t"+Tools.format("%.2f", avgsum2*1.0/avgsum));
929 tsw.println("#Median\t"+Tools.medianHistogram(avgQualArray));
930 tsw.println("#Mode\t"+Tools.calcModeHistogram(avgQualArray));
931 tsw.println("#Quality\tAvgCount\tMaxCount");
932 for(int i=0; i<=max; i++){
933 tsw.println(i+"\t"+avgQualArray[i]+"\t"+maxQualArray[i]);
934 }
935 tsw.poisonAndWait();
936 return tsw.errorState;
937 }
938
939 /*--------------------------------------------------------------*/
940 /*---------------- Inner Classes ----------------*/
941 /*--------------------------------------------------------------*/
942
943 /** This class is static to prevent accidental writing to shared variables.
944 * It is safe to remove the static modifier. */
945 private class ProcessThread extends Thread {
946
947 //Constructor
948 ProcessThread(final ConcurrentReadInputStream cris_, final SamReadStreamer ss_, final SamStreamerMF ssmf_,
949 final int tid_, final KCountArray7MTA kca_, final boolean prefilterOnly_){
950 cris=cris_;
951 ss=ss_;
952 ssmf=ssmf_;
953 tid=tid_;
954 kca=kca_;
955 prefilterOnly=prefilterOnly_;
956 realigner=(realign ? new Realigner() : null);
957 }
958
959 //Called by start()
960 @Override
961 public void run(){
962 //Do anything necessary prior to processing
963
964 //Process the reads
965 if(ss!=null){
966 processInner_ss();
967 }else if(cris!=null){
968 processInner_cris();
969 }else{
970 processInner_ssmf();
971 }
972
973 //Do anything necessary after processing
974 if(!varMapT.isEmpty()){
975 dumpVars(varMapT);
976 }
977 assert(varMapT.isEmpty());
978
979 //Indicate successful exit status
980 success=true;
981 }
982
983 /** Iterate through the reads */
984 void processInner_cris(){
985
986 //Grab the first ListNum of reads
987 ListNum<Read> ln=cris.nextList();
988 //Grab the actual read list from the ListNum
989 ArrayList<Read> reads=(ln!=null ? ln.list : null);
990
991 //Check to ensure pairing is as expected
992 if(reads!=null && !reads.isEmpty()){
993 Read r=reads.get(0);
994 // assert(ffin.samOrBam() || (r.mate!=null)==cris.properlyPaired()); //Disabled due to non-static access
995 }
996
997 //As long as there is a nonempty read list...
998 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
999 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
1000
1001 //Loop through each read in the list
1002 for(int idx=0; idx<reads.size(); idx++){
1003 final Read r=reads.get(idx);
1004 assert(r.mate==null);
1005
1006 if(!r.validated()){r.validate(true);}
1007
1008 //Track the initial length for statistics
1009 final int initialLength=r.length();
1010
1011 //Increment counters
1012 readsProcessedT++;
1013 basesProcessedT+=initialLength;
1014
1015 boolean b=processRead(r);
1016
1017 if(!b){
1018 readsDiscardedT++;
1019 }
1020 }
1021
1022 //Notify the input stream that the list was used
1023 cris.returnList(ln);
1024 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
1025
1026 //Fetch a new list
1027 ln=cris.nextList();
1028 reads=(ln!=null ? ln.list : null);
1029 }
1030
1031 //Notify the input stream that the final list was used
1032 if(ln!=null){
1033 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
1034 }
1035 }
1036
1037 /** Iterate through the reads */
1038 void processInner_ss(){
1039
1040 //Grab the actual read list from the ListNum
1041 ListNum<Read> ln=ss.nextList();
1042
1043 //As long as there is a nonempty read list...
1044 while(ln!=null && ln.size()>0){
1045 ArrayList<Read> reads=ln.list;
1046 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
1047
1048 //Loop through each read in the list
1049 for(int idx=0; idx<reads.size(); idx++){
1050 final Read r=reads.get(idx);
1051 assert(r.mate==null);
1052
1053 if(!r.validated()){r.validate(true);}
1054
1055 //Track the initial length for statistics
1056 final int initialLength=r.length();
1057
1058 //Increment counters
1059 readsProcessedT++;
1060 basesProcessedT+=initialLength;
1061
1062 boolean b=processRead(r);
1063 if(!b){
1064 readsDiscardedT++;
1065 }
1066 }
1067
1068 ln=ss.nextList();
1069 }
1070 }
1071
1072 /** Iterate through the reads */
1073 void processInner_ssmf(){
1074
1075 //Grab the actual read list from the ListNum
1076 ListNum<Read> ln=ssmf.nextList();
1077
1078 //As long as there is a nonempty read list...
1079 while(ln!=null && ln.size()>0){
1080 ArrayList<Read> reads=ln.list;
1081 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static accessmf
1082
1083 //Loop through each read in the list
1084 for(int idx=0; idx<reads.size(); idx++){
1085 final Read r=reads.get(idx);
1086 assert(r.mate==null);
1087
1088 if(!r.validated()){r.validate(true);}
1089
1090 //Track the initial length for statistics
1091 final int initialLength=r.length();
1092
1093 //Increment counters
1094 readsProcessedT++;
1095 basesProcessedT+=initialLength;
1096
1097 boolean b=processRead(r);
1098 if(!b){
1099 readsDiscardedT++;
1100 }
1101 }
1102
1103 ln=ssmf.nextList();
1104 }
1105 }
1106
1107 /**
1108 * Process a read.
1109 * @param r Read 1
1110 * @return True if the reads should be kept, false if they should be discarded.
1111 */
1112 boolean processRead(final Read r){
1113 if(r.bases==null || r.length()<=1){return false;}
1114 final SamLine sl=r.samline;
1115
1116 // System.err.println("A: "+sl);
1117
1118 // final SamLine oldSL=new SamLine(sl);
1119 // final Read oldRead=r.clone();
1120
1121 if(samFilter!=null && !samFilter.passesFilter(sl)){return false;}
1122
1123 if(sl.properPair()){properlyPairedReadsProcessedT++;}
1124 if(sl.hasMate()){pairedInSequencingReadsProcessedT++;}
1125 final Scaffold scaf=scafMap.getScaffold(sl);
1126 final int scafnum=scaf.number;
1127 // System.err.println("B: "+sl);
1128
1129 // r.toLongMatchString(false); //Not necessary since scoring can be done on short match string
1130 if(realign){
1131 realigner.realign(r, sl, scaf, unclip);
1132 }
1133
1134 //TODO ****** I am trimming of all left-clipping after this.
1135 //TODO Also, I'm adjusting the stop rather than start if on the revere strand!
1136 // assert(false) : new String(new String(r.match)+"\n"+r.start+"\n"+r.stop+"\n"+r.obj+"\n");
1137 // System.err.println(sl);
1138 // System.err.println(new String(r.match));
1139 // System.err.println("C: "+sl);
1140
1141 int leftTrimAmount=border, rightTrimAmount=border;
1142 if(border>0){
1143 int skipTrimRange=Tools.max(10, border+5);
1144 if(r.start<skipTrimRange){
1145 if(r.strand()==Shared.PLUS){leftTrimAmount=0;}
1146 else{rightTrimAmount=0;}
1147 }
1148 if(r.stop>scaf.length-skipTrimRange){
1149 if(r.strand()==Shared.PLUS){rightTrimAmount=0;}
1150 else{leftTrimAmount=0;}
1151 }
1152 }
1153 if(qtrimLeft || qtrimRight){
1154 long packed=TrimRead.testOptimal(r.bases, r.quality, trimE);
1155 if(qtrimLeft){leftTrimAmount=Tools.max(leftTrimAmount, (int)((packed>>32)&0xFFFFFFFFL));}
1156 if(qtrimRight){rightTrimAmount=Tools.max(rightTrimAmount, (int)((packed)&0xFFFFFFFFL));}
1157 }
1158 // System.err.println("D: "+sl);
1159
1160 int trimmed=(leftTrimAmount<1 && rightTrimAmount<1 ? 0 : TrimRead.trimReadWithMatch(r, sl, leftTrimAmount, rightTrimAmount, 0, scaf.length, false));
1161 if(trimmed<0){return false;}//In this case the whole read should be trimmed
1162 int extra=(qtrimLeft || qtrimRight) ? trimmed/2 : Tools.min(border, trimmed/2);
1163 // System.err.println(sl);
1164 // System.err.println(new String(r.match));
1165 // System.err.println(border+", "+leftTrimAmount+", "+rightTrimAmount+", "+trimmed);
1166 // System.err.println("E: "+sl);
1167
1168 //TODO
1169 //assert(false) : new String(new String(r.match)+"\n"+r.start+"\n"+r.stop+"\n"+r.obj+"\n");
1170 ArrayList<Var> vars=null;
1171 // try {
1172 vars = Var.toVars(r, sl, callNs, scafnum);
1173 // } catch (Throwable e) {
1174 // // TODO Auto-generated catch block
1175 // System.err.println("Bad line:");
1176 // System.err.println(oldRead.toString());
1177 // System.err.println(r.toString());
1178 // System.err.println(oldSL.toString());
1179 // System.err.println(sl.toString());
1180 // System.err.println("\n");
1181 // }
1182
1183 if(prefilterOnly){
1184 if(vars==null){return true;}
1185 for(Var v : vars){
1186 long key=v.toKey();
1187 kca.increment(key);
1188 }
1189 }else{
1190 trimmedBasesProcessedT+=r.length();
1191 totalQualitySumT+=shared.Vector.sum(r.quality);
1192 totalMapqSumT+=sl.mapq;
1193 if(calcCoverage){scaf.add(sl);}
1194 if(vars==null){return true;}
1195
1196 for(Var v : vars){
1197 // assert(false) : v.alleleCount();
1198 int depth=Integer.MAX_VALUE;
1199 if(kca!=null){
1200 depth=kca.read(v.toKey());
1201 }
1202 if(depth>=varFilter.minAlleleDepth){
1203 v.endDistMax+=extra;
1204 v.endDistSum+=extra;
1205
1206 Var old=varMapT.get(v);
1207 if(old==null){varMapT.put(v, v);}
1208 else{old.add(v);}
1209 }else{
1210 prefilteredT++;
1211 }
1212 }
1213 if(varMapT.size()>vmtSizeLimit){
1214 dumpVars(varMapT);
1215 }
1216 }
1217 varsProcessedT+=vars.size();
1218 return true;
1219 }
1220
1221 private final KCountArray7MTA kca;
1222 private final boolean prefilterOnly;
1223
1224 /** Number of vars blocked by the prefilter */
1225 protected long prefilteredT=0;
1226 /** Number of vars processed */
1227 protected long varsProcessedT=0;
1228
1229 /** Sum of trimmed, mapped base qualities */
1230 protected long totalQualitySumT=0;
1231 /** Sum of mapqs */
1232 protected long totalMapqSumT=0;
1233
1234 /** Number of reads processed by this thread */
1235 protected long readsProcessedT=0;
1236 /** Number of bases processed by this thread */
1237 protected long basesProcessedT=0;
1238 /** Number of trimmed, mapped bases processed. */
1239 protected long trimmedBasesProcessedT=0;
1240 /** Number of reads discarded by this thread */
1241 protected long readsDiscardedT=0;
1242 /** Number of paired reads processed by this thread, whether or not they mapped as pairs */
1243 protected long pairedInSequencingReadsProcessedT=0;
1244 /** Number of properly paired reads processed by this thread */
1245 protected long properlyPairedReadsProcessedT=0;
1246
1247 /** True only if this thread has completed successfully */
1248 boolean success=false;
1249
1250 HashMap<Var, Var> varMapT=new HashMap<Var, Var>();
1251
1252 /** Shared input stream */
1253 private final ConcurrentReadInputStream cris;
1254 /** Optional SamReadStreamer for high throughput */
1255 private final SamReadStreamer ss;
1256 /** Optional SamStreamerMF for very high throughput */
1257 private final SamStreamerMF ssmf;
1258 /** For realigning reads */
1259 final Realigner realigner;
1260
1261 /** Thread ID */
1262 final int tid;
1263 }
1264
1265 // public int fixVars(Read r, SamLine sl){
1266 // return fixVars(r, sl, varMap, scafMap);
1267 // }
1268
1269 public static int fixVars(Read r, VarMap varMap, ScafMap scafMap){
1270 if(r==null || r.bases==null || r.match==null || r.samline==null){return 0;}
1271 final SamLine sl=r.samline;
1272 if(!sl.mapped()){return 0;}
1273 return fixVars(r, sl, varMap, scafMap);
1274 }
1275
1276 public static void unfixVars(Read r){
1277 if(r==null || r.match==null){return;}
1278 for(int i=0; i<r.match.length; i++){
1279 if(r.match[i]=='V'){r.match[i]='S';}
1280 else if(r.match[i]=='i'){r.match[i]='I';}
1281 else if(r.match[i]=='d'){r.match[i]='D';}
1282 }
1283 }
1284
1285 public static int fixVars(Read r, SamLine sl, VarMap varMap, ScafMap scafMap){
1286 if(r==null || r.bases==null || r.match==null){return 0;}
1287 assert(r.mapped());
1288
1289 // if(!Read.containsSubs(r.match)){return 0;}
1290 if(!Read.containsVars(r.match)){return 0;}
1291 final int scafnum=scafMap.getNumber(sl.rnameS());
1292 assert(scafnum>=0) : "Can't find scaffold "+sl.rnameS();
1293 if(scafnum<0){return 0;}
1294 // System.err.println("A");
1295
1296 if(r.match!=null && r.shortmatch()){
1297 r.toLongMatchString(false);
1298 }
1299 int varsFound=0;
1300 final byte[] match=r.match;
1301 final byte[] bases=r.bases;
1302
1303 final boolean rcomp=(r.strand()==Shared.MINUS);
1304 if(rcomp){r.reverseComplement();}
1305
1306 int rpos=sl.pos-1-SamLine.countLeadingClip(sl.cigar, true, true);
1307
1308 // System.err.println("varMap: \n"+varMap+"\n\n");
1309 byte prev='?';
1310 for(int bpos=0, mpos=0; mpos<match.length; mpos++){
1311 final byte m=match[mpos];
1312 assert(bpos<bases.length) : new String(match);
1313 final byte b=bases[bpos];
1314
1315 if(m=='S'){
1316 Var v=new Var(scafnum, rpos, rpos+1, b, Var.SUB);
1317 if(varMap.containsKey(v)){
1318 varsFound++;
1319 match[mpos]='V';
1320 // System.err.println("Found "+v+"\n");
1321 // }else{
1322 // System.err.println("Can't find "+v+" in\n"+varMap+"\n");
1323 }
1324 }else if(fixIndels && prev!=m && (m=='I' || m=='D')){
1325 int len=0;
1326 for(int i=mpos; i<match.length; i++){
1327 if(match[i]==m){len++;}else{break;}
1328 }
1329 byte replacement=Tools.toLowerCase(m);
1330 Var v;
1331 if(m=='D'){v=new Var(scafnum, rpos, rpos+len+1, 0, Var.DEL);}//Check the +1; may not be right
1332 else{
1333 byte[] alt=(len==1 ? Var.AL_MAP[b] : Arrays.copyOfRange(bases, bpos, bpos+len));
1334 v=new Var(scafnum, rpos, rpos, alt, Var.INS);
1335 }
1336 if(varMap.containsKey(v)){
1337 varsFound++;
1338 for(int i=mpos; i<match.length; i++){
1339 if(match[i]==m){match[i]=replacement;}else{break;}
1340 }
1341 // System.err.println("Found "+v+"\n");
1342 // }else{
1343 // System.err.println("Can't find "+v+" in\n"+varMap+"\n");
1344 }
1345 }
1346
1347 if(m!='D' && m!='d'){bpos++;}
1348 if(m!='I' && m!='i'){rpos++;}
1349 prev=m;
1350 }
1351 if(rcomp){r.reverseComplement();}
1352
1353 // assert(false) : new String(r.match);
1354
1355 // System.err.println("B:"+varsFound);
1356 return varsFound;
1357 }
1358
1359 public static ArrayList<Var> findUniqueSubs(Read r, SamLine sl, VarMap varMap, ScafMap scafMap, int maxVarDepth, float maxAlleleFraction, int minCov, int minEDist){
1360 if(r==null || r.bases==null || r.match==null){return null;}
1361 assert(r.mapped());
1362
1363 final int subs=Read.countSubs(r.match);
1364 if(subs==0){return null;}
1365
1366 final int scafnum=scafMap.getNumber(sl.rnameS());
1367 assert(scafnum>=0) : "Can't find scaffold "+sl.rnameS();
1368
1369 if(r.match!=null && r.shortmatch()){r.toLongMatchString(false);}
1370
1371 final boolean rcomp=(r.strand()==Shared.MINUS);
1372 if(rcomp){r.reverseComplement();}
1373
1374 final byte[] match=r.match;
1375 final byte[] bases=r.bases;
1376 final ArrayList<Var> list=new ArrayList<Var>(subs);
1377
1378 int rpos=sl.pos-1-SamLine.countLeadingClip(sl.cigar, true, true);
1379 int subsFound=0;
1380 for(int qpos=0, mpos=0; mpos<match.length; mpos++){
1381 final byte m=match[mpos];
1382 final byte b=bases[qpos];
1383
1384 if(m=='S' && scafnum>=0){
1385 subsFound++;
1386 if(qpos>=minEDist && qpos<bases.length-minEDist){
1387 Var v=new Var(scafnum, rpos, rpos+1, b, Var.SUB);
1388 Var old=varMap.get(v);
1389 if(old==null){
1390 list.add(v);
1391 }else if(old.hasCoverage()){
1392 if(old.coverage()>=minCov){
1393 if(old.alleleCount()<=maxVarDepth || (maxAlleleFraction>0 && old.alleleFraction()<=maxAlleleFraction)){
1394 list.add(old);
1395 }
1396 }
1397 }else{
1398 if(old.alleleCount()<=maxVarDepth){list.add(old);}
1399 }
1400 }
1401 }
1402
1403 if(m!='D'){qpos++;}
1404 if(m!='I'){rpos++;}
1405 }
1406 assert(subs==subsFound) : subs+", "+subsFound+", "+Read.countSubs(r.match)+"\n"+new String(match)+"\n"+new String(Read.toShortMatchString(r.match));
1407 if(rcomp){r.reverseComplement();}
1408 return list.isEmpty() ? null : list;
1409 }
1410
1411 public static ArrayList<Var> findUniqueVars(Read r, SamLine sl, VarMap varMap, ScafMap scafMap, int maxVarDepth, float maxAlleleFraction, int minCov, int minEDist){
1412 if(r==null || r.bases==null || r.match==null){return null;}
1413 assert(r.mapped());
1414
1415 final int vars=Read.countVars(r.match, Var.CALL_SUB, Var.CALL_INS, Var.CALL_DEL);
1416 if(vars==0){return null;}
1417
1418 final int scafnum=scafMap.getNumber(sl.rnameS());
1419 assert(scafnum>=0) : "Can't find scaffold "+sl.rnameS();
1420
1421 if(r.match!=null && r.shortmatch()){r.toLongMatchString(false);}
1422
1423 final boolean rcomp=(r.strand()==Shared.MINUS);
1424 if(rcomp){
1425 r.reverseComplement();
1426 r.setSwapped(true);
1427 }
1428
1429 final ArrayList<Var> list=Var.toVars(r, sl, false, scafMap);
1430 ArrayList<Var> list2=new ArrayList<Var>();
1431 for(Var v : list){
1432 if(v.endDistMax>=minEDist){
1433 Var old=varMap.get(v);
1434 if(old==null){
1435 list2.add(v);
1436 }else if(old.hasCoverage()){
1437 if(old.coverage()>=minCov){
1438 if(old.alleleCount()<=maxVarDepth || (maxAlleleFraction>0 && old.alleleFraction()<=maxAlleleFraction)){
1439 list2.add(old);
1440 }
1441 }
1442 }else{
1443 if(old.alleleCount()<=maxVarDepth){list2.add(old);}
1444 }
1445 }
1446 }
1447 if(rcomp){
1448 r.reverseComplement();
1449 r.setSwapped(false);
1450 }
1451 return list2.isEmpty() ? null : list2;
1452 }
1453
1454 /*--------------------------------------------------------------*/
1455 /*---------------- Fields ----------------*/
1456 /*--------------------------------------------------------------*/
1457
1458 /** Primary input file path */
1459 private ArrayList<String> in=new ArrayList<String>();
1460
1461 /** Primary output file path */
1462 private String out=null;
1463
1464 /** VCF output file path */
1465 private String vcf=null;
1466
1467 /** VCF input file path for forced variants */
1468 private String vcfin=null;
1469
1470 /** GFF output file path */
1471 private String gffout=null;
1472
1473 /** GFF input file path */
1474 private String gffin=null;
1475
1476 private String scoreHistFile=null;
1477 private String zygosityHistFile=null;
1478 private String qualityHistFile=null;
1479
1480 /** Override input file extension */
1481 private String extin=null;
1482 /** Override output file extension */
1483 private String extout=null;
1484 /** A fasta file. */
1485 private String ref=null;
1486
1487 private boolean loadedRef=false;
1488
1489 private boolean qtrimLeft=false;
1490 private boolean qtrimRight=true;
1491 private float trimq=10;
1492 private final float trimE;
1493
1494 /*--------------------------------------------------------------*/
1495
1496 /** Number of reads processed */
1497 protected long readsProcessed=0;
1498 /** Number of bases processed */
1499 protected long basesProcessed=0;
1500 /** Number of trimmed, mapped bases processed */
1501 protected long trimmedBasesProcessed=0;
1502 /** Number of reads discarded */
1503 protected long readsDiscarded=0;
1504 /** Number of paired reads processed by this thread, whether or not they mapped as pairs */
1505 protected long pairedInSequencingReadsProcessed=0;
1506 /** Number of properly paired reads processed */
1507 protected long properlyPairedReadsProcessed=0;
1508 /** Number of vars ignored via prefilter */
1509 protected long varsPrefiltered=0;
1510 /** Number of vars processed */
1511 protected long varsProcessed=0;
1512
1513 /** Sum of trimmed, mapped base qualities */
1514 protected long totalQualitySum=0;
1515 /** Sum of mapqs */
1516 protected long totalMapqSum=0;
1517
1518 protected long realignmentsAttempted;
1519 protected long realignmentsImproved;
1520 protected long realignmentsSucceeded;
1521 protected long realignmentsRetained;
1522
1523 /** Quit after processing this many input reads; -1 means no limit */
1524 private long maxReads=-1;
1525
1526 public ScafMap scafMap;
1527 public VarMap varMap;
1528
1529 public boolean calcCoverage=true;
1530
1531 public int ploidy=-1;
1532
1533 public int border=5;
1534
1535 public boolean realign=false;
1536 public boolean unclip=false;
1537
1538 public boolean prefilter=false;
1539
1540 public String sampleName=null;
1541
1542 /*
1543 * These cover junk due to artifacts, misassemblies, or structural variants,
1544 * which generally result in a rainbow of adjacent SNPs.
1545 * Some fields are in VarFilter.
1546 */
1547 public boolean countNearbyVars=true;
1548
1549 /*--------------------------------------------------------------*/
1550 /*---------------- Final Fields ----------------*/
1551 /*--------------------------------------------------------------*/
1552
1553 /** Primary input file */
1554 private final ArrayList<FileFormat> ffin=new ArrayList<FileFormat>();
1555
1556 /** Primary output file */
1557 private final FileFormat ffout;
1558
1559 public final VarFilter varFilter=new VarFilter();
1560 public final SamFilter samFilter=new SamFilter();
1561 public final long[][] scoreArray=new long[8][200];
1562 public final long[] ploidyArray;
1563 public final long[][] avgQualityArray=new long[8][100];
1564 public final long[] maxQualityArray=new long[100];
1565 public final long[][] ADArray=new long[2][7];
1566 public final double[] AFArray=new double[7];
1567
1568 /*--------------------------------------------------------------*/
1569 /*---------------- Static Fields ----------------*/
1570 /*--------------------------------------------------------------*/
1571
1572 private static int vmtSizeLimit=10000;
1573
1574 static boolean callNs=false;
1575 static boolean trimWhitespace=true;
1576 public static boolean fixIndels=true;
1577
1578 static boolean useStreamer=true;
1579 static boolean useStreamerMF=true;
1580 static int streamerThreads=SamStreamer.DEFAULT_THREADS;
1581
1582 /*--------------------------------------------------------------*/
1583 /*---------------- Common Fields ----------------*/
1584 /*--------------------------------------------------------------*/
1585
1586 /** Print status messages to this output stream */
1587 private PrintStream outstream=System.err;
1588 /** Print verbose messages */
1589 public static boolean verbose=false;
1590 /** True if an error was encountered */
1591 public boolean errorState=false;
1592 /** Overwrite existing output files */
1593 private boolean overwrite=true;
1594 /** Append to existing output files */
1595 private boolean append=false;
1596
1597 }