Debian Codegraph @

current/var2/CallVariants2.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.HashMap;
7 import java.util.HashSet;
8
9 import bloom.KCountArray7MTA;
10 import fileIO.ByteFile;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import fileIO.TextFile;
14 import shared.Parse;
15 import shared.Parser;
16 import shared.PreParser;
17 import shared.Shared;
18 import shared.Timer;
19 import shared.Tools;
20 import shared.TrimRead;
21 import stream.ConcurrentReadInputStream;
22 import stream.FastaReadInputStream;
23 import stream.Read;
24 import stream.SamLine;
25 import stream.SamReadStreamer;
26 import stream.SamStreamer;
27 import structures.ListNum;
28
29 /**
30 * Calls variants from one or more sam or bam files.
31 *
32 * @author Brian Bushnell
33 * @date December 18, 2016
34 *
35 */
36 public class CallVariants2 {
37
38 /*--------------------------------------------------------------*/
39 /*---------------- Initialization ----------------*/
40 /*--------------------------------------------------------------*/
41
42 /**
43 * Code entrance from the command line.
44 * @param args Command line arguments
45 */
46 public static void main(String[] args){
47 //Start a timer immediately upon code entrance.
48 Timer t=new Timer();
49
50 //Create an instance of this class
51 CallVariants2 x=new CallVariants2(args);
52
53 //Run the object
54 x.process(t);
55
56 //Close the print stream if it was redirected
57 Shared.closeStream(x.outstream);
58 }
59
60 /**
61 * Constructor.
62 * @param args Command line arguments
63 */
64 public CallVariants2(String[] args){
65
66 {//Preparse block for help, config files, and outstream
67 PreParser pp=new PreParser(args, getClass(), false);
68 args=pp.args;
69 outstream=pp.outstream;
70 }
71
72 SamLine.PARSE_0=false;
73 // SamLine.PARSE_2=false;
74 // SamLine.PARSE_5=false;
75 // SamLine.PARSE_6=false;
76 // SamLine.PARSE_7=false;
77 SamLine.PARSE_8=false;
78 // SamLine.PARSE_10=false;
79 // SamLine.PARSE_OPTIONAL=false;
80 SamLine.PARSE_OPTIONAL_MD_ONLY=true; //I only need the MD tag..
81
82 SamLine.RNAME_AS_BYTES=false;
83
84 //Set shared static variables
85 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
86 ReadWrite.setZipThreads(Shared.threads());
87 ReadWrite.USE_BGZIP=true;
88
89 //Create a parser object
90 Parser parser=new Parser();
91 parser.qtrimLeft=qtrimLeft;
92 parser.qtrimRight=qtrimRight;
93 parser.trimq=trimq;
94 Shared.TRIM_READ_COMMENTS=Shared.TRIM_RNAME=true;
95
96 samFilter.includeUnmapped=false;
97 samFilter.includeSupplimentary=false;
98 samFilter.includeDuplicate=false;
99 samFilter.includeNonPrimary=false;
100 samFilter.includeQfail=false;
101 samFilter.minMapq=4;
102 String atomic="auto";
103
104 //Parse each argument
105 for(int i=0; i<args.length; i++){
106 String arg=args[i];
107
108 //Break arguments into their constituent parts, in the form of "a=b"
109 String[] split=arg.split("=");
110 String a=split[0].toLowerCase();
111 String b=split.length>1 ? split[1] : null;
112
113 if(a.equals("verbose")){
114 verbose=Parse.parseBoolean(b);
115 }else if(a.equals("multi") || a.equals("multisample")){
116 boolean multi=Parse.parseBoolean(b);
117 assert(multi) : "\nThis program is for multisample variant calling. Please use CallVariants for single-sample variant calling.\n";
118 }else if(a.equals("ploidy")){
119 ploidy=Integer.parseInt(b);
120 }else if(a.equals("parse_flag_goes_here")){
121 long fake_variable=Parse.parseKMG(b);
122 //Set a variable here
123 }else if(a.equals("ss") || a.equals("samstreamer")){
124 if(b!=null && Tools.isDigit(b.charAt(0))){
125 useStreamer=true;
126 streamerThreads=Tools.max(1, Integer.parseInt(b));
127 }else{
128 useStreamer=Parse.parseBoolean(b);
129 }
130 }else if(a.equals("parsename")){
131 SamLine.PARSE_0=Parse.parseBoolean(b);
132 }else if(a.equalsIgnoreCase("noPassDotGenotype") || a.equalsIgnoreCase("noPassDot")){
133 Var.noPassDotGenotype=Parse.parseBoolean(b);
134 }else if(a.equalsIgnoreCase("minVarCopies")){
135 Var.MIN_VAR_COPIES=Integer.parseInt(b);
136 }else if(a.equals("extended")){
137 Var.extendedText=Parse.parseBoolean(b);
138 }else if(a.equals("useidentity")){
139 Var.useIdentity=Parse.parseBoolean(b);
140 }else if(a.equals("usehomopolymer") || a.equals("homopolymer")){
141 Var.useHomopolymer=Parse.parseBoolean(b);
142 }else if(a.equals("usepairing")){
143 Var.usePairing=Parse.parseBoolean(b);
144 }else if(a.equals("usebias")){
145 Var.useBias=Parse.parseBoolean(b);
146 }else if(a.equals("nscan") || a.equals("donscan")){
147 Var.doNscan=Parse.parseBoolean(b);
148 }else if(a.equals("useedist")){
149 Var.useEdist=Parse.parseBoolean(b);
150 }else if(a.equals("prefilter")){
151 prefilter=Parse.parseBoolean(b);
152 }else if(a.equals("ref")){
153 ref=b;
154 }else if(a.equals("vcf") || a.equals("vcfout") || a.equals("outvcf") || a.equals("out")){
155 vcf=b;
156 }else if(a.equals("vcf0") || a.equals("vcfout0") || a.equals("outvcf0")){
157 vcf0=b;
158 }else if(a.equals("invcf") || a.equals("vcfin")){
159 vcfin=b;
160 }else if(a.equals("scorehist") || a.equals("qualhist") || a.equals("qhist") || a.equals("shist")){
161 scoreHistFile=b;
162 }else if(a.equals("border")){
163 border=Integer.parseInt(b);
164 }else if(a.equals("sample") || a.equals("samplename")){
165 assert(b!=null) : "Bad parameter: "+arg;
166 if(new File(b).exists()){sampleNames.add(b);}
167 else{
168 for(String s : b.split(",")){sampleNames.add(s);}
169 }
170 }
171
172 else if(a.equals("ca3") || a.equals("32bit")){
173 Scaffold.setCA3(Parse.parseBoolean(b));
174 }else if(a.equals("atomic")){
175 atomic=b;
176 }else if(a.equals("strandedcov") || a.equals("trackstrand")){
177 Scaffold.setTrackStrand(Parse.parseBoolean(b));
178 }
179
180 else if(a.equals("realign")){
181 realign=Parse.parseBoolean(b);
182 }else if(a.equals("unclip")){
183 unclip=Parse.parseBoolean(b);
184 }else if(a.equals("realignrows") || a.equals("rerows")){
185 Realigner.defaultMaxrows=Integer.parseInt(b);
186 }else if(a.equals("realigncols") || a.equals("recols")){
187 Realigner.defaultColumns=Integer.parseInt(b);
188 }else if(a.equals("realignpadding") || a.equals("repadding") || a.equals("padding")){
189 Realigner.defaultPadding=Integer.parseInt(b);
190 }else if(a.equals("msa")){
191 Realigner.defaultMsaType=b;
192 }
193
194 else if(samFilter.parse(arg, a, b)){
195 //do nothing
196 }
197
198 else if(a.equalsIgnoreCase("countNearbyVars")){
199 countNearbyVars=Parse.parseBoolean(b);
200 }
201
202 else if(a.equals("in") || a.equals("in1") || a.equals("in2")){
203 assert(b!=null) : "Bad parameter: "+arg;
204 if(new File(b).exists()){in.add(b);}
205 else{
206 for(String s : b.split(",")){in.add(s);}
207 }
208 }else if(a.equals("list")){
209 for(String line : TextFile.toStringLines(b)){
210 in.add(line);
211 }
212 }else if(a.equals("clearfilters")){
213 if(Parse.parseBoolean(b)){
214 varFilter.clear();
215 samFilter.clear();
216 }
217 }else if(varFilter.parse(a, b, arg)){
218 //do nothing
219 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
220 //do nothing
221 }else if(arg.indexOf('=')<0 && (new File(arg).exists() || arg.indexOf(',')>0)){
222 if(new File(arg).exists()){
223 if(FileFormat.isSamOrBamFile(arg)){
224 in.add(arg);
225 }else if(FileFormat.isFastaFile(arg) && (ref==null || ref.equals(arg))){
226 ref=arg;
227 }else{
228 assert(false) : "Unknown parameter "+arg;
229 outstream.println("Warning: Unknown parameter "+arg);
230 }
231 }else{
232 for(String s : arg.split(",")){
233 if(FileFormat.isSamOrBamFile(s)){
234 in.add(s);
235 }else{
236 assert(false) : "Unknown parameter "+arg+" part "+s;
237 outstream.println("Warning: Unknown parameter "+arg+" part "+s);
238 }
239 }
240 }
241 }else{
242 outstream.println("Unknown parameter "+args[i]);
243 assert(false) : "Unknown parameter "+args[i];
244 }
245 }
246
247 if("auto".equalsIgnoreCase(atomic)){Scaffold.setCA3A(Shared.threads()>8);}
248 else{Scaffold.setCA3A(Parse.parseBoolean(atomic));}
249
250 if(ploidy<1){System.err.println("WARNING: ploidy not set; assuming ploidy=1."); ploidy=1;}
251 samFilter.setSamtoolsFilter();
252
253 {//Process parser fields
254 Parser.processQuality();
255
256 maxReads=parser.maxReads;
257 overwrite=parser.overwrite;
258
259 extin=parser.extin;
260 extout=parser.extout;
261
262 qtrimLeft=parser.qtrimLeft;
263 qtrimRight=parser.qtrimRight;
264 trimq=parser.trimq;
265 trimE=parser.trimE();
266
267 trimWhitespace=Shared.TRIM_READ_COMMENTS;
268 }
269 if(vcf==null){Scaffold.setTrackStrand(false);}
270
271 assert(FastaReadInputStream.settingsOK());
272
273 ploidyArray=new long[ploidy+1];
274
275 //Ensure there is an input file
276 if(in.isEmpty()){throw new RuntimeException("Error - at least one input file is required.");}
277
278 //Adjust the number of threads for input file reading
279 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
280 ByteFile.FORCE_MODE_BF2=true;
281 }
282
283 //Ensure output files can be written
284 if(!Tools.testOutputFiles(overwrite, false, false, vcf)){
285 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+vcf+"\n");
286 }
287
288 //Ensure input files can be read
289 if(!Tools.testInputFiles(false, true, in.toArray(new String[0]))){
290 throw new RuntimeException("\nCan't read some input files.\n");
291 }
292
293 if(vcfin!=null && !Tools.testInputFiles(false, true, vcfin.split(","))){
294 throw new RuntimeException("\nCan't read vcfin: "+vcfin+"\n");
295 }
296
297 //Create input FileFormat objects
298 for(String s : in){
299 FileFormat ff=FileFormat.testInput(s, FileFormat.SAM, extin, true, false);
300 ffin.add(ff);
301 }
302
303 fixSampleNames();
304 assert(sampleNames.size()==in.size()) : "Number of sample names and file names must match.";
305
306 assert(ref!=null) : "Please specify a reference fasta.";
307 }
308
309 private VarMap loadForcedVCF(String fnames){
310 if(fnames==null){return null;}
311
312 Timer t2=new Timer(outstream, true);
313 VarMap varMap=new VarMap(scafMap);
314 String[] array=(fnames.indexOf(',')>=0 ? fnames.split(",") : new String[] {fnames});
315 for(String fname : array){
316 FileFormat ff=FileFormat.testInput(fname, FileFormat.VCF, null, true, false);
317 VarMap varMap2=VcfLoader.loadFile(ff, scafMap, false, false);
318
319 for(Var v : varMap2){
320 v.clear();
321 v.setForced(true);
322 varMap.addUnsynchronized(v);
323 }
324 }
325
326 t2.stop("Vars: \t"+varMap.size()+"\nTime: ");
327 return varMap;
328 }
329
330 private void fixSampleNames(){
331 if(sampleNames.size()!=0){assert(sampleNames.size()==in.size()) : "Different number of input files ("+in.size()+") and sample names ("+sampleNames.size()+")";}
332 if(sampleNames.size()==0){
333 HashMap<String, Integer> map=new HashMap<String, Integer>();
334 for(String s : in){
335 String core=ReadWrite.stripToCore(s);
336 if(map.containsKey(core)){
337 int x=map.get(core)+1;
338 map.put(core, x);
339 sampleNames.add(core+"_copy_"+x);
340 }else{
341 map.put(core, 1);
342 sampleNames.add(core);
343 }
344 }
345 }
346
347 // assert(false) : sampleNames;
348 assert(sampleNames.size()==in.size()) : "Different number of input files ("+in.size()+") and sample names ("+sampleNames.size()+")";
349
350 HashSet<String> set=new HashSet<String>();
351 for(String s : sampleNames){
352 assert(!set.contains(s)) : "Duplicate sample name "+s;
353 set.add(s);
354 }
355 }
356
357 /*--------------------------------------------------------------*/
358 /*---------------- Outer Methods ----------------*/
359 /*--------------------------------------------------------------*/
360
361 private void loadReference(){
362 if(loadedRef){return;}
363 assert(ref!=null);
364 scafMap=ScafMap.loadReference(ref, scafMap, samFilter, true);
365 if(realign){Realigner.map=scafMap;}
366 loadedRef=true;
367 }
368
369 /** Create read streams and process all data */
370 public void process(Timer t){
371
372 //Turn off read validation in the input threads to increase speed
373 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
374 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
375
376 Timer t2=new Timer();
377
378 if(ref!=null){
379 loadReference();
380 }
381
382 forcedVars2=new VarMap(scafMap);
383 if(vcfin!=null){
384 forcedVars1=loadForcedVCF(vcfin);
385 for(Var v : forcedVars1){
386 forcedVars2.addUnsynchronized(v.clone());
387 }
388 }
389
390 ArrayList<Sample> samples=new ArrayList<Sample>(ffin.size());
391
392 for(int i=0; i<ffin.size(); i++){
393 FileFormat ff=ffin.get(i);
394 String sname=sampleNames.get(i);
395 Sample sample=new Sample(ff, sname);
396 samples.add(sample);
397 }
398
399 t2.start("Calculating which variants pass filters.");
400
401 long loadedVars=0;
402 long varsProcessed0=0;
403 for(Sample sample : samples){
404 loadedVars+=sample.process1(forcedVars1, forcedVars2);
405 varsProcessed0+=sample.varsProcessed;
406 sample.clear();
407 scafMap.clearCoverage();
408 }
409 forcedVars1=null;
410
411 t2.stop(loadedVars+" variants passed filters.");
412
413 t2.start("Processing second pass.");
414
415 long readsProcessed=0;
416 long basesProcessed=0;
417 long pairedInSequencingReadsProcessed=0;
418 long properlyPairedReadsProcessed=0;
419 long trimmedBasesProcessed=0;
420 long realignmentsAttempted=0;
421 long realignmentsSucceeded=0;
422 long realignmentsImproved=0;
423 long realignmentsRetained=0;
424 long varsPrefiltered=0;
425 long varsProcessed=0;
426
427 for(Sample sample : samples){
428 sample.process2(forcedVars2);
429
430 if(sample.vcfName!=null){
431 VcfWriter vw=new VcfWriter(sample.varMap, varFilter, sample.readsProcessed-sample.readsDiscarded,
432 sample.pairedInSequencingReadsProcessed, sample.properlyPairedReadsProcessed,
433 sample.trimmedBasesProcessed, ref, trimWhitespace, sample.name);
434 vw.writeVcfFile(sample.vcfName);
435 }
436
437 readsProcessed+=sample.readsProcessed;
438 basesProcessed+=sample.basesProcessed;
439 pairedInSequencingReadsProcessed+=sample.pairedInSequencingReadsProcessed;
440 properlyPairedReadsProcessed+=sample.properlyPairedReadsProcessed;
441 trimmedBasesProcessed+=sample.trimmedBasesProcessed;
442 realignmentsAttempted+=sample.realignmentsAttempted;
443 realignmentsSucceeded+=sample.realignmentsSucceeded;
444 realignmentsImproved+=sample.realignmentsImproved;
445 realignmentsRetained+=sample.realignmentsRetained;
446 varsPrefiltered+=sample.varsPrefiltered;
447 varsProcessed+=sample.varsProcessed;
448
449 sample.clear();
450 scafMap.clearCoverage();
451 }
452
453
454 t2.start("Finished second pass.");
455
456 long[] types=forcedVars2.countTypes();
457
458 if(vcf!=null){
459 t2.start("Writing output.");
460 MergeSamples merger=new MergeSamples();
461 merger.filter=varFilter;
462 merger.mergeSamples(samples, scafMap, vcf, scoreHistFile);
463 t2.stop("Time: ");
464 }
465
466 //Reset read validation
467 Read.VALIDATE_IN_CONSTRUCTOR=vic;
468
469 //Report timing and results
470 {
471 t.stop();
472
473 long size=scafMap.lengthSum();
474 long a=varsProcessed0, b=loadedVars, c=varsPrefiltered, d=varsProcessed;
475 double amult=100.0/a;
476 double bmult=100.0/b;
477 outstream.println();
478 if(prefilter){
479 outstream.println(c+" of "+d+" events were screened by the prefilter ("+Tools.format("%.4f%%", c*100.0/d)+").");
480 }
481 outstream.println(b+" of "+a+" variants passed filters ("+Tools.format("%.4f%%", b*amult)+").");
482 outstream.println();
483 outstream.println("Substitutions: \t"+types[Var.SUB]+Tools.format("\t%.1f%%", types[Var.SUB]*bmult));
484 outstream.println("Deletions: \t"+types[Var.DEL]+Tools.format("\t%.1f%%", types[Var.DEL]*bmult));
485 outstream.println("Insertions: \t"+types[Var.INS]+Tools.format("\t%.1f%%", types[Var.INS]*bmult));
486 outstream.println("Variation Rate:\t"+(b==0 ? 0 : 1)+"/"+(size/Tools.max(1,b))+"\n");
487
488 if(realign){
489 outstream.println("Realignments: \t"+realignmentsAttempted);
490 outstream.println("Successes: \t"+realignmentsSucceeded);
491 outstream.println("Improvements: \t"+realignmentsImproved);
492 outstream.println("Retained: \t"+realignmentsRetained);
493 outstream.println();
494 }
495
496 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
497 }
498
499 //Throw an exception of there was an error in a thread
500 if(errorStateOverall){
501 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
502 }
503 }
504
505 /*--------------------------------------------------------------*/
506 /*---------------- Inner Methods ----------------*/
507 /*--------------------------------------------------------------*/
508
509 /*--------------------------------------------------------------*/
510 /*---------------- Inner Classes ----------------*/
511 /*--------------------------------------------------------------*/
512
513 class Sample{
514
515 public Sample(FileFormat ff_, String sname_){
516 ff=ff_;
517 name=sname_;
518 vcfName=vcf0==null ? null : vcf0.replaceFirst("%", name);
519 }
520
521 /** Find all variants that pass filters for this sample and add them to the shared map */
522 public long process1(VarMap forcedVarsIn, VarMap forcedVarsOut) {
523
524 Timer t2=new Timer();
525 outstream.println("Processing sample "+name+".");
526
527 final KCountArray7MTA kca;
528 if(prefilter){
529 t2.start("Loading the prefilter.");
530 kca=prefilter(varFilter.minAlleleDepth);
531 double used=(100.0*kca.cellsUsed())/kca.cells;
532 outstream.println("Added "+varsProcessed+" events to prefilter; approximately "+(long)(kca.estimateUniqueKmers(2))+" were unique.");
533 outstream.println(Tools.format("The prefilter is %.2f%% full.", used));
534 varsProcessed=0;
535 t2.stop("Time: ");
536 outstream.println();
537 }else{
538 kca=null;
539 }
540
541 t2.start("Loading variants.");
542
543 assert(varMap==null);
544 varMap=new VarMap(scafMap);
545
546 if(forcedVarsIn!=null && forcedVarsIn.size()>0){
547 for(Var v : forcedVarsIn){
548 varMap.addUnsynchronized(v.clone());
549 }
550 }
551
552 processInput(ff, kca, forcedVarsIn, true);
553 final double properPairRate=properlyPairedReadsProcessed/(double)Tools.max(1, readsProcessed-readsDiscarded);
554 final double pairedInSequencingRate=pairedInSequencingReadsProcessed/(double)Tools.max(1, readsProcessed-readsDiscarded);
555 final double totalQualityAvg=totalQualitySum/(double)Tools.max(1, trimmedBasesProcessed);
556 final double totalMapqAvg=totalMapqSum/(double)Tools.max(1, readsProcessed-readsDiscarded);
557 final double readLengthAvg=trimmedBasesProcessed/(double)Tools.max(1, readsProcessed-readsDiscarded);
558 // System.err.println(properlyPairedReadsProcessed+", "+readsProcessed+", "+readsDiscarded);
559 varMap.ploidy=ploidy;
560 varMap.properPairRate=properPairRate;
561 varMap.pairedInSequencingRate=pairedInSequencingRate;
562 varMap.totalQualityAvg=totalQualityAvg;
563 varMap.totalMapqAvg=totalMapqAvg;
564 varMap.readLengthAvg=readLengthAvg;
565 t2.stop("Time: ");
566 outstream.println();
567
568 // assert(false) : filter.toString(properPairRate, ploidy);
569
570 long initialCount=varMap.size();
571 t2.start("Processing variants.");
572 final long[] types=processVariants();
573 t2.stop("Time: ");
574 outstream.println();
575
576 if(countNearbyVars){
577 t2.start("Counting nearby variants.");
578 int x=varMap.countNearbyVars(varFilter);
579 if(x>0 && varFilter.failNearby){
580 for(Var v : varMap.toArray(false)){
581 if(!v.forced() && v.nearbyVarCount>varFilter.maxNearbyCount){
582 varMap.removeUnsynchronized(v);
583 }
584 }
585 }
586 t2.stop("Time: ");
587 outstream.println();
588 }
589
590 long added=0;
591 if(forcedVarsOut!=null){
592 for(Var v : varMap){
593 if(!forcedVarsOut.containsKey(v)){
594 forcedVarsOut.addUnsynchronized(v.clone().clear().setForced(true));
595 added++;
596 }
597 }
598 }
599 // for(int i=0; i<=VarMap.MASK; i++){
600 // synchronized(sharedVarMap.maps[i]){
601 // initialSharedCount+=sharedVarMap.maps[i].size();
602 // sharedVarMap.maps[i].putAll(varMap.maps[i]);
603 // finalSharedCount+=sharedVarMap.maps[i].size();
604 // }
605 // }
606 return added;
607 }
608
609 public long process2(VarMap forcedVars) {
610 Timer t2=new Timer();
611 outstream.println("Processing sample "+name+".");
612
613 t2.start("Loading variants.");
614
615 assert(varMap==null);
616 varMap=new VarMap(scafMap);
617
618 if(forcedVars!=null && forcedVars.size()>0){
619 for(Var v : forcedVars){
620 varMap.addUnsynchronized(v.clone().clear().setForced(true));
621 }
622 }
623
624 processInput(ff, null, forcedVars, true);
625 final double properPairRate=properlyPairedReadsProcessed/(double)Tools.max(1, readsProcessed-readsDiscarded);
626 final double pairedInSequencingRate=pairedInSequencingReadsProcessed/(double)Tools.max(1, readsProcessed-readsDiscarded);
627 final double totalQualityAvg=totalQualitySum/(double)Tools.max(1, trimmedBasesProcessed);
628 final double totalMapqAvg=totalMapqSum/(double)Tools.max(1, readsProcessed-readsDiscarded);
629 final double readLengthAvg=trimmedBasesProcessed/(double)Tools.max(1, readsProcessed-readsDiscarded);
630 // System.err.println(properlyPairedReadsProcessed+", "+readsProcessed+", "+readsDiscarded);
631 varMap.ploidy=ploidy;
632 varMap.properPairRate=properPairRate;
633 varMap.pairedInSequencingRate=pairedInSequencingRate;
634 varMap.totalQualityAvg=totalQualityAvg;
635 varMap.totalMapqAvg=totalMapqAvg;
636 varMap.readLengthAvg=readLengthAvg;
637 t2.stop("Time: ");
638 outstream.println();
639
640 // assert(false) : filter.toString(properPairRate, ploidy);
641
642 long initialCount=varMap.size();
643 t2.start("Processing variants.");
644 final long[] types=processVariants();
645 // final long[] types=addSharedVariants(sharedVarMap);
646 varMap.calcCoverage(scafMap);
647 t2.stop("Time: ");
648 outstream.println();
649
650 long added=0;
651 assert(forcedVars!=null);
652 if(forcedVars!=null){
653 for(Var v : varMap){
654 Var old=forcedVars.get(v);
655 assert(old!=null) : v;
656 if(old!=null){
657 old.add(v);
658 }else{
659 added++;
660 forcedVars.addUnsynchronized(v);
661 }
662 }
663 }
664 return added;
665 // long initialSharedCount=0, finalSharedCount=0;
666 // for(int i=0; i<=VarMap.MASK; i++){
667 // synchronized(sharedVarMap.maps[i]){
668 // initialSharedCount+=sharedVarMap.maps[i].size();
669 // sharedVarMap.maps[i].putAll(varMap.maps[i]);
670 // finalSharedCount+=sharedVarMap.maps[i].size();
671 // }
672 // }
673 // return finalSharedCount-initialSharedCount;
674 }
675
676 /*--------------------------------------------------------------*/
677
678 private KCountArray7MTA prefilter(int minReads){
679 int cbits=2;
680 while((1L<<cbits)-1<minReads){
681 cbits*=2;
682 }
683
684 long mem=Shared.memAvailable(4);
685 long prebits=mem; //1 bit per byte; 1/8th of the memory
686
687 long precells=prebits/cbits;
688 if(precells<100000){ //Not enough memory - no point.
689 return null;
690 }
691
692 KCountArray7MTA kca=new KCountArray7MTA(precells, cbits, 2, null, minReads);
693
694 if(ref==null){
695 ScafMap.loadSamHeader(ff, scafMap);
696 }
697
698 final SamReadStreamer ss;
699 //Create a read input stream
700 final ConcurrentReadInputStream cris;
701 if(useStreamer){
702 cris=null;
703 ss=new SamReadStreamer(ff, streamerThreads, false, maxReads);
704 ss.start();
705 if(verbose){outstream.println("Started streamer");}
706 }else{
707 ss=null;
708 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, false, ff, null);
709 cris.start(); //Start the stream
710 if(verbose){outstream.println("Started cris");}
711 }
712
713 final int threads=Shared.threads();
714
715 //Fill a list with ProcessThreads
716 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
717 for(int i=0; i<threads; i++){
718 alpt.add(new ProcessThread(cris, ss, i, kca, null, true, false));
719 }
720
721 //Start the threads
722 for(ProcessThread pt : alpt){
723 pt.start();
724 }
725
726 //Wait for completion of all threads
727 boolean success=true;
728 for(ProcessThread pt : alpt){
729
730 //Wait until this thread has terminated
731 while(pt.getState()!=Thread.State.TERMINATED){
732 try {
733 //Attempt a join operation
734 pt.join();
735 } catch (InterruptedException e) {
736 //Potentially handle this, if it is expected to occur
737 e.printStackTrace();
738 }
739 }
740 varsProcessed+=pt.varsProcessedT;
741
742 //Accumulate per-thread statistics
743 success&=pt.success;
744 }
745
746 if(forcedVars1!=null && forcedVars1.size()>0){//For forced vars from an input VCF
747 for(Var v : forcedVars1){
748 final long key=v.toKey();
749 kca.incrementAndReturnUnincremented(key, minReads);
750 }
751 }
752
753 //Track whether any threads failed
754 if(!success){errorState=true;}
755
756 kca.shutdown();
757 return kca;
758 }
759
760 /** Create read streams and process all data */
761 void processInput(FileFormat ff, KCountArray7MTA kca, VarMap forcedVarsIn, boolean calcCoverage){
762 assert(ff.samOrBam()) : ff.name();
763
764 if(ref==null){
765 ScafMap.loadSamHeader(ff, scafMap);
766 }
767
768 final SamReadStreamer ss;
769 //Create a read input stream
770 final ConcurrentReadInputStream cris;
771 if(useStreamer){
772 cris=null;
773 ss=new SamReadStreamer(ff, streamerThreads, false, maxReads);
774 ss.start();
775 if(verbose){outstream.println("Started streamer");}
776 }else{
777 ss=null;
778 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, false, ff, null);
779 cris.start(); //Start the stream
780 if(verbose){outstream.println("Started cris");}
781 }
782
783 //Process the reads in separate threads
784 spawnThreads(cris, ss, kca, forcedVarsIn, calcCoverage);
785
786 if(verbose){outstream.println("Finished; closing streams.");}
787
788 //Close the read streams
789 errorState|=ReadWrite.closeStreams(cris);
790 }
791
792 private long[] processVariants(){
793 return varMap.processVariantsMT(varFilter, scoreArray, ploidyArray, avgQualityArray, maxQualityArray, ADArray, AFArray);
794 }
795
796 // private long[] addSharedVariants(VarMap sharedVarMap){
797 // return varMap.addSharedVariantsST(varFilter, sharedVarMap);
798 // }
799
800 /** Spawn process threads */
801 private void spawnThreads(final ConcurrentReadInputStream cris, final SamReadStreamer ss,
802 final KCountArray7MTA kca, final VarMap forced, final boolean calcCoverage){
803
804 //Do anything necessary prior to processing
805 if(calcCoverage){
806 scafMap.clearCoverage();
807 }
808
809 //Determine how many threads may be used
810 final int threads=Shared.threads();
811
812 //Fill a list with ProcessThreads
813 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
814 for(int i=0; i<threads; i++){
815 alpt.add(new ProcessThread(cris, ss, i, kca, forced, false, calcCoverage));
816 }
817
818 //Start the threads
819 for(ProcessThread pt : alpt){
820 pt.start();
821 }
822
823 //Wait for completion of all threads
824 boolean success=true;
825 for(ProcessThread pt : alpt){
826
827 //Wait until this thread has terminated
828 while(pt.getState()!=Thread.State.TERMINATED){
829 try {
830 //Attempt a join operation
831 pt.join();
832 } catch (InterruptedException e) {
833 //Potentially handle this, if it is expected to occur
834 e.printStackTrace();
835 }
836 }
837
838 //Accumulate per-thread statistics
839 readsProcessed+=pt.readsProcessedT;
840 basesProcessed+=pt.basesProcessedT;
841 trimmedBasesProcessed+=pt.trimmedBasesProcessedT;
842 readsDiscarded+=pt.readsDiscardedT;
843 pairedInSequencingReadsProcessed+=pt.pairedInSequencingReadsProcessedT;
844 properlyPairedReadsProcessed+=pt.properlyPairedReadsProcessedT;
845 varsPrefiltered+=pt.prefilteredT;
846 varsProcessed+=pt.varsProcessedT;
847 totalQualitySum+=pt.totalQualitySumT;
848 totalMapqSum+=pt.totalMapqSumT;
849 success&=pt.success;
850 if(pt.realigner!=null){
851 realignmentsAttempted+=pt.realigner.realignmentsAttempted;
852 realignmentsImproved+=pt.realigner.realignmentsImproved;
853 realignmentsSucceeded+=pt.realigner.realignmentsSucceeded;
854 realignmentsRetained+=pt.realigner.realignmentsRetained;
855 }
856 }
857
858 //Track whether any threads failed
859 if(!success){errorState=true;}
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 public int fixVars(Read r, SamLine sl){
869 assert(false);
870 return -1;//fixVars(r, sl, varMap, scafMap);
871 }
872
873 private void clear(){
874 readsProcessed=0;
875 basesProcessed=0;
876 trimmedBasesProcessed=0;
877 readsDiscarded=0;
878 pairedInSequencingReadsProcessed=0;
879 properlyPairedReadsProcessed=0;
880 varsPrefiltered=0;
881 varsProcessed=0;
882 totalQualitySum=0;
883 totalMapqSum=0;
884
885 realignmentsAttempted=0;
886 realignmentsImproved=0;
887 realignmentsSucceeded=0;
888 realignmentsRetained=0;
889
890 varMap=null;
891 // varMap.clear();
892
893 //errorState=false;
894 }
895
896 /*--------------------------------------------------------------*/
897
898 final FileFormat ff;
899 final String name;
900 final String vcfName;
901
902 /** Number of reads processed */
903 protected long readsProcessed=0;
904 /** Number of bases processed */
905 protected long basesProcessed=0;
906 /** Number of trimmed, mapped bases processed */
907 protected long trimmedBasesProcessed=0;
908 /** Number of reads discarded */
909 protected long readsDiscarded=0;
910 /** Number of paired reads processed by this thread, whether or not they mapped as pairs */
911 protected long pairedInSequencingReadsProcessed=0;
912 /** Number of properly paired reads processed */
913 protected long properlyPairedReadsProcessed=0;
914 /** Number of vars ignored via prefilter */
915 protected long varsPrefiltered=0;
916 /** Number of vars processed */
917 protected long varsProcessed=0;
918
919 /** Sum of trimmed, mapped base qualities */
920 protected long totalQualitySum=0;
921 /** Sum of mapqs */
922 protected long totalMapqSum=0;
923
924 protected long realignmentsAttempted=0;
925 protected long realignmentsImproved=0;
926 protected long realignmentsSucceeded=0;
927 protected long realignmentsRetained=0;
928
929 public VarMap varMap;
930
931 boolean errorState=false;
932
933
934
935
936 /*--------------------------------------------------------------*/
937
938 /** This class is static to prevent accidental writing to shared variables.
939 * It is safe to remove the static modifier. */
940 private class ProcessThread extends Thread {
941
942 //Constructor
943 ProcessThread(final ConcurrentReadInputStream cris_, final SamReadStreamer ss_, final int tid_,
944 final KCountArray7MTA kca_, final VarMap forced_, final boolean prefilterOnly_,
945 final boolean calcCoverage_){
946 cris=cris_;
947 ss=ss_;
948 tid=tid_;
949 kca=kca_;
950 prefilterOnly=prefilterOnly_;
951 realigner=(realign ? new Realigner() : null);
952 forced=forced_;
953 calcCoverage=calcCoverage_;
954 }
955
956 //Called by start()
957 @Override
958 public void run(){
959 //Do anything necessary prior to processing
960
961 //Process the reads
962 if(cris==null){
963 processInner_ss();
964 }else{
965 processInner_cris();
966 }
967
968 //Do anything necessary after processing
969 if(!varMapT.isEmpty()){
970 dumpVars(varMapT);
971 }
972 assert(varMapT.isEmpty());
973
974 //Indicate successful exit status
975 success=true;
976 }
977
978 /** Iterate through the reads */
979 void processInner_cris(){
980
981 //Grab the first ListNum of reads
982 ListNum<Read> ln=cris.nextList();
983 //Grab the actual read list from the ListNum
984 ArrayList<Read> reads=(ln!=null ? ln.list : null);
985
986 //As long as there is a nonempty read list...
987 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
988 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
989
990 //Loop through each read in the list
991 for(int idx=0; idx<reads.size(); idx++){
992 final Read r=reads.get(idx);
993 assert(r.mate==null);
994
995 if(!r.validated()){r.validate(true);}
996
997 //Track the initial length for statistics
998 final int initialLength=r.length();
999
1000 //Increment counters
1001 readsProcessedT++;
1002 basesProcessedT+=initialLength;
1003
1004 boolean b=processRead(r);
1005
1006 if(!b){
1007 readsDiscardedT++;
1008 }
1009 }
1010
1011 //Notify the input stream that the list was used
1012 cris.returnList(ln);
1013 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
1014
1015 //Fetch a new list
1016 ln=cris.nextList();
1017 reads=(ln!=null ? ln.list : null);
1018 }
1019
1020 //Notify the input stream that the final list was used
1021 if(ln!=null){
1022 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
1023 }
1024 }
1025
1026 /** Iterate through the reads */
1027 void processInner_ss(){
1028
1029 //Grab the actual read list from the ListNum
1030 ListNum<Read> ln=ss.nextList();
1031
1032 //As long as there is a nonempty read list...
1033 while(ln!=null && ln.size()>0){
1034 ArrayList<Read> reads=ln.list;
1035 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
1036
1037 //Loop through each read in the list
1038 for(int idx=0; idx<reads.size(); idx++){
1039 final Read r=reads.get(idx);
1040 assert(r.mate==null);
1041
1042 if(!r.validated()){r.validate(true);}
1043
1044 //Track the initial length for statistics
1045 final int initialLength=r.length();
1046
1047 //Increment counters
1048 readsProcessedT++;
1049 basesProcessedT+=initialLength;
1050
1051 boolean b=processRead(r);
1052 if(!b){
1053 readsDiscardedT++;
1054 }
1055 }
1056
1057 ln=ss.nextList();
1058 }
1059 }
1060
1061 /**
1062 * Process a read.
1063 * @param r Read 1
1064 * @return True if the reads should be kept, false if they should be discarded.
1065 */
1066 boolean processRead(final Read r){
1067 if(r.bases==null || r.length()<=1){return false;}
1068 final SamLine sl=r.samline;
1069
1070 // final SamLine oldSL=new SamLine(sl);
1071 // final Read oldRead=r.clone();
1072
1073 if(samFilter!=null && !samFilter.passesFilter(sl)){return false;}
1074 if(sl.properPair()){properlyPairedReadsProcessedT++;}
1075 if(sl.hasMate()){pairedInSequencingReadsProcessedT++;}
1076 final Scaffold scaf=scafMap.getScaffold(sl);
1077 final int scafnum=scaf.number;
1078
1079 // r.toLongMatchString(false); //Not necessary since scoring can be done on short match string
1080 if(realign){
1081 realigner.realign(r, sl, scaf, unclip);
1082 }
1083 // System.err.println(sl);
1084 // System.err.println(new String(r.match));
1085
1086 int leftTrimAmount=border, rightTrimAmount=border;
1087 if(qtrimLeft || qtrimRight){
1088 long packed=TrimRead.testOptimal(r.bases, r.quality, trimE);
1089 if(qtrimLeft){leftTrimAmount=Tools.max(leftTrimAmount, (int)((packed>>32)&0xFFFFFFFFL));}
1090 if(qtrimRight){rightTrimAmount=Tools.max(rightTrimAmount, (int)((packed)&0xFFFFFFFFL));}
1091 }
1092
1093 int trimmed=(leftTrimAmount<1 && rightTrimAmount<1 ? 0 : TrimRead.trimReadWithMatch(r, sl, leftTrimAmount, rightTrimAmount, 0, scaf.length, false));
1094 if(trimmed<0){return false;}//In this case the whole read should be trimmed
1095 int extra=(qtrimLeft || qtrimRight) ? trimmed/2 : Tools.min(border, trimmed/2);
1096 // System.err.println(sl);
1097 // System.err.println(new String(r.match));
1098 // System.err.println();
1099
1100 ArrayList<Var> vars=null;
1101 // try {
1102 vars = Var.toVars(r, sl, callNs, scafnum);
1103 // } catch (Throwable e) {
1104 // // TODO Auto-generated catch block
1105 // System.err.println("Bad line:");
1106 // System.err.println(oldRead.toString());
1107 // System.err.println(r.toString());
1108 // System.err.println(oldSL.toString());
1109 // System.err.println(sl.toString());
1110 // System.err.println("\n");
1111 // }
1112
1113 if(prefilterOnly){
1114 if(vars==null){return true;}
1115 for(Var v : vars){
1116 long key=v.toKey();
1117 kca.increment(key);
1118 }
1119 }else{
1120 trimmedBasesProcessedT+=r.length();
1121 totalQualitySumT+=shared.Vector.sum(r.quality);
1122 totalMapqSumT+=sl.mapq;
1123 if(calcCoverage){scaf.add(sl);}
1124 if(vars==null){return true;}
1125
1126 for(Var v : vars){//Vars in each read
1127 if((forced!=null && forced.containsKey(v)) || kca==null || kca.read(v.toKey())>=varFilter.minAlleleDepth){
1128 v.endDistMax+=extra;
1129 v.endDistSum+=extra;
1130
1131 Var old=varMapT.get(v);
1132 if(old==null){varMapT.put(v, v);}
1133 else{old.add(v);}
1134 }else{
1135 prefilteredT++;
1136 }
1137 }
1138 if(varMapT.size()>vmtSizeLimit){
1139 dumpVars(varMapT);
1140 }
1141 }
1142 varsProcessedT+=vars.size();
1143 return true;
1144 }
1145
1146 private final KCountArray7MTA kca;
1147 private final boolean prefilterOnly;
1148 private final VarMap forced;
1149
1150 HashMap<Var, Var> varMapT=new HashMap<Var, Var>();
1151
1152 /** Number of vars blocked by the prefilter */
1153 protected long prefilteredT=0;
1154 /** Number of vars processed */
1155 protected long varsProcessedT=0;
1156
1157 /** Sum of trimmed, mapped base qualities */
1158 protected long totalQualitySumT=0;
1159 /** Sum of mapqs */
1160 protected long totalMapqSumT=0;
1161
1162 /** Number of reads processed by this thread */
1163 protected long readsProcessedT=0;
1164 /** Number of bases processed by this thread */
1165 protected long basesProcessedT=0;
1166 /** Number of trimmed, mapped bases processed. */
1167 protected long trimmedBasesProcessedT=0;
1168 /** Number of reads discarded by this thread */
1169 protected long readsDiscardedT=0;
1170 /** Number of paired reads processed by this thread, whether or not they mapped as pairs */
1171 protected long pairedInSequencingReadsProcessedT=0;
1172 /** Number of properly paired reads processed by this thread */
1173 protected long properlyPairedReadsProcessedT=0;
1174
1175 /** True only if this thread has completed successfully */
1176 boolean success=false;
1177
1178 /** Shared input stream */
1179 private final ConcurrentReadInputStream cris;
1180 /** Optional SamReadStreamer for high throughput */
1181 private final SamReadStreamer ss;
1182 /** For realigning reads */
1183 final Realigner realigner;
1184
1185 final boolean calcCoverage;
1186
1187 /** Thread ID */
1188 final int tid;
1189 }
1190 }
1191
1192 public static int fixVars(Read r, VarMap varMap, ScafMap scafMap){
1193 return CallVariants.fixVars(r, varMap, scafMap);
1194 }
1195
1196 public static void unfixVars(Read r){
1197 CallVariants.unfixVars(r);
1198 }
1199
1200 public static int fixVars(Read r, SamLine sl, VarMap varMap, ScafMap scafMap){
1201 return CallVariants.fixVars(r, sl, varMap, scafMap);
1202 }
1203
1204 /*--------------------------------------------------------------*/
1205 /*---------------- Fields ----------------*/
1206 /*--------------------------------------------------------------*/
1207
1208 /** Primary input file path */
1209 private ArrayList<String> in=new ArrayList<String>();
1210
1211 /** VCF output file path */
1212 private String vcf=null;
1213
1214 /** VCF input file path for forced variants */
1215 private String vcfin=null;
1216
1217 /** Individual vcf files */
1218 private String vcf0="individual_%.vcf.gz";
1219
1220 private String scoreHistFile=null;
1221
1222 /** Override input file extension */
1223 private String extin=null;
1224 /** Override output file extension */
1225 private String extout=null;
1226 /** A fasta file. */
1227 private String ref=null;
1228
1229 private boolean loadedRef=false;
1230
1231 private boolean qtrimLeft=false;
1232 private boolean qtrimRight=true;
1233 private float trimq=10;
1234 private final float trimE;
1235
1236 /*--------------------------------------------------------------*/
1237
1238 public ScafMap scafMap=new ScafMap();
1239
1240 public VarMap forcedVars1=null;
1241 public VarMap forcedVars2=null;
1242
1243 /** Quit after processing this many input reads; -1 means no limit */
1244 private long maxReads=-1;
1245
1246 public int ploidy=-1;
1247
1248 public int border=5;
1249
1250 public boolean realign=false;
1251 public boolean unclip=false;
1252
1253 public boolean prefilter=false;
1254
1255 /*
1256 * These cover junk due to artifacts, misassemblies, or structural variants,
1257 * which generally result in a rainbow of adjacent SNPs.
1258 * Some fields are in VarFilter.
1259 */
1260 public boolean countNearbyVars=true;
1261
1262 /*--------------------------------------------------------------*/
1263 /*---------------- Final Fields ----------------*/
1264 /*--------------------------------------------------------------*/
1265
1266 /** Primary input file */
1267 private final ArrayList<FileFormat> ffin=new ArrayList<FileFormat>();
1268
1269 /** Sample names */
1270 private final ArrayList<String> sampleNames=new ArrayList<String>();
1271
1272 public final VarFilter varFilter=new VarFilter();
1273 public final SamFilter samFilter=new SamFilter();
1274 public final long[][] scoreArray=new long[8][200];
1275 public final long[] ploidyArray;
1276 public final long[][] avgQualityArray=new long[8][100];
1277 public final long[] maxQualityArray=new long[100];
1278 public final long[][] ADArray=new long[2][7];
1279 public final double[] AFArray=new double[7];
1280
1281 /*--------------------------------------------------------------*/
1282 /*---------------- Static Fields ----------------*/
1283 /*--------------------------------------------------------------*/
1284
1285 private static int vmtSizeLimit=10000;
1286
1287 static boolean callNs=false;
1288 static boolean trimWhitespace=true;
1289
1290 static boolean useStreamer=true;
1291 static int streamerThreads=SamStreamer.DEFAULT_THREADS;
1292
1293 /*--------------------------------------------------------------*/
1294 /*---------------- Common Fields ----------------*/
1295 /*--------------------------------------------------------------*/
1296
1297 /** Print status messages to this output stream */
1298 private PrintStream outstream=System.err;
1299 /** Print verbose messages */
1300 public static boolean verbose=false;
1301 /** True if an error was encountered */
1302 public boolean errorStateOverall=false;
1303 /** Overwrite existing output files */
1304 private boolean overwrite=true;
1305
1306 }