Debian Codegraph @

current/jgi/ReformatReads.java

raw symbols SCIP
1 package jgi;
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 import java.util.HashSet;
9 import java.util.Random;
10
11 import cardinality.CardinalityTracker;
12 import dna.AminoAcid;
13 import dna.Data;
14 import fileIO.ByteFile;
15 import fileIO.ByteFile1;
16 import fileIO.ByteFile2;
17 import fileIO.FileFormat;
18 import fileIO.ReadWrite;
19 import hiseq.IlluminaHeaderParser2;
20 import hiseq.ReadHeaderParser;
21 import shared.KillSwitch;
22 import shared.MetadataWriter;
23 import shared.Parse;
24 import shared.Parser;
25 import shared.PreParser;
26 import shared.Shared;
27 import shared.Timer;
28 import shared.Tools;
29 import shared.TrimRead;
30 import stream.ConcurrentGenericReadInputStream;
31 import stream.ConcurrentReadInputStream;
32 import stream.ConcurrentReadOutputStream;
33 import stream.FASTQ;
34 import stream.FastaReadInputStream;
35 import stream.Read;
36 import stream.SamLine;
37 import structures.ListNum;
38 import structures.LongList;
39 import structures.Quantizer;
40 import structures.SuperLongList;
41 import tracker.ReadStats;
42 import var2.ScafMap;
43
44 /**
45 * @author Brian Bushnell
46 * @date Sep 11, 2012
47 *
48 */
49 public class ReformatReads {
50
51 public static void main(String[] args){
52 Timer t=new Timer();
53 ReformatReads x=new ReformatReads(args);
54 x.process(t);
55
56 //Close the print stream if it was redirected
57 Shared.closeStream(x.outstream);
58 }
59
60 public ReformatReads(String[] args){
61
62 {//Preparse block for help, config files, and outstream
63 PreParser pp=new PreParser(args, getClass(), false);
64 args=pp.args;
65 outstream=pp.outstream;
66 }
67
68 boolean setInterleaved=false; //Whether it was explicitly set.
69
70
71
72 Shared.capBuffers(4);
73 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
74 ReadWrite.setZipThreads(Shared.threads());
75
76
77 SamLine.SET_FROM_OK=true;
78 // SamLine.CONVERT_CIGAR_TO_MATCH=true;
79
80 Parser parser=new Parser();
81 for(int i=0; i<args.length; i++){
82 String arg=args[i];
83 String[] split=Parse.splitOnFirst(arg, '=');
84 String a=split[0].toLowerCase();
85 String b=split.length>1 ? split[1] : null;
86
87 if(a.equals("passes")){
88 assert(false) : "'passes' is disabled.";
89 // passes=Integer.parseInt(b);
90 }else if(a.equals("path")){
91 Data.setPath(b);
92 }else if(a.equals("ref")){
93 ref=b;
94 }else if(a.equals("verbose")){
95 verbose=Parse.parseBoolean(b);
96 ByteFile1.verbose=verbose;
97 ByteFile2.verbose=verbose;
98 stream.FastaReadInputStream.verbose=verbose;
99 ConcurrentGenericReadInputStream.verbose=verbose;
100 stream.FastqReadInputStream.verbose=verbose;
101 ReadWrite.verbose=verbose;
102 }else if(a.equals("sample") || a.equals("samplereads") || a.equals("samplereadstarget") || a.equals("srt")){
103 sampleReadsTarget=Parse.parseKMG(b);
104 sampleReadsExact=(sampleReadsTarget>0);
105 }else if(a.equals("samplebases") || a.equals("samplebasestarget") || a.equals("sbt")){
106 sampleBasesTarget=Parse.parseKMG(b);
107 sampleBasesExact=(sampleBasesTarget>0);
108 }else if(a.equals("prioritizelength")){
109 prioritizeLength=Parse.parseBoolean(b);
110 }else if(a.equals("upsample")){
111 allowUpsample=Parse.parseBoolean(b);
112 }else if(a.equals("addslash")){
113 addslash=Parse.parseBoolean(b);
114 }else if(a.equals("addcolon")){
115 addcolon=Parse.parseBoolean(b);
116 }else if(a.equals("slashspace") || a.equals("spaceslash")){
117 boolean x=Parse.parseBoolean(b);
118 if(x){
119 slash1=" /1";
120 slash2=" /2";
121 }else{
122 slash1="/1";
123 slash2="/2";
124 }
125 }else if(a.equals("addunderscore") || a.equals("underscore")){
126 addunderscore=Parse.parseBoolean(b);
127 }else if(a.equals("uniquenames")){
128 uniqueNames=Parse.parseBoolean(b);
129 }else if(a.equals("verifyinterleaved") || a.equals("verifyinterleaving") || a.equals("vint")){
130 verifyinterleaving=Parse.parseBoolean(b);
131 }else if(a.equals("verifypaired") || a.equals("verifypairing") || a.equals("vpair")){
132 verifypairing=Parse.parseBoolean(b);
133 }else if(a.equals("allowidenticalnames") || a.equals("ain")){
134 allowIdenticalPairNames=Parse.parseBoolean(b);
135 }else if(a.equals("rcompmate") || a.equals("rcm")){
136 reverseComplementMate=Parse.parseBoolean(b);
137 outstream.println("Set RCOMPMATE to "+reverseComplementMate);
138 }else if(a.equals("rcomp") || a.equals("rc") || a.equals("reversecomplement")){
139 reverseComplement=Parse.parseBoolean(b);
140 outstream.println("Set RCOMP to "+reverseComplement);
141 }else if(a.equals("comp") || a.equals("complement")){
142 complement=Parse.parseBoolean(b);
143 outstream.println("Warning: Setting non-standard parameter 'complement'.");
144 }
145
146 //Unneeded due to pad flag
147 // else if(a.equals("npad") || a.equals("padns")){
148 // assert(b!=null) : "npad requires an int value, e.g. npad=10";
149 // assert(Character.isDigit(b.charAt(0)) || b.charAt(0)=='f') : "npad requires an int value, e.g. npad=10";
150 // if(Character.isDigit(b.charAt(0)){npad=Integer.parseInt(b);}
151 // else {npad=0;}
152 // }
153
154 else if(a.equals("deleteempty") || a.equals("deletempty") || a.equals("delempty") || a.equals("def")){
155 deleteEmptyFiles=Parse.parseBoolean(b);
156 }else if(a.equals("mappedonly")){
157 mappedOnly=Parse.parseBoolean(b);
158 }else if(a.equals("pairedonly")){
159 pairedOnly=Parse.parseBoolean(b);
160 }else if(a.equals("unpairedonly")){
161 unpairedOnly=Parse.parseBoolean(b);
162 }else if(a.equals("unmappedonly")){
163 unmappedOnly=Parse.parseBoolean(b);
164 }else if(a.equals("requiredbits") || a.equals("rbits")){
165 requiredBits=Parse.parseIntHexDecOctBin(b);
166 }else if(a.equals("filterbits") || a.equals("fbits")){
167 filterBits=Parse.parseIntHexDecOctBin(b);
168 }else if(a.equals("primaryonly")){
169 primaryOnly=Parse.parseBoolean(b);
170 }else if(a.equals("remap1")){
171 remap1=Parse.parseRemap(b);
172 }else if(a.equals("remap2")){
173 remap2=Parse.parseRemap(b);
174 }else if(a.equals("remap")){
175 remap1=remap2=Parse.parseRemap(b);
176 }else if(a.equals("minmapq")){
177 minMapq=Integer.parseInt(b);
178 }else if(a.equals("maxmapq")){
179 maxMapq=Integer.parseInt(b);
180 }else if(a.equals("skipreads")){
181 skipreads=Parse.parseKMG(b);
182 }else if(a.equals("undefinedton") || a.equals("iupacton") || a.equals("itn")){
183 iupacToN=Parse.parseBoolean(b);
184 }else if(a.equals("bottom")){
185 bottom=Parse.parseBoolean(b);
186 }else if(a.equals("top")){
187 top=Parse.parseBoolean(b);
188 }
189
190 else if(a.equals("quantize") || a.equals("quantizesticky")){
191 quantizeQuality=Quantizer.parse(arg, a, b);
192 }else if(a.equals("samversion") || a.equals("samv") || a.equals("sam")){
193 parser.parse(arg, a, b);
194 fixCigar=true;
195 }else if(a.equals("deleteinput")){
196 deleteInput=Parse.parseBoolean(b);
197 }else if(a.equals("invert") || a.equals("invertfilters")){
198 invertFilters=Parse.parseBoolean(b);
199 }else if(a.equals("k")){
200 k=Integer.parseInt(b);
201 }else if(a.equals("top")){
202 top=Parse.parseBoolean(b);
203 }else if(a.equals("bottom")){
204 bottom=Parse.parseBoolean(b);
205 }
206
207 else if(a.equalsIgnoreCase("lastUnderscoreToSpace") || a.equalsIgnoreCase("underscoreToSpace")){
208 lastUnderscoreToSpace=Parse.parseBoolean(b);
209 }
210
211 else if(a.equals("fixheader") || a.equals("fixheaders") || a.equals("fixnames")){
212 fixHeaders=Parse.parseBoolean(b);
213 }
214
215 else if(a.equals("padleft")){
216 padLeft=Integer.parseInt(b);
217 }else if(a.equals("padright")){
218 padRight=Integer.parseInt(b);
219 }else if(a.equals("pad")){
220 assert(b!=null) : "No value for pad.";
221 if(Character.isLetter(b.charAt(0))){padSymbol=(byte)b.charAt(0);}
222 else{padLeft=padRight=Integer.parseInt(b);}
223 }else if(a.equals("padsymbol")){
224 padSymbol=(byte)b.charAt(0);
225 }else if(a.equals("padq")){
226 padQ=(byte)Integer.parseInt(b);
227 }
228
229 else if(a.equals("minsubs")){
230 minsubs=Integer.parseInt(b);
231 }
232
233 else if(a.equals("tag")){
234 tag=b;
235 }else if(a.equals("delimiter")){
236 // delimiterS=null;
237 delimiter=Parse.parseSymbolToCharacter(b);
238 // if(delimiter==0) {delimiterS=Parse.parseSymbol(b);}
239 assert(delimiter>0) : delimiter+", '"+b+"'";
240 }else if(a.equals("minvalue")){
241 minValue=Integer.parseInt(b);
242 }else if(a.equals("maxvalue")){
243 maxValue=Integer.parseInt(b);
244 }else if(a.equals("value")){
245 requiredValue=b;
246 }
247
248 else if(parser.parse(arg, a, b)){
249 //do nothing
250 }else if(parser.in1==null && i==0 && Tools.looksLikeInputStream(arg)){
251 parser.in1=arg;
252 }else{
253 outstream.println("Unknown parameter "+args[i]);
254 assert(false) : "Unknown parameter "+args[i];
255 // throw new RuntimeException("Unknown parameter "+args[i]);
256 }
257 }
258
259 if(k>0){parser.loglogk=k;}
260 if(parser.loglog && k<1){k=parser.loglogk;}
261 pad=padLeft>0 || padRight>0;
262 if(AminoAcid.isFullyDefined(padSymbol)){padQ=Tools.max(padQ, (byte)2);}
263
264 {//Process parser fields
265 Parser.processQuality();
266
267 maxReads=parser.maxReads;
268 samplerate=parser.samplerate;
269 sampleseed=parser.sampleseed;
270
271 overwrite=ReadStats.overwrite=parser.overwrite;
272 append=ReadStats.append=parser.append;
273 testsize=parser.testsize;
274 trimBadSequence=parser.trimBadSequence;
275 breakLength=parser.breakLength;
276 stoptag=SamLine.MAKE_STOP_TAG;
277
278 forceTrimModulo=parser.forceTrimModulo;
279 forceTrimLeft=parser.forceTrimLeft;
280 forceTrimRight=parser.forceTrimRight;
281 forceTrimRight2=parser.forceTrimRight2;
282 qtrimLeft=parser.qtrimLeft;
283 qtrimRight=parser.qtrimRight;
284 trimq=parser.trimq;
285 trimE=parser.trimE();
286 minAvgQuality=parser.minAvgQuality;
287 minAvgQualityBases=parser.minAvgQualityBases;
288 chastityFilter=parser.chastityFilter;
289 failBadBarcodes=parser.failBadBarcodes;
290 removeBadBarcodes=parser.removeBadBarcodes;
291 failIfNoBarcode=parser.failIfNoBarcode;
292 barcodes=parser.barcodes;
293 maxNs=parser.maxNs;
294 minConsecutiveBases=parser.minConsecutiveBases;
295 minReadLength=parser.minReadLength;
296 maxReadLength=parser.maxReadLength;
297 minLenFraction=parser.minLenFraction;
298 requireBothBad=parser.requireBothBad;
299 minGC=parser.minGC;
300 maxGC=parser.maxGC;
301 filterGC=(minGC>0 || maxGC<1);
302 usePairGC=parser.usePairGC;
303 tossJunk=parser.tossJunk;
304 recalibrateQuality=parser.recalibrateQuality;
305
306 minIdFilter=parser.minIdFilter;
307 maxIdFilter=parser.maxIdFilter;
308 subfilter=parser.subfilter;
309 clipfilter=parser.clipfilter;
310 delfilter=parser.delfilter;
311 insfilter=parser.insfilter;
312 indelfilter=parser.indelfilter;
313 dellenfilter=parser.dellenfilter;
314 inslenfilter=parser.inslenfilter;
315 editfilter=parser.editfilter;
316
317 USE_EDIT_FILTER=(subfilter>-1 || minsubs>-1 || delfilter>-1 || insfilter>-1 || indelfilter>-1 || dellenfilter>-1 || inslenfilter>-1 || editfilter>-1 || clipfilter>-1);
318
319 setInterleaved=parser.setInterleaved;
320
321 in1=parser.in1;
322 in2=parser.in2;
323 qfin1=parser.qfin1;
324 qfin2=parser.qfin2;
325
326 out1=parser.out1;
327 out2=parser.out2;
328 outsingle=parser.outsingle;
329 qfout1=parser.qfout1;
330 qfout2=parser.qfout2;
331
332 extin=parser.extin;
333 extout=parser.extout;
334
335 loglog=(parser.loglog ? CardinalityTracker.makeTracker(parser) : null);
336 silent=Parser.silent;
337 }
338
339 if(recalibrateQuality){CalcTrueQuality.initializeMatrices();}
340
341 if(SamLine.setxs && !SamLine.setintron){SamLine.INTRON_LIMIT=10;}
342 qtrim=qtrimLeft||qtrimRight;
343
344 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
345 in2=in1.replace("#", "2");
346 in1=in1.replace("#", "1");
347 }
348 if(out1!=null && out2==null && out1.indexOf('#')>-1){
349 out2=out1.replace("#", "2");
350 out1=out1.replace("#", "1");
351 }
352
353 if(out1!=null && in1!=null && out1.indexOf('%')>-1){
354 out1=out1.replace("%", ReadWrite.stripExtension(in1));
355 }
356 if(out2!=null && out2.indexOf('%')>-1){
357 if(in2!=null){
358 out2=out2.replace("%", ReadWrite.stripExtension(in2));
359 }else if(in1!=null){
360 out2=out2.replace("%", ReadWrite.stripExtension(in1));
361 }
362 }
363
364 if(in2!=null){
365 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
366 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
367 }
368
369 if(verifyinterleaving || (verifypairing && in2==null)){
370 verifypairing=true;
371 setInterleaved=true;
372 // if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
373 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=true;
374 }
375
376 assert(FastaReadInputStream.settingsOK());
377
378 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
379 in1=Tools.fixExtension(in1);
380 in2=Tools.fixExtension(in2);
381 qfin1=Tools.fixExtension(qfin1);
382 qfin2=Tools.fixExtension(qfin2);
383 ref=Tools.fixExtension(ref);
384 if(!Tools.testInputFiles(false, true, in1, in2, qfin1, qfin2)){
385 throw new RuntimeException("\nCan't read some input files.\n");
386 }
387
388
389 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
390 ByteFile.FORCE_MODE_BF2=true;
391 }
392
393 if(out1==null){
394 if(out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
395
396 if(!parser.setOut){
397 outstream.println("No output stream specified. To write to stdout, please specify 'out=stdout.fq' or similar.");
398 // out1="stdout";
399 }
400 }
401
402 if(!setInterleaved){
403 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
404 if(in2!=null){ //If there are 2 input streams.
405 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
406 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
407 }else{ //There is one input stream.
408 if(out2!=null){
409 FASTQ.FORCE_INTERLEAVED=true;
410 FASTQ.TEST_INTERLEAVED=false;
411 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
412 }
413 }
414 }
415
416 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
417 if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
418 if(outsingle!=null && outsingle.equalsIgnoreCase("null")){outsingle=null;}
419
420 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2, qfout1, qfout2, outsingle)){
421 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
422 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
423 }
424 if(!Tools.testForDuplicateFiles(true, in1, in2, qfin1, qfin2, out1, out2, qfout1, qfout2, outsingle) || !ReadStats.testFiles(false)){
425 throw new RuntimeException("Duplicate filenames are not allowed.");
426 }
427
428 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
429 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
430 ffoutsingle=FileFormat.testOutput(outsingle, FileFormat.FASTQ, extout, true, overwrite, append, false);
431
432 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
433 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
434
435 parser.validateStdio(ffin1, ffout1, ffoutsingle);
436
437 assert(ReadStats.testFiles(true)) : "Existing output files specified, but overwrite==false";
438 assert(ReadStats.testFiles(false)) : "Duplicate or output files specified";
439
440 // outstream.println("\n"+ReadWrite.USE_PIGZ+", "+ReadWrite.USE_UNPIGZ+", "+Data.PIGZ()+", "+Data.UNPIGZ()+", "+ffin1+"\n");
441 // assert(false) : ReadWrite.USE_PIGZ+", "+ReadWrite.USE_UNPIGZ+", "+Data.PIGZ()+", "+Data.UNPIGZ()+", "+ffin1;
442
443 nameMap1=(uniqueNames ? new HashMap<String, Integer>() : null);
444 nameMap2=(uniqueNames ? new HashMap<String, Integer>() : null);
445
446 if(ref!=null){ScafMap.loadReference(ref, true);}
447 if(tag!=null) {
448 assert(delimiter>0/* || delimiterS!=null*/) :
449 "When using a tag, a delimiter must be set; e.g. "
450 + "delimiter=X, delimiter=' ' or delimiter=space\n"
451 + "Most problematic symbols can be spelled out, like tab, "
452 + "pipe, asterisk, greaterthan, etc.";
453 // if(delimiterS!=null) {
454 // splitter=Pattern.compile(delimiterS);
455 // }
456 // lp=new LineParser2S(delimiter);
457 }
458 // lp=null;//lp is not currently used
459 }
460
461
462
463 void process(Timer t){
464
465 long readsRemaining=0;
466 long basesRemaining=0;
467
468 if(sampleReadsExact || sampleBasesExact){
469 if(prioritizeLength){
470 SuperLongList sll=makeLengthHist(maxReads);
471 LongList list=sll.list();
472 long[] array=sll.array();
473 if(sampleReadsExact){
474 long sum=0;
475 for(int i=list.size()-1; i>=0 && sum<sampleReadsTarget; i--){
476 long num=list.get(i);
477 sum++;
478 if(sum>=sampleReadsTarget){
479 minReadLength=Tools.max(minReadLength, (int)num);
480 }
481 }
482 for(int i=array.length-1; i>=0 && sum<sampleReadsTarget; i--){
483 long count=array[i];
484 sum+=count;
485 if(sum>=sampleReadsTarget){
486 minReadLength=Tools.max(minReadLength, i);
487 }
488 }
489 }else{
490 long sum=0;
491 for(int i=list.size()-1; i>=0 && sum<sampleBasesTarget; i--){
492 long num=list.get(i);
493 sum+=num;
494 if(sum>=sampleBasesTarget){
495 minReadLength=Tools.max(minReadLength, (int)num);
496 }
497 }
498 for(int i=array.length-1; i>=0 && sum<sampleBasesTarget; i--){
499 long count=array[i];
500 sum+=(count*i);
501 if(sum>=sampleBasesTarget){
502 minReadLength=Tools.max(minReadLength, i);
503 }
504 }
505 // System.err.println(sum+", "+minReadLength+", "+sll.median()+", "+sll.mean());
506 }
507 // System.err.println(sll.toString());
508 sampleReadsExact=sampleBasesExact=false;
509 }else{
510 long[] counts=countReads(maxReads);
511 readsRemaining=counts[0];
512 basesRemaining=counts[2];
513 setSampleSeed(sampleseed);
514 double prob=(sampleReadsExact ? sampleReadsTarget/(double)(readsRemaining)
515 : sampleBasesTarget/(double)(basesRemaining));
516 if(!allowUpsample) {prob=Tools.min(prob, 1.0);}
517 System.err.println("Initial samplerate set to "+String.format("%.6f", prob));
518 }
519 }
520
521
522 final ConcurrentReadInputStream cris;
523 {
524 useSharedHeader=(ffin1.samOrBam() && ffout1!=null && ffout1.samOrBam());
525 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, useSharedHeader, ffin1, ffin2, qfin1, qfin2);
526 cris.setSampleRate(samplerate, sampleseed);
527 if(verbose){outstream.println("Started cris");}
528 cris.start(); //4567
529 }
530 boolean paired=cris.paired();
531 if(!silent){
532 outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));
533 }
534
535 assert(!paired || breakLength<1) : "Paired input cannot be broken with 'breaklength'";
536
537 final ConcurrentReadOutputStream ros;
538 if(ffout1!=null){
539 final int buff=4;
540
541 if(cris.paired() && ffout2==null && ffout1!=null && !ffout1.samOrBam()){
542 outstream.println("Writing interleaved.");
543 }
544
545 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, useSharedHeader);
546 ros.start();
547 }else{ros=null;}
548
549 final ConcurrentReadOutputStream rosb;
550 if(ffoutsingle!=null){
551 final int buff=4;
552
553 rosb=ConcurrentReadOutputStream.getStream(ffoutsingle, null, buff, null, useSharedHeader);
554 rosb.start();
555 }else{rosb=null;}
556 final boolean discardTogether=(!paired || (ffoutsingle==null && !requireBothBad));
557
558 long basesFTrimmedT=0;
559 long readsFTrimmedT=0;
560
561 long basesQTrimmedT=0;
562 long readsQTrimmedT=0;
563
564 long lowqBasesT=0;
565 long lowqReadsT=0;
566
567 long badGcBasesT=0;
568 long badGcReadsT=0;
569
570 long readShortDiscardsT=0;
571 long baseShortDiscardsT=0;
572
573 long unmappedReadsT=0;
574 long unmappedBasesT=0;
575
576 long idfilteredReadsT=0;
577 long idfilteredBasesT=0;
578
579 long basesSwappedT=0;
580 long readsSwappedT=0;
581
582 final boolean MAKE_IHIST=ReadStats.COLLECT_INSERT_STATS;
583
584 final boolean sam=ffin1.samOrBam();
585
586 final ReadStats readstats=ReadStats.collectingStats() ? new ReadStats() : null;
587
588 {
589
590 ListNum<Read> ln=cris.nextList();
591 ArrayList<Read> reads=(ln!=null ? ln.list : null);
592
593 // outstream.println("Fetched "+reads);
594
595 if(reads!=null && !reads.isEmpty()){
596 Read r=reads.get(0);
597 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
598 }
599
600 Read prevRead=null;
601
602 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
603
604 if(skipreads>0){
605 int removed=0;
606 for(int i=0; i<reads.size(); i++){
607 Read r=reads.get(i);
608 if(r.numericID<skipreads){
609 reads.set(i, null);
610 removed++;
611 }else{
612 skipreads=-1;
613 break;
614 }
615 }
616 if(removed>0){
617 Tools.condenseStrict(reads);
618 }
619 }
620
621 ArrayList<Read> singles=(rosb==null ? null : new ArrayList<Read>(32));
622
623 if(breakLength>0){
624 Tools.breakReads(reads, breakLength, minReadLength, verbose? outstream : null);
625 }
626
627 for(int idx=0; idx<reads.size(); idx++){
628 final Read r1=reads.get(idx);
629 final Read r2=r1.mate;
630
631 final int initialLength1=r1.length();
632 final int initialLength2=(r1.mateLength());
633
634 final int minlen1=(int)Tools.max(initialLength1*minLenFraction, minReadLength);
635 final int minlen2=(int)Tools.max(initialLength2*minLenFraction, minReadLength);
636
637 final SamLine sl1;
638 if(sam){
639 sl1=r1.samline;
640 assert(r2==null);
641 // sl2=(r2==null ? null : r2.samline);
642 // if(sl1!=null && Shared.TRIM_RNAME){
643 // sl1.setRname(Tools.trimToWhitespace(sl1.rname()));
644 // sl1.setRnext(Tools.trimToWhitespace(sl1.rnext()));
645 // }
646 }else{
647 sl1=null;//=sl2=null;
648 }
649
650 if(fixHeaders){
651 fixHeader(r1);
652 fixHeader(r2);
653 }
654
655 if(lastUnderscoreToSpace){
656 underscoreToSpace(r1);
657 underscoreToSpace(r2);
658 }
659
660 if(readstats!=null){
661 readstats.addToHistograms(r1);
662
663 if(MAKE_IHIST && sl1!=null && !r1.secondary() && sl1.pairnum()==0){
664 readstats.addToInsertHistogram(sl1);
665 }
666
667 // if(MAKE_IHIST && !r1.secondary()){
668 // if(sl1!=null && sl2!=null && sl1.qname.equals(sl2.qname) && sl1.pairnum()!=sl2.pairnum()){
669 // readstats.addToInsertHistogram(sl1, sl2);
670 // }
671 // }
672 }
673 if(!r1.secondary()){prevRead=r1;}
674
675 if(loglog!=null){loglog.hash(r1);}
676
677 if(k>0){
678 {
679 final int kmers=Tools.countKmers(r1.bases, k);
680 kmersProcessed+=kmers;
681 correctKmers+=(r1.quality==null ? kmers : Tools.countCorrectKmers(r1.quality, k));
682 }
683 if(r2!=null){
684 final int kmers=Tools.countKmers(r2.bases, k);
685 kmersProcessed+=kmers;
686 correctKmers+=(r2.quality==null ? kmers : Tools.countCorrectKmers(r2.quality, k));
687 }
688 }
689
690 {
691 readsProcessed++;
692 basesProcessed+=initialLength1;
693 if(reverseComplement){r1.reverseComplement();}
694 if(complement){r1.complement();}
695 }
696 if(r2!=null){
697 readsProcessed++;
698 basesProcessed+=initialLength2;
699 if(reverseComplement || reverseComplementMate){r2.reverseComplement();}
700 if(complement){r2.complement();}
701 }
702
703 if(!bottom || !top) {
704 rhp.parse(r1);
705 if(!bottom && rhp.surface()==1) {
706 r1.setDiscarded(true);
707 r2.setDiscarded(true);
708 }
709 if(!top && rhp.surface()==2) {
710 r1.setDiscarded(true);
711 r2.setDiscarded(true);
712 }
713 }
714
715 if(verifypairing){
716 String s1=r1==null ? null : r1.id;
717 String s2=r2==null ? null : r2.id;
718 boolean b=FASTQ.testPairNames(s1, s2, allowIdenticalPairNames);
719 if(!b){
720 outstream.println("Names do not appear to be correctly paired.\n"+s1+"\n"+s2+"\n");
721 ReadWrite.closeStreams(cris, ros);
722 System.exit(1);
723 }
724 }
725
726 if(tossJunk){
727 if(r1!=null && r1.junk()){
728 lowqBasesT+=r1.length();
729 lowqReadsT++;
730 r1.setDiscarded(true);
731 }
732 if(r2!=null && r2.junk()){
733 lowqBasesT+=r2.length();
734 lowqReadsT++;
735 r2.setDiscarded(true);
736 }
737 }
738
739 if(iupacToN){
740 if(r1!=null){r1.convertUndefinedTo((byte)'N');}
741 if(r2!=null){r2.convertUndefinedTo((byte)'N');}
742 }
743
744 if(remap1!=null && r1!=null){
745 int swaps=r1.remapAndCount(remap1);
746 if(swaps>0){
747 basesSwappedT+=swaps;
748 readsSwappedT++;
749 }
750 }
751 if(remap2!=null && r2!=null){
752 int swaps=r2.remapAndCount(remap2);
753 if(swaps>0){
754 basesSwappedT+=swaps;
755 readsSwappedT++;
756 }
757 }
758
759 if(trimBadSequence){//Experimental
760 if(r1!=null){
761 int x=TrimRead.trimBadSequence(r1);
762 basesQTrimmedT+=x;
763 readsQTrimmedT+=(x>0 ? 1 : 0);
764 }
765 if(r2!=null){
766 int x=TrimRead.trimBadSequence(r2);
767 basesQTrimmedT+=x;
768 readsQTrimmedT+=(x>0 ? 1 : 0);
769 }
770 }
771
772 if(chastityFilter){
773 if(r1!=null && r1.failsChastity()){
774 lowqBasesT+=r1.pairLength();
775 lowqReadsT+=r1.pairCount();
776 r1.setPairDiscarded(true);
777 }
778 }
779
780 if(removeBadBarcodes){
781 if(r1!=null && !r1.discarded() && r1.failsBarcode(barcodes, failIfNoBarcode)){
782 if(failBadBarcodes){KillSwitch.kill("Invalid barcode detected: "+r1.id+"\nThis can be disabled with the flag barcodefilter=f");}
783 lowqBasesT+=r1.pairLength();
784 lowqReadsT+=r1.pairCount();
785 r1.setPairDiscarded(true);
786 }
787 }
788
789 if(tag!=null && r1!=null && !r1.discarded()) {
790 boolean pass=passesTagFilter(r1.id, tag, delimiter);
791 if(!pass){r1.setPairDiscarded(true);}
792 }
793
794 if(filterBits!=0 || requiredBits!=0){
795 if(r1!=null && !r1.discarded()){
796 assert(sl1!=null) : "filterbits and requiredbits only work on sam/bam input.";
797 if(((sl1.flag&filterBits)!=0) || ((sl1.flag&requiredBits)!=requiredBits)){
798 r1.setDiscarded(true);
799 unmappedBasesT+=initialLength1;
800 unmappedReadsT++;
801 }
802 }
803 }
804
805 if(minMapq>=0 || maxMapq>=0){
806 if(r1!=null && !r1.discarded()){
807 assert(sl1!=null) : "mapq filters only work on sam/bam input.";
808 final int mapq=sl1.mapped() ? sl1.mapq : 0;
809 if((minMapq>=0 && mapq<minMapq) || (maxMapq>=0 && mapq>maxMapq)){
810 r1.setDiscarded(true);
811 unmappedBasesT+=initialLength1;
812 unmappedReadsT++;
813 }
814 }
815 }
816
817 if(minIdFilter>=0 || maxIdFilter<1 || USE_EDIT_FILTER){
818 if(r1!=null && !r1.discarded()){
819 assert(r1.match!=null || r1.samline!=null) : "idfilter requires sam/bam input.";
820 boolean pass=passesIDFilter(r1, minIdFilter, maxIdFilter, false);
821 if(USE_EDIT_FILTER){
822 pass=pass&&passesEditFilter(r1, false);
823 }
824 if(!pass){
825 r1.setDiscarded(true);
826 idfilteredBasesT+=initialLength1;
827 idfilteredReadsT++;
828 }
829 }
830 if(r2!=null && !r2.discarded()){
831 assert(r2.match!=null || r2.samline!=null) : "idfilter requires sam/bam input.";
832 boolean pass=passesIDFilter(r2, minIdFilter, maxIdFilter, false);
833 if(USE_EDIT_FILTER){
834 pass=pass&&passesEditFilter(r2, false);
835 }
836 if(!pass){
837 r2.setDiscarded(true);
838 idfilteredBasesT+=initialLength2;
839 idfilteredReadsT++;
840 }
841 }
842 }
843
844 if(fixCigar){
845 if(SamLine.VERSION==1.3f){
846 if(r1!=null && !r1.discarded()){
847 assert(sl1!=null) : "Cigar string adjustment only works on sam/bam input.";
848 sl1.cigar=SamLine.toCigar13(sl1.cigar);
849 }
850 }else{
851 if(r1!=null && !r1.discarded()){
852 assert(sl1!=null) : "Cigar string adjustment only works on sam/bam input.";
853 if(r1.match!=null){
854 r1.toLongMatchString(false);
855 int start=sl1.pos-1;
856 int stop=start+Read.calcMatchLength(r1.match)-1;
857 sl1.cigar=SamLine.toCigar14(r1.match, start, stop, Integer.MAX_VALUE, r1.bases);
858 }
859 }
860 }
861 }
862
863 if(stoptag){
864 if(r1!=null && !r1.discarded()){
865 assert(sl1!=null) : "stoptag only works on sam/bam input.";
866 if(sl1.mapped() && sl1.cigar!=null){
867 if(sl1.optional==null){sl1.optional=new ArrayList<String>(2);}
868 sl1.optional.add(SamLine.makeStopTag(sl1.pos, sl1.calcCigarLength(false, false), sl1.cigar, r1.perfect()));
869 }
870 }
871 }
872
873 if(pairedOnly || unpairedOnly){
874 assert(sl1!=null) : "pairedonly requires sam/bam input.";
875
876 if(r1!=null && !r1.discarded() && sl1.properPair()!=pairedOnly){
877 r1.setDiscarded(true);
878 unmappedBasesT+=initialLength1;
879 unmappedReadsT++;
880 }
881 }
882
883 if(mappedOnly || unmappedOnly){
884 if(r1!=null && !r1.discarded() && (r1.mapped()!=mappedOnly || r1.bases==null || r1.secondary())){
885 r1.setDiscarded(true);
886 unmappedBasesT+=initialLength1;
887 unmappedReadsT++;
888 }
889 if(r2!=null && !r2.discarded() && (r2.mapped()!=mappedOnly || r2.bases==null || r2.secondary())){
890 r2.setDiscarded(true);
891 unmappedBasesT+=initialLength2;
892 unmappedReadsT++;
893 }
894 }
895
896 if(primaryOnly){
897 if(r1!=null && (r1.bases==null || r1.secondary())){
898 r1.setDiscarded(true);
899 unmappedBasesT+=initialLength1;
900 unmappedReadsT++;
901 }
902 if(r2!=null && (r2.bases==null || r2.secondary())){
903 r2.setDiscarded(true);
904 unmappedBasesT+=initialLength2;
905 unmappedReadsT++;
906 }
907 }
908
909 if(filterGC && (initialLength1>0 || initialLength2>0)){
910 float gc1=(initialLength1>0 ? r1.gc() : -1);
911 float gc2=(initialLength2>0 ? r2.gc() : gc1);
912 if(gc1==-1){gc1=gc2;}
913 if(usePairGC){
914 final float gc;
915 if(r2==null){
916 gc=gc1;
917 }else{
918 gc=(gc1*initialLength1+gc2*initialLength2)/(initialLength1+initialLength2);
919 }
920 gc1=gc2=gc;
921 }
922 if(r1!=null && !r1.discarded() && (gc1<minGC || gc1>maxGC)){
923 r1.setDiscarded(true);
924 badGcBasesT+=initialLength1;
925 badGcReadsT++;
926 }
927 if(r2!=null && !r2.discarded() && (gc2<minGC || gc2>maxGC)){
928 r2.setDiscarded(true);
929 badGcBasesT+=initialLength2;
930 badGcReadsT++;
931 }
932 }
933
934 if(recalibrateQuality){
935 if(r1!=null && !r1.discarded()){
936 CalcTrueQuality.recalibrate(r1);
937 }
938 if(r2!=null && !r2.discarded()){
939 CalcTrueQuality.recalibrate(r2);
940 }
941 }
942
943 if(quantizeQuality){
944 final byte[] quals1=r1.quality, quals2=(r2==null ? null : r2.quality);
945 Quantizer.quantize(quals1);
946 Quantizer.quantize(quals2);
947 }
948
949 if(forceTrimLeft>0 || forceTrimRight>=0 || forceTrimModulo>0 || forceTrimRight2>0){
950 if(r1!=null && !r1.discarded()){
951 final int len=r1.length();
952 final int a=forceTrimLeft>0 ? forceTrimLeft : 0;
953 final int b0=forceTrimModulo>0 ? len-1-len%forceTrimModulo : len;
954 final int b1=forceTrimRight>=0 ? forceTrimRight : len;
955 final int b2=forceTrimRight2>0 ? len-1-forceTrimRight2 : len;
956 final int b=Tools.min(b0, b1, b2);
957 final int x=TrimRead.trimToPosition(r1, a, b, 1);
958 basesFTrimmedT+=x;
959 readsFTrimmedT+=(x>0 ? 1 : 0);
960 if(r1.length()<minlen1){r1.setDiscarded(true);}
961 }
962 if(r2!=null && !r2.discarded()){
963 final int len=r2.length();
964 final int a=forceTrimLeft>0 ? forceTrimLeft : 0;
965 final int b0=forceTrimModulo>0 ? len-1-len%forceTrimModulo : len;
966 final int b1=forceTrimRight>0 ? forceTrimRight : len;
967 final int b2=forceTrimRight2>0 ? len-1-forceTrimRight2 : len;
968 final int b=Tools.min(b0, b1, b2);
969 final int x=TrimRead.trimToPosition(r2, a, b, 1);
970 basesFTrimmedT+=x;
971 readsFTrimmedT+=(x>0 ? 1 : 0);
972 if(r2.length()<minlen2){r2.setDiscarded(true);}
973 }
974 }
975
976 if(qtrim){
977 if(r1!=null && !r1.discarded()){
978 int x=TrimRead.trimFast(r1, qtrimLeft, qtrimRight, trimq, trimE, 1);
979 basesQTrimmedT+=x;
980 readsQTrimmedT+=(x>0 ? 1 : 0);
981 }
982 if(r2!=null && !r2.discarded()){
983 int x=TrimRead.trimFast(r2, qtrimLeft, qtrimRight, trimq, trimE, 1);
984 basesQTrimmedT+=x;
985 readsQTrimmedT+=(x>0 ? 1 : 0);
986 }
987 }
988
989 if(minAvgQuality>0){
990 if(r1!=null && !r1.discarded() && r1.avgQuality(false, minAvgQualityBases)<minAvgQuality){
991 lowqBasesT+=r1.length();
992 lowqReadsT++;
993 r1.setDiscarded(true);
994 }
995 if(r2!=null && !r2.discarded() && r2.avgQuality(false, minAvgQualityBases)<minAvgQuality){
996 lowqBasesT+=r2.length();
997 lowqReadsT++;
998 r2.setDiscarded(true);
999 }
1000 }
1001
1002 if(maxNs>=0){
1003 if(r1!=null && !r1.discarded() && r1.countUndefined()>maxNs){
1004 lowqBasesT+=r1.length();
1005 lowqReadsT++;
1006 r1.setDiscarded(true);
1007 }
1008 if(r2!=null && !r2.discarded() && r2.countUndefined()>maxNs){
1009 lowqBasesT+=r2.length();
1010 lowqReadsT++;
1011 r2.setDiscarded(true);
1012 }
1013 }
1014
1015 if(minConsecutiveBases>0){
1016 if(r1!=null && !r1.discarded() && !r1.hasMinConsecutiveBases(minConsecutiveBases)){
1017 lowqBasesT+=r1.length();
1018 lowqReadsT++;
1019 r1.setDiscarded(true);
1020 }
1021 if(r2!=null && !r2.discarded() && !r2.hasMinConsecutiveBases(minConsecutiveBases)){
1022 lowqBasesT+=r2.length();
1023 lowqReadsT++;
1024 r2.setDiscarded(true);
1025 }
1026 }
1027
1028 if(minlen1>0 || minlen2>0 || maxReadLength>0){
1029 // assert(false) : minlen1+", "+minlen2+", "+maxReadLength+", "+r1.length();
1030 if(r1!=null && !r1.discarded()){
1031 int rlen=r1.length();
1032 if(rlen<minlen1 || (maxReadLength>0 && rlen>maxReadLength)){
1033 r1.setDiscarded(true);
1034 readShortDiscardsT++;
1035 baseShortDiscardsT+=rlen;
1036 }
1037 }
1038 if(r2!=null && !r2.discarded()){
1039 int rlen=r2.length();
1040 if(rlen<minlen1 || (maxReadLength>0 && rlen>maxReadLength)){
1041 r2.setDiscarded(true);
1042 readShortDiscardsT++;
1043 baseShortDiscardsT+=rlen;
1044 }
1045 }
1046 }
1047
1048 boolean remove=false;
1049 if(r2==null){
1050 remove=r1.discarded();
1051 }else{
1052 remove=requireBothBad ? (r1.discarded() && r2.discarded()) : (r1.discarded() || r2.discarded());
1053 }
1054 if(invertFilters){
1055 remove=!remove;
1056 r1.setDiscarded(!r1.discarded());
1057 if(r2!=null){r2.setDiscarded(!r2.discarded());}
1058 }
1059
1060 if(remove){reads.set(idx, null);}
1061 else{
1062
1063 if(pad){
1064 pad(r1);
1065 pad(r2);
1066 }
1067
1068 if(uniqueNames || addunderscore || addslash || addcolon){
1069
1070 if(r1.id==null){r1.id=""+r1.numericID;}
1071 if(r2!=null && r2.id==null){r2.id=r1.id;}
1072
1073 if(uniqueNames){
1074
1075 {
1076 Integer v=nameMap1.get(r1.id);
1077 if(v==null){
1078 nameMap1.put(r1.id, 1);
1079 }else{
1080 v++;
1081 nameMap1.put(r1.id, v);
1082 r1.id=r1.id+"_"+v;
1083 }
1084 }
1085 if(r2!=null){
1086 Integer v=nameMap2.get(r2.id);
1087 if(v==null){
1088 nameMap2.put(r2.id, 1);
1089 }else{
1090 v++;
1091 nameMap2.put(r2.id, v);
1092 r2.id=r2.id+"_"+v;
1093 }
1094 }
1095 }
1096 if(addunderscore){
1097 r1.id=Tools.whitespace.matcher(r1.id).replaceAll("_");
1098 if(r2!=null){r2.id=Tools.whitespace.matcher(r2.id).replaceAll("_");}
1099 }
1100 if(addcolon){
1101 if(!r1.id.contains(colon1)){r1.id+=colon1;}
1102 if(r2!=null){
1103 if(!r2.id.contains(colon2)){r2.id+=colon2;}
1104 }
1105 }else if(addslash){
1106 if(!r1.id.contains(slash1)){r1.id+=slash1;}
1107 if(r2!=null){
1108 if(!r2.id.contains(slash2)){r2.id+=slash2;}
1109 }
1110 }
1111 }
1112 }
1113
1114 if(singles!=null){
1115 if(r1.discarded() || (r2!=null && r2.discarded())){
1116 if(!r1.discarded()){
1117 Read r=r1.clone();
1118 r.mate=null;
1119 r.setPairnum(0);
1120 singles.add(r);
1121 }else if(r2!=null && !r2.discarded()){
1122 Read r=r2.clone();
1123 r.mate=null;
1124 r.setPairnum(0);
1125 singles.add(r);
1126 }
1127 }
1128 }
1129 }
1130
1131 final ArrayList<Read> listOut;
1132
1133 // assert(false) : sampleReadsExact+", "+sampleBasesExact;
1134 if(sampleReadsExact || sampleBasesExact){
1135 listOut=new ArrayList<Read>();
1136 if(sampleReadsExact){
1137 for(Read r : reads){
1138 if(r!=null){
1139 assert(readsRemaining>0) : readsRemaining;
1140 double prob=sampleReadsTarget/(double)(readsRemaining);
1141 // outstream.println("sampleReadsTarget="+sampleReadsTarget+", readsRemaining="+readsRemaining+", prob="+prob);
1142 while(allowUpsample && prob>1){
1143 listOut.add(r);
1144 sampleReadsTarget--;
1145 prob--;
1146 }
1147 if(randy.nextDouble()<prob){
1148 listOut.add(r);
1149 sampleReadsTarget--;
1150 }
1151 }
1152 readsRemaining--;
1153 }
1154 }else if(sampleBasesExact){
1155 for(Read r : reads){
1156 if(r!=null){
1157 assert(basesRemaining>0) : basesRemaining;
1158 final int bases=r.pairLength();
1159 double prob=sampleBasesTarget/(double)(basesRemaining);
1160 while(allowUpsample && prob>1){
1161 listOut.add(r);
1162 sampleBasesTarget-=bases;
1163 prob--;
1164 }
1165 if(randy.nextDouble()<prob){
1166 listOut.add(r);
1167 sampleBasesTarget-=bases;
1168 }
1169 basesRemaining-=bases;
1170 }
1171 }
1172 }
1173 }else{
1174 listOut=reads;
1175 }
1176 // if(deleteEmptyFiles){
1177 for(Read r : listOut){
1178 if(r!=null){
1179 readsOut1++;
1180 basesOut1+=r.length();
1181 if(r.mate!=null){
1182 readsOut2++;
1183 basesOut2+=r.mateLength();
1184 }
1185 }
1186 }
1187 if(singles!=null){
1188 for(Read r : singles){
1189 if(r!=null){
1190 readsOutSingle++;
1191 basesOutSingle+=r.length();
1192 }
1193 }
1194 }
1195 // }
1196 if(ros!=null){ros.add(listOut, ln.id);}
1197 if(rosb!=null){rosb.add(singles, ln.id);}
1198
1199 cris.returnList(ln.id, false);
1200 ln=cris.nextList();
1201 reads=(ln!=null ? ln.list : null);
1202 }
1203 if(ln!=null){
1204 // cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
1205 assert(ln.list.isEmpty());
1206 cris.returnList(ln.id, true);
1207 }
1208 }
1209
1210 errorState|=ReadStats.writeAll();
1211
1212 {
1213 //Prevent a spurious error message in the event of a race condition when maxReads is set.
1214 boolean b=ReadWrite.closeStream(cris);
1215 if(maxReads<1 || maxReads==Long.MAX_VALUE || (maxReads!=readsProcessed && maxReads*2!=readsProcessed && samplerate<1)){errorState|=b;}
1216 }
1217 errorState|=ReadWrite.closeOutputStreams(ros, rosb);
1218
1219 if(deleteEmptyFiles){
1220 deleteEmpty(readsOut1, readsOut2, readsOutSingle);
1221 }
1222
1223 // outstream.println(cris.errorState()+", "+(ros==null ? "null" : (ros.errorState()+", "+ros.finishedSuccessfully())));
1224 // if(ros!=null){
1225 // ReadStreamWriter rs1=ros.getRS1();
1226 // ReadStreamWriter rs2=ros.getRS2();
1227 // outstream.println(rs1==null ? "null" : rs1.finishedSuccessfully());
1228 // outstream.println(rs2==null ? "null" : rs2.finishedSuccessfully());
1229 // }
1230
1231 t.stop();
1232
1233 final long rawReadsIn=cris.readsIn(), rawBasesIn=cris.basesIn();
1234 final double rmult=100.0/rawReadsIn, bmult=100.0/rawBasesIn;
1235 final double rpmult=100.0/readsProcessed, bpmult=100.0/basesProcessed;
1236
1237 if(silent){
1238 if(errorState){
1239 throw new RuntimeException("ReformatReads terminated in an error state; the output may be corrupt.");
1240 }
1241 return;
1242 }
1243
1244 outstream.println("Input: \t"+cris.readsIn()+" reads \t"+
1245 cris.basesIn()+" bases");
1246 if(samplerate!=1f){
1247 outstream.println("Processed: \t"+readsProcessed+" reads \t"+
1248 basesProcessed+" bases");
1249 }
1250
1251 if(remap1!=null || remap2!=null){
1252 outstream.println("Base Transforms: \t"+readsSwappedT+" reads ("+Tools.format("%.2f",readsSwappedT*rpmult)+"%) \t"+
1253 basesSwappedT+" bases ("+Tools.format("%.2f",basesSwappedT*bpmult)+"%)");
1254 }
1255 if(qtrim || trimBadSequence){
1256 outstream.println("QTrimmed: \t"+readsQTrimmedT+" reads ("+Tools.format("%.2f",readsQTrimmedT*rpmult)+"%) \t"+
1257 basesQTrimmedT+" bases ("+Tools.format("%.2f",basesQTrimmedT*bpmult)+"%)");
1258 }
1259 if(forceTrimLeft>0 || forceTrimRight>0 || forceTrimRight2>0 || forceTrimModulo>0){
1260 outstream.println("FTrimmed: \t"+readsFTrimmedT+" reads ("+Tools.format("%.2f",readsFTrimmedT*rpmult)+"%) \t"+
1261 basesFTrimmedT+" bases ("+Tools.format("%.2f",basesFTrimmedT*bpmult)+"%)");
1262 }
1263 if(minReadLength>0 || maxReadLength>0){
1264 outstream.println("Short Read Discards: \t"+readShortDiscardsT+" reads ("+Tools.format("%.2f",readShortDiscardsT*rpmult)+"%) \t"+
1265 baseShortDiscardsT+" bases ("+Tools.format("%.2f",baseShortDiscardsT*bpmult)+"%)");
1266 }
1267 if(minAvgQuality>0 || maxNs>=0 || chastityFilter || tossJunk || removeBadBarcodes){
1268 outstream.println("Low quality discards: \t"+lowqReadsT+" reads ("+Tools.format("%.2f",lowqReadsT*rpmult)+"%) \t"+
1269 lowqBasesT+" bases ("+Tools.format("%.2f",lowqBasesT*bpmult)+"%)");
1270 }
1271 if(minIdFilter>=0 || maxIdFilter<1 || USE_EDIT_FILTER){
1272 outstream.println("Identity/edit discards: \t"+idfilteredReadsT+" reads ("+Tools.format("%.2f",idfilteredReadsT*rpmult)+"%) \t"+
1273 idfilteredBasesT+" bases ("+Tools.format("%.2f",idfilteredBasesT*bpmult)+"%)");
1274 }
1275
1276 if(filterGC){
1277 outstream.println("GC content discards: \t"+badGcReadsT+" reads ("+Tools.format("%.2f",badGcReadsT*rpmult)+"%) \t"+
1278 badGcBasesT+" bases ("+Tools.format("%.2f",badGcBasesT*bpmult)+"%)");
1279 }
1280 final long ro=readsOut1+readsOut2+readsOutSingle, bo=basesOut1+basesOut2+basesOutSingle;
1281 outstream.println("Output: \t"+ro+" reads ("+Tools.format("%.2f",ro*rmult)+"%) \t"+
1282 bo+" bases ("+Tools.format("%.2f",bo*bmult)+"%)");
1283
1284 if(k>0){
1285 outstream.println(k+"-mers processed: \t"+kmersProcessed);
1286 outstream.println("Correct "+k+"-mers: \t"+Tools.format("%.2f%%", correctKmers*100.0/kmersProcessed));
1287 }
1288 if(loglog!=null){
1289 outstream.println("Unique "+loglog.k+"-mers: \t"+loglog.cardinality());
1290 }
1291
1292 if(deleteInput && !errorState && out1!=null && in1!=null){
1293 try {
1294 new File(in1).delete();
1295 if(in2!=null){new File(in2).delete();}
1296 } catch (Exception e) {
1297 outstream.println("WARNING: Failed to delete input files.");
1298 }
1299 }
1300
1301 outstream.println();
1302 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
1303 MetadataWriter.write(null, readsProcessed, basesProcessed, readsOut1+readsOut2, basesOut1+basesOut2, false);
1304 if(testsize){
1305 long bytesProcessed=(new File(in1).length()+(in2==null ? 0 : new File(in2).length())+
1306 (qfin1==null ? 0 : new File(qfin1).length())+(qfin2==null ? 0 : new File(qfin2).length()));//*passes
1307 double xpnano=bytesProcessed/(double)(t.elapsed);
1308 String xpstring=(bytesProcessed<100000 ? ""+bytesProcessed : bytesProcessed<100000000 ? (bytesProcessed/1000)+"k" : (bytesProcessed/1000000)+"m");
1309 while(xpstring.length()<8){xpstring=" "+xpstring;}
1310 outstream.println("Bytes Processed: "+xpstring+" \t"+Tools.format("%.2fm bytes/sec", xpnano*1000));
1311 }
1312
1313 if(verifypairing){
1314 outstream.println("Names appear to be correctly paired.");
1315 }
1316
1317 if(outstream!=System.err && outstream!=System.out){outstream.close();}
1318
1319 if(errorState){
1320 throw new RuntimeException("ReformatReads terminated in an error state; the output may be corrupt.");
1321 }
1322 }
1323
1324 /*--------------------------------------------------------------*/
1325
1326 private void pad(Read r){
1327 pad(r, padLeft, padRight, padSymbol, padQ);
1328 }
1329
1330 public static final void pad(Read r, int padLeft, int padRight, byte padSymbol, byte padQ){
1331 if(r==null || r.length()==0 || (padLeft<1 && padRight<1)){return;}
1332 padLeft=Tools.max(0, padLeft);
1333 padRight=Tools.max(0, padRight);
1334 r.bases=pad(r.bases, padLeft, padRight, padSymbol);
1335 r.quality=pad(r.quality, padLeft, padRight, padQ);
1336 }
1337
1338 private static final byte[] pad(byte[] old, int padLeft, int padRight, byte padSymbol){
1339 if(old==null){return null;}
1340 final int innerLimit=old.length+padLeft;
1341 byte[] array=new byte[innerLimit+padRight];
1342 Arrays.fill(array, 0, padLeft, padSymbol);
1343 Arrays.fill(array, innerLimit, innerLimit+padRight, padSymbol);
1344 for(int i=0; i<old.length; i++){array[i+padLeft]=old[i];}
1345 return array;
1346 }
1347
1348 public static final boolean passesIDFilter(Read r, float minId, float maxId, boolean requireMapped){
1349 if(!passesMinIDFilter(r, minId, requireMapped)){return false;}
1350 return passesMaxIDFilter(r, maxId);
1351 }
1352
1353 public static final boolean passesMinIDFilter(Read r, float minId, boolean requireMapped){
1354 if(minId<=0 || r.perfect()){return true;}
1355 if(r.match==null && r.samline!=null){
1356 r.match=r.samline.toShortMatch(false);
1357 }
1358 if(r.match==null){return !requireMapped;}
1359 return Read.identityFlat(r.match, true)>=minId;
1360 }
1361
1362 public static final boolean passesMaxIDFilter(Read r, float maxId){
1363 if(maxId>=1){return true;}
1364 if(r.match==null && r.samline!=null){
1365 r.match=r.samline.toShortMatch(false);
1366 }
1367 if(r.match==null){return true;}
1368 return Read.identityFlat(r.match, true)<=maxId;
1369 }
1370
1371 public final boolean passesEditFilter(Read r, boolean requireMapped){
1372 if(r.perfect()){return true;}
1373 if(r.match==null && r.samline!=null){
1374 r.match=r.samline.toShortMatch(false);
1375 }
1376 if(r.match==null){return !requireMapped;}
1377 r.toLongMatchString(false);
1378
1379 final int sub=Read.countSubs(r.match);
1380 final int ins=Read.countInsertions(r.match);
1381 final int del=Read.countDeletions(r.match);
1382 final int inscount=Read.countInsertionEvents(r.match);
1383 final int delcount=Read.countDeletionEvents(r.match);
1384 final int clip=SamLine.countLeadingClip(r.match)+SamLine.countTrailingClip(r.match);
1385
1386 boolean bad=false;
1387 bad=bad||(subfilter>=0 && sub>subfilter);
1388 bad=bad||(minsubs>=0 && sub<minsubs);
1389 bad=bad||(clipfilter>=0 && clip>clipfilter);
1390 bad=bad||(insfilter>=0 && inscount>insfilter);
1391 bad=bad||(delfilter>=0 && delcount>delfilter);
1392 bad=bad||(inslenfilter>=0 && r.hasLongInsertion(inslenfilter));
1393 bad=bad||(dellenfilter>=0 && r.hasLongDeletion(dellenfilter));
1394 bad=bad||(indelfilter>=0 && inscount+delcount>indelfilter);
1395 bad=bad||(editfilter>=0 && sub+ins+del>editfilter);
1396
1397 return !bad;
1398 }
1399
1400 public boolean passesTagFilter(String s, String tag, char delimiter) {
1401 if(requiredValue!=null) {
1402 String value=Parse.parseString(s, tag, delimiter);
1403 return (value==null ? requiredValue==null : value.equals(requiredValue));
1404 }
1405 double value=Parse.parseDouble(s, tag, delimiter);
1406 return value>=minValue && value<=maxValue;
1407 }
1408
1409 // public boolean passesTagFilter(String s, Pattern splitter) {
1410 // String[] split=s.split(s);
1411 // if(requiredValue!=null) {
1412 // String value=Parse.parseString(s, tag, delimiter);
1413 // return (value==null ? requiredValue==null : value.equals(requiredValue));
1414 // }
1415 // double value=Parse.parseDouble(s, tag, delimiter);
1416 // return value>=minValue && value<=maxValue;
1417 // }
1418
1419 /*--------------------------------------------------------------*/
1420
1421 private void deleteEmpty(long readsOut1, long readsOut2, long readsOutSingle){
1422 deleteEmpty(readsOut1, ffout1, qfout1);
1423 deleteEmpty(readsOut2, ffout2, qfout2);
1424 deleteEmpty(readsOutSingle, ffoutsingle, null);
1425 }
1426
1427 private static void deleteEmpty(long count, FileFormat ff, String qf){
1428 try {
1429 if(ff!=null && count<1){
1430 String s=ff.name();
1431 if(s!=null && !ff.stdio() && !ff.devnull()){
1432 File f=new File(ff.name());
1433 if(f.exists()){
1434 f.delete();
1435 }
1436 }
1437 if(qf!=null){
1438 File f=new File(qf);
1439 if(f.exists()){
1440 f.delete();
1441 }
1442 }
1443 }
1444 } catch (Exception e) {
1445 // TODO Auto-generated catch block
1446 e.printStackTrace();
1447 }
1448 }
1449
1450 private long[] countReads(long maxReads){
1451 if(ffin1.stdio()){
1452 throw new RuntimeException("Can't precount reads from standard in, only from a file.");
1453 }
1454
1455 final ConcurrentReadInputStream cris;
1456 {
1457 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, null, null);
1458 if(verbose){outstream.println("Counting Reads");}
1459 cris.start(); //4567
1460 }
1461
1462 ListNum<Read> ln=cris.nextList();
1463 ArrayList<Read> reads=(ln!=null ? ln.list : null);
1464
1465 long count=0, count2=0, bases=0;
1466
1467 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
1468 count+=reads.size();
1469 for(Read r : reads){
1470 bases+=r.length();
1471 count2++;
1472 if(r.mate!=null){
1473 bases+=r.mateLength();
1474 count2++;
1475 }
1476 }
1477 cris.returnList(ln);
1478 ln=cris.nextList();
1479 reads=(ln!=null ? ln.list : null);
1480 }
1481 cris.returnList(ln);
1482 errorState|=ReadWrite.closeStream(cris);
1483 return new long[] {count, count2, bases};
1484 }
1485
1486 private SuperLongList makeLengthHist(long maxReads){
1487 if(ffin1.stdio()){
1488 throw new RuntimeException("Can't precount reads from standard in, only from a file.");
1489 }
1490
1491 final ConcurrentReadInputStream cris;
1492 {
1493 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, null, null);
1494 if(verbose){outstream.println("Counting Reads");}
1495 cris.start(); //4567
1496 }
1497
1498 ListNum<Read> ln=cris.nextList();
1499 ArrayList<Read> reads=(ln!=null ? ln.list : null);
1500
1501 SuperLongList sll=new SuperLongList(200000);
1502
1503 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
1504 for(Read r : reads){
1505 sll.add(r.length());
1506 if(r.mate!=null){
1507 sll.add(r.mateLength());
1508 }
1509 }
1510 cris.returnList(ln);
1511 ln=cris.nextList();
1512 reads=(ln!=null ? ln.list : null);
1513 }
1514 cris.returnList(ln);
1515 errorState|=ReadWrite.closeStream(cris);
1516 sll.sort();
1517 return sll;
1518 }
1519
1520 public void setSampleSeed(long seed){
1521 randy=Shared.threadLocalRandom(seed);
1522 }
1523
1524
1525 /*--------------------------------------------------------------*/
1526
1527 public static final void underscoreToSpace(Read r){
1528 if(r!=null){
1529 r.id=underscoreToSpace(r.id);
1530 }
1531 }
1532
1533 public static String underscoreToSpace(String header){
1534 int x=header.lastIndexOf('_');
1535 if(x<0){return header;}
1536 byte[] bytes=header.getBytes();
1537 bytes[x]=' ';
1538 return new String(bytes);
1539 }
1540
1541 public static final void fixHeader(Read r){
1542 if(r!=null){
1543 r.id=fixHeader(r.id);
1544 if(r.samline!=null){
1545 r.samline.qname=r.id;
1546 }
1547 }
1548 }
1549
1550 public static final String fixHeader(String header){
1551 if(header==null || header.length()<1){return header;}
1552 byte[] array=new byte[header.length()];
1553 boolean changed=false;
1554 for(int i=0; i<header.length(); i++){
1555 char c=header.charAt(i);
1556 byte b=headerSymbols[c];
1557 array[i]=b;
1558 changed|=(b!=c);
1559 }
1560 if(changed){header=new String(array);}
1561 return header;
1562 }
1563
1564 /** For converting headers to filesystem-valid Strings */
1565 private static final byte[] headerSymbols=new byte[128];
1566
1567 static{
1568 Arrays.fill(headerSymbols, (byte)'_');
1569 for(int i=0; i<128; i++){
1570 if(Character.isLetterOrDigit(i)){
1571 headerSymbols[i]=(byte)i;
1572 }
1573 }
1574 char[] acceptable=new char[] {'_', '.', '#', '-', '(', ')', '~'};
1575 for(char c : acceptable){
1576 headerSymbols[c]=(byte)c;
1577 }
1578 }
1579
1580 /*--------------------------------------------------------------*/
1581
1582 private String in1=null;
1583 private String in2=null;
1584
1585 private String qfin1=null;
1586 private String qfin2=null;
1587
1588 private String out1=null;
1589 private String out2=null;
1590 private String outsingle=null;
1591
1592 private String qfout1=null;
1593 private String qfout2=null;
1594
1595 private String extin=null;
1596 private String extout=null;
1597
1598 private String ref=null;
1599
1600 /*--------------------------------------------------------------*/
1601
1602 public long readsProcessed=0;
1603 public long basesProcessed=0;
1604 public long kmersProcessed=0;
1605 public double correctKmers=0;
1606
1607 //Only used with deleteEmptyFiles flag
1608 public long readsOut1=0;
1609 public long readsOut2=0;
1610 public long readsOutSingle=0;
1611
1612 public long basesOut1=0;
1613 public long basesOut2=0;
1614 public long basesOutSingle=0;
1615
1616 /*--------------------------------------------------------------*/
1617
1618 /** For calculating kmer cardinality */
1619 private final CardinalityTracker loglog;
1620
1621 private int k=0;
1622
1623 /** Tracks names to ensure no duplicate names. */
1624 private final HashMap<String,Integer> nameMap1, nameMap2;
1625 private boolean uniqueNames=false;
1626
1627 private boolean reverseComplementMate=false;
1628 private boolean reverseComplement=false;
1629 private boolean complement=false;
1630 private boolean verifyinterleaving=false;
1631 private boolean verifypairing=false;
1632 private boolean allowIdenticalPairNames=true;
1633 private boolean trimBadSequence=false;
1634 private boolean chastityFilter=false;
1635 /** Crash if a barcode is encountered that contains Ns or is not in the table */
1636 private final boolean failBadBarcodes;
1637 /** Remove reads with Ns in barcodes or that are not in the table */
1638 private final boolean removeBadBarcodes;
1639 /** Fail reads missing a barcode */
1640 private final boolean failIfNoBarcode;
1641 /** A set of valid barcodes; null if unused */
1642 private final HashSet<String> barcodes;
1643 private boolean deleteEmptyFiles=false;
1644 private boolean mappedOnly=false;
1645 private boolean pairedOnly=false;
1646 private boolean unpairedOnly=false;
1647 private boolean unmappedOnly=false;
1648 private boolean primaryOnly=false;
1649 /** For sam file filtering: These bits must be set. */
1650 private int requiredBits=0;
1651 /** For sam file filtering: These bits must be unset */
1652 private int filterBits=0;
1653 /** Add /1 and /2 to read names */
1654 private boolean addslash=false;
1655 /** Add 1: and 2: to read names */
1656 private boolean addcolon=false;
1657 /** Change read name whitespace to underscores */
1658 private boolean addunderscore=false;
1659 private boolean stoptag=false;
1660 private boolean iupacToN=false;
1661
1662 boolean bottom=true;
1663 boolean top=true;
1664
1665 private float minIdFilter=-1;
1666 private float maxIdFilter=-1;
1667 private int subfilter=-1;
1668 private int minsubs=-1;
1669 private int clipfilter=-1;
1670 private int delfilter=-1;
1671 private int insfilter=-1;
1672 private int indelfilter=-1;
1673 private int dellenfilter=-1;
1674 private int inslenfilter=-1;
1675 private int editfilter=-1;
1676 private int minMapq=-1;
1677 private int maxMapq=-1;
1678
1679 boolean USE_EDIT_FILTER=false;
1680
1681 private long maxReads=-1;
1682 private long skipreads=-1;
1683 private float samplerate=1f;
1684 private long sampleseed=-1;
1685 private boolean sampleReadsExact=false;
1686 private boolean sampleBasesExact=false;
1687 private boolean allowUpsample=false;
1688 private boolean prioritizeLength=false;
1689 private long sampleReadsTarget=0;
1690 private long sampleBasesTarget=0;
1691
1692 /** Recalibrate quality scores using matrices */
1693 private boolean recalibrateQuality=false;
1694 private boolean qtrimRight=false;
1695 private boolean qtrimLeft=false;
1696 private final int forceTrimLeft;
1697 private final int forceTrimRight;
1698 private final int forceTrimRight2;
1699 /** Trim right bases of the read modulo this value.
1700 * e.g. forceTrimModulo=50 would trim the last 3bp from a 153bp read. */
1701 private final int forceTrimModulo;
1702 private float trimq=6;
1703 /** Error rate for trimming (derived from trimq) */
1704 private final float trimE;
1705 private float minAvgQuality=0;
1706 private int minAvgQualityBases=0;
1707 private int maxNs=-1;
1708 private int minConsecutiveBases=0;
1709 private int breakLength=0;
1710 private int maxReadLength=0;
1711 private int minReadLength=0;
1712 private float minLenFraction=0;
1713 private float minGC=0;
1714 private float maxGC=1;
1715 private boolean filterGC=false;
1716 /** Average GC for paired reads. */
1717 private boolean usePairGC;
1718 private boolean tossJunk=false;
1719 /** Toss pair only if both reads are shorter than limit */
1720 private boolean requireBothBad=false;
1721 /** Invert filters. */
1722 private boolean invertFilters;
1723
1724 /** Replace problematic symbols in read headers. */
1725 private boolean fixHeaders;
1726
1727 /** Change the last underscore to a space, to fix UCSF headers */
1728 private boolean lastUnderscoreToSpace=false;
1729
1730 private boolean useSharedHeader;
1731
1732 private byte[] remap1=null, remap2=null;
1733
1734 private boolean quantizeQuality=false;
1735 private boolean fixCigar=false;
1736
1737 private final boolean pad;
1738 private byte padSymbol='N';
1739 private byte padQ=0;
1740 private int padLeft=0;
1741 private int padRight=0;
1742
1743 //For scanning for specific terms in headers, like "count=53".
1744 /** Parse headers for this tag, like "count=" */
1745 private String tag;
1746 /** Use this delimiter when parsing the header */
1747 private char delimiter=0;
1748 private String delimiterS=null;
1749 /** Min value for numeric terms */
1750 private float minValue=Float.MIN_VALUE;
1751 /** Max value for numeric terms */
1752 private float maxValue=Float.MAX_VALUE;
1753 /** A specific String value for terms */
1754 private String requiredValue=null;
1755 // private final LineParser2S lp;
1756 // private Pattern splitter;
1757
1758 ReadHeaderParser rhp=new IlluminaHeaderParser2();
1759
1760 /*--------------------------------------------------------------*/
1761
1762 private final FileFormat ffin1;
1763 private final FileFormat ffin2;
1764
1765 private final FileFormat ffout1;
1766 private final FileFormat ffout2;
1767 private final FileFormat ffoutsingle;
1768
1769 private final boolean qtrim;
1770
1771
1772 /*--------------------------------------------------------------*/
1773
1774 private static String slash1=" /1";
1775 private static String slash2=" /2";
1776 private static final String colon1=" 1:";
1777 private static final String colon2=" 2:";
1778
1779 private PrintStream outstream=System.err;
1780 public static boolean verbose=false;
1781 public boolean silent=false;
1782 public boolean errorState=false;
1783 private boolean overwrite=true;
1784 private boolean append=false;
1785 private boolean testsize=false;
1786 private boolean deleteInput=false;
1787
1788 private Random randy;
1789
1790 }