Debian Codegraph @

current/bloom/PolyFilter.java

raw symbols SCIP
1 package bloom;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.concurrent.locks.ReadWriteLock;
7
8 import cardinality.CardinalityTracker;
9 import dna.AminoAcid;
10 import fileIO.ByteFile;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import jgi.BBDuk;
14 import jgi.BBMerge;
15 import shared.KillSwitch;
16 import shared.MetadataWriter;
17 import shared.Parse;
18 import shared.Parser;
19 import shared.PreParser;
20 import shared.Shared;
21 import shared.Timer;
22 import shared.Tools;
23 import stream.ConcurrentReadInputStream;
24 import stream.ConcurrentReadOutputStream;
25 import stream.FASTQ;
26 import stream.FastaReadInputStream;
27 import stream.Read;
28 import stream.SamLine;
29 import structures.ListNum;
30 import structures.LongHashSet;
31 import structures.Quantizer;
32 import template.Accumulator;
33 import template.ThreadWaiter;
34 import tracker.EntropyTracker;
35 import tracker.ReadStats;
36
37 /**
38 * Filters reads with artificial homopolymers.
39 *
40 * @author Brian Bushnell
41 * @date August 21, 2024
42 *
43 */
44 public class PolyFilter implements Accumulator<PolyFilter.ProcessThread> {
45
46 /*--------------------------------------------------------------*/
47 /*---------------- Initialization ----------------*/
48 /*--------------------------------------------------------------*/
49
50 /**
51 * Code entrance from the command line.
52 * @param args Command line arguments
53 */
54 public static void main(String[] args){
55 //Start a timer immediately upon code entrance.
56 Timer t=new Timer();
57
58 //Create an instance of this class
59 PolyFilter x=new PolyFilter(args);
60
61 //Run the object
62 x.process(t);
63
64 //Close the print stream if it was redirected
65 Shared.closeStream(x.outstream);
66 }
67
68 /**
69 * Constructor.
70 * @param args Command line arguments
71 */
72 public PolyFilter(String[] args){
73
74 {//Preparse block for help, config files, and outstream
75 PreParser pp=new PreParser(args, getClass(), false);
76 args=pp.args;
77 outstream=pp.outstream;
78 }
79
80 boolean setInterleaved=false; //Whether interleaved was explicitly set.
81
82 //Set shared static variables
83 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
84 ReadWrite.setZipThreads(Tools.max(Shared.threads()>1 ? 2 : 1, Shared.threads()>20 ? Shared.threads()/2 : Shared.threads()));
85 BBMerge.strict=true;
86 KCountArray.LOCKED_INCREMENT=true;
87
88 //Create a parser object
89 Parser parser=new Parser();
90 parser.loglog=parser.loglogOut=true;
91
92 boolean setBits=false;
93 int k_=31;
94 int ksmall_=-1;
95 int hashes_=3;
96 int bits_=2;
97 boolean rcomp_=true;
98 boolean merge_=true;
99 boolean tossjunk_=false;
100
101 //Parse each argument
102 for(int i=0; i<args.length; i++){
103 String arg=args[i];
104
105 //Break arguments into their constituent parts, in the form of "a=b"
106 String[] split=arg.split("=");
107 String a=split[0].toLowerCase();
108 String b=split.length>1 ? split[1] : null;
109
110 if(a.equals("verbose")){
111 verbose=Parse.parseBoolean(b);
112 }else if(a.equals("ordered")){
113 ordered=Parse.parseBoolean(b);
114 }
115
116 else if(a.equalsIgnoreCase("k") || a.equalsIgnoreCase("bloomK") || a.equalsIgnoreCase("kbloom") || a.equalsIgnoreCase("bloomFilterK") || a.equalsIgnoreCase("kbig")){
117 k_=Integer.parseInt(b);
118 assert(k_>0 && k_<=31) : "K must be between 1 and 31, inclusive.";
119 }else if(a.equalsIgnoreCase("ksmall") || a.equalsIgnoreCase("bloomKsmall") || a.equalsIgnoreCase("bloomFilterKsmall")){
120 ksmall_=Integer.parseInt(b);
121 }else if(a.equalsIgnoreCase("hashes") || a.equalsIgnoreCase("bloomHashes") || a.equalsIgnoreCase("bloomFilterHashes")){
122 hashes_=Integer.parseInt(b);
123 }else if(a.equals("rcomp")){
124 rcomp_=Parse.parseBoolean(b);
125 }else if(a.equals("bits")){
126 setBits=true;
127 bits_=Integer.parseInt(b);
128 assert(bits_>0);
129 }
130
131 else if(a.equals("kpoly") || a.equals("kset") || a.equals("polyk")) {
132 kpoly=Integer.parseInt(b);
133 }else if(a.equals("hdist")) {
134 hdist=Integer.parseInt(b);
135 }else if(a.equals("mm") || a.equals("maskmiddle")) {
136 maskMiddle=Parse.parseBoolean(b);
137 }
138
139 else if(a.equals("mincount") || a.equals("mindepth")){
140 minCount=Integer.parseInt(b);
141 }else if(a.equalsIgnoreCase("minPolymer") || a.equalsIgnoreCase("minPoly")){
142 minPolymer=Integer.parseInt(b);
143 }else if(a.equalsIgnoreCase("minPolymer2") || a.equalsIgnoreCase("minPoly2")){
144 minPolymer2=Integer.parseInt(b);
145 }else if(a.equalsIgnoreCase("lowCountFraction") || a.equals("lcf") ||
146 a.equalsIgnoreCase("lowDepthFraction") || a.equals("ldf")){
147 lowCountFraction=Float.parseFloat(b);
148 }else if(a.equalsIgnoreCase("lowCountFraction2") || a.equals("lcf2") ||
149 a.equalsIgnoreCase("lowDepthFraction2") || a.equals("ldf2")){
150 lowCountFraction2=Float.parseFloat(b);
151 }else if(a.equalsIgnoreCase("entropyCutoff") || a.equals("entropy") || a.equals("minentropy")){
152 entropyCutoff=Float.parseFloat(b);
153 }else if(a.equalsIgnoreCase("entropyCutoff2") || a.equals("entropy2") || a.equals("minentropy2")){
154 entropyCutoff2=Float.parseFloat(b);
155 }else if(a.equalsIgnoreCase("qualityCutoff") || a.equals("maq") ||
156 a.equals("quality") || a.equals("minquality")){
157 qualityCutoff=Float.parseFloat(b);
158 }else if(a.equalsIgnoreCase("qualityCutoff2") || a.equals("maq2") ||
159 a.equals("quality2") || a.equals("minquality2")){
160 qualityCutoff2=Float.parseFloat(b);
161 }else if(a.equalsIgnoreCase("purity")){
162 nonPolyFraction=1-Float.parseFloat(b);
163 assert(nonPolyFraction>=0 && nonPolyFraction<1) : b;
164 }else if(a.equals("mers") || a.equals("polymers") || a.equals("polymer") || a.equals("bases")){
165 polymers=b.toUpperCase().getBytes();
166 }else if(a.equals("trimpolymers") || a.equals("trimpoly")){
167 trimPolymers=(b==null ? "" : b.toUpperCase()).getBytes();
168 }
169
170 else if(a.equals("minprob")){
171 ReadCounter.minProb=Float.parseFloat(b);
172 }else if(a.equals("maxload")){
173 maxLoad=Float.parseFloat(b);
174 }else if(a.equals("merge")){
175 merge_=Parse.parseBoolean(b);
176 }else if(a.equals("tossjunk")){
177 tossjunk_=Parse.parseBoolean(b);
178 }else if(a.equals("memfraction") || a.equals("memmult") || a.equals("memratio")){
179 memFraction=Float.parseFloat(b);
180 }
181
182 else if(a.equals("trim")){
183 trimLeft=trimRight=parseIntOrBool(b, 6, 0);
184 }else if(a.equals("trimleft")){
185 trimLeft=parseIntOrBool(b, 6, 0);
186 }else if(a.equals("trimright")){
187 trimLeft=parseIntOrBool(b, 6, 0);
188 }else if(a.equals("minlen") || a.equals("minlength")){
189 minLength=Integer.parseInt(b);
190 }else if(a.equals("maxnonpoly")){
191 maxNonPoly=Integer.parseInt(b);
192 }else if(a.equals("quantize") || a.equals("quantizesticky")){
193 quantizeQuality=Quantizer.parse(arg, a, b);
194 }
195
196 else if(a.equals("cells")){
197 BloomFilter.OVERRIDE_CELLS=Parse.parseKMG(b);
198 }else if(a.equals("seed")){
199 KCountArray7MTA.setSeed(Parse.parseKMG(b));
200 }else if(a.equals("smoothwidth") || a.equals("junkwidth") || a.equals("width")){
201 junkWidth=Integer.parseInt(b);
202 }
203
204 else if(a.equals("ref")){
205 addFiles(b, ref);
206 }else if(a.equals("extra")){
207 addFiles(b, extra);
208 }else if(a.equals("outm") || a.equals("outm1") || a.equals("out") || a.equals("out1")){
209 out1=b;
210 }else if(a.equals("outm2") || a.equals("out2")){
211 out2=b;
212 }else if(a.equals("outb") || a.equals("outb1") || a.equals("outbad") || a.equals("outbad1") || a.equals("outlow") || a.equals("outlow1")){
213 outbad1=b;
214 }else if(a.equals("outb2") || a.equals("outbad2") || a.equals("outlow2")){
215 outbad2=b;
216 }else if(a.equals("parse_flag_goes_here")){
217 long fake_variable=Parse.parseKMG(b);
218 //Set a variable here
219 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
220 //do nothing
221 }else{
222 outstream.println("Unknown parameter "+args[i]);
223 assert(false) : "Unknown parameter "+args[i];
224 }
225 }
226
227 while(minCount>0 && ((1L<<bits_)-1)<minCount){bits_*=2;}
228
229 if(ksmall_<=0){ksmall_=k_;}
230 assert(ksmall_<=k_) : k_+", "+ksmall_;
231
232 kbloom=k_;
233 ksmall=Tools.min(kbloom, ksmall_);
234 bits=bits_;
235 hashes=hashes_;
236 rcomp=rcomp_;
237 tossjunk=tossjunk_;
238 merge=merge_;
239 KmerCountAbstract.CANONICAL=rcomp; //rcomp, or true, perhaps... hmmm.
240 polymerFlagged=new long[polymers.length];
241 if(trimPolymers==null){trimPolymers=polymers;}
242
243 {//Process parser fields
244 Parser.processQuality();
245
246 maxReads=parser.maxReads;
247
248 overwrite=ReadStats.overwrite=parser.overwrite;
249 append=ReadStats.append=parser.append;
250 setInterleaved=parser.setInterleaved;
251
252 in1=parser.in1;
253 in2=parser.in2;
254
255 extin=parser.extin;
256 extout=parser.extout;
257
258 // parser.loglogk=k;
259 parser.loglogMinprob=ReadCounter.minProb;
260 loglogOut=((parser.loglog&parser.loglogOut) ? CardinalityTracker.makeTracker(parser) : null);
261 }
262
263 SamLine.SET_FROM_OK=true;
264
265 //Do input file # replacement
266 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
267 in2=in1.replace("#", "2");
268 in1=in1.replace("#", "1");
269 }
270
271 //Do output file # replacement
272 if(out1!=null && out2==null && out1.indexOf('#')>-1){
273 out2=out1.replace("#", "2");
274 out1=out1.replace("#", "1");
275 }
276
277 in1=Tools.fixExtension(in1);
278 in2=Tools.fixExtension(in2);
279 ref=Tools.fixExtension(ref);
280 extra=Tools.fixExtension(extra);
281
282 //Do output file # replacement
283 if(outbad1!=null && outbad2==null && outbad1.indexOf('#')>-1){
284 outbad2=outbad1.replace("#", "2");
285 outbad1=outbad1.replace("#", "1");
286 }
287
288 //Adjust interleaved detection based on the number of input files
289 if(in2!=null){
290 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
291 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
292 }
293
294 assert(FastaReadInputStream.settingsOK());
295
296 //Ensure there is an input file
297 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
298
299 //Adjust the number of threads for input file reading
300 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
301 ByteFile.FORCE_MODE_BF2=true;
302 }
303
304 //Ensure out2 is not set without out1
305 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
306
307 //Adjust interleaved settings based on number of output files
308 if(!setInterleaved){
309 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
310 if(in2!=null){ //If there are 2 input streams.
311 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
312 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
313 }else{ //There is one input stream.
314 if(out2!=null){
315 FASTQ.FORCE_INTERLEAVED=true;
316 FASTQ.TEST_INTERLEAVED=false;
317 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
318 }
319 }
320 }
321
322 //Ensure output files can be written
323 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2, outbad1, outbad2)){
324 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
325 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
326 }
327
328 //Ensure input files can be read
329 if(!Tools.testInputFiles(false, true, in1, in2)){
330 throw new RuntimeException("\nCan't read some input files.\n");
331 }
332
333 //Ensure that no file was specified multiple times
334 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2, outbad1, outbad2)){
335 throw new RuntimeException("\nSome file names were specified multiple times.\n");
336 }
337
338 //Create output FileFormat objects
339 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
340 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
341
342 //Create output FileFormat objects
343 ffoutm1=FileFormat.testOutput(outbad1, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
344 ffoutm2=FileFormat.testOutput(outbad2, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
345
346 //Create input FileFormat objects
347 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
348 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
349
350 if(kpoly>0) {
351 kpoly=Tools.min(kpoly, 32);
352 midMask=makeMidMask(maskMiddle, kpoly);
353 kmerMask=(kpoly==32 ? 0 : ~((-1L)<<(2*kpoly)));
354 set=makeSet(polymers, kpoly, hdist, midMask);
355 System.err.println("Added "+set.size()+" kmer mutants to filter set.");
356 }
357
358 if(lowCountFraction>1.0f){
359 filter=null;
360 }else{
361 outstream.println("Using "+bits+" bits per cell.");
362 {
363 Timer t=new Timer(outstream, true);
364 if(ref.isEmpty()){
365 filter=new BloomFilter(in1, in2, extra, ksmall, kbloom, bits, hashes, 1,
366 rcomp, false, false, memFraction);
367 }else{
368 ref.addAll(extra);
369 filter=new BloomFilter(null, null, ref, ksmall, kbloom, bits, hashes, 1,
370 rcomp, false, false, memFraction);
371 }
372 t.stop("Filter creation: \t\t");
373 outstream.println(filter.filter.toShortString());
374 }
375
376 {
377 double a=filter.filter.estimateUniqueKmers(hashes);
378 outstream.println("Estimated kmers of depth 1+: \t"+(long)a);
379 if(bits>1){
380 double usedFraction2=filter.filter.usedFraction(2);
381 double b=filter.filter.estimateUniqueKmersFromUsedFraction(hashes, usedFraction2);
382 outstream.println("Estimated kmers of depth 2+: \t"+(long)b);
383 outstream.println("Used fraction for depth 2+: \t"+Tools.format("%.3f%%", usedFraction2*100));
384 if(usedFraction2>maxLoad){
385 KillSwitch.kill("Max load exceeded, quitting: "+usedFraction2+" > "+maxLoad);
386 }
387 }else if(maxLoad<1.0f){
388 double usedFraction=filter.filter.usedFraction(2);
389 if(usedFraction>maxLoad){
390 KillSwitch.kill("Max load exceeded, quitting: "+usedFraction+" > "+maxLoad);
391 }
392 }
393 }
394 }
395 }
396
397 private static void addFiles(String b, ArrayList<String> list){
398 if(b==null){list.clear();}
399 else{
400 if(new File(b).exists()){list.add(b);}
401 else{
402 for(String s : b.split(",")){list.add(s);}
403 }
404 }
405 }
406
407 private static final int parseIntOrBool(String b, int defaultTrue, int defaultFalse) {
408 if(b==null || Tools.startsWithLetter(b)) {
409 boolean x=Parse.parseBoolean(b);
410 return (x ? defaultTrue : defaultFalse);
411 }
412 return Integer.parseInt(b);
413 }
414
415 public static long makeMidMask(boolean maskMiddle, int k) {
416 if(!maskMiddle) {return -1L;}
417 int bitsPerBase=2;
418 int midMaskLen=2-(k&1);
419 assert(k>midMaskLen+1);
420 int bits=midMaskLen*bitsPerBase;
421 int shift=((k-midMaskLen)/2)*bitsPerBase;
422 long middleMask=~((~((-1L)<<bits))<<shift);
423 return middleMask;
424 }
425
426 public static LongHashSet makeSet(byte[] polymers, int k, int hdist, long midMask) {
427 if(polymers==null || polymers.length<1) {return null;}
428 LongHashSet set=new LongHashSet(1024);
429 for(byte b : polymers) {
430 long x=AminoAcid.baseToNumber[b];
431 long kmer=0;
432 for(int i=0; i<k; i++) {kmer=((kmer<<2)|x);}
433 addToSet(kmer, k, midMask, hdist, set);
434 }
435 return set;
436 }
437
438 public static void addToSet(final long kmer, final long k, final long midMask, final int hdist,
439 final LongHashSet set){
440 set.add(kmer&midMask);
441 if(hdist<1) {return;}
442
443 for(int i=0; i<k; i++) {
444 final int shift=2*i;
445 final long masked=kmer&~(3L<<shift);
446 for(long x=0; x<4; x++) {
447 final long mutant=(masked|(x<<shift))&midMask;
448 if(mutant!=kmer) {addToSet(mutant, k, midMask, hdist-1, set);}
449 }
450 }
451 }
452
453 public static boolean kmerScan(Read r, int k, long kmerMask, long midMask, LongHashSet set) {
454 if(r==null || r.length()<k) {return false;}
455 final byte[] bases=r.bases;
456 long kmer=0;
457 int len=0;
458 for(int i=0; i<bases.length; i++){
459 byte b=bases[i];
460 long x=AminoAcid.baseToNumber[b];
461 kmer=((kmer<<2)|x)&kmerMask;
462 if(x<0){len=0;}else{len++;}
463 if(len>=k && set.contains(kmer&midMask)){return true;}
464 }
465 return false;
466 }
467
468 /*--------------------------------------------------------------*/
469 /*---------------- Outer Methods ----------------*/
470 /*--------------------------------------------------------------*/
471
472 /** Create read streams and process all data */
473 public void process(Timer t){
474
475 //Turn off read validation in the input threads to increase speed
476 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
477 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
478
479 //Create a read input stream
480 final ConcurrentReadInputStream cris;
481 {
482 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, null, null);
483 cris.start(); //Start the stream
484 if(verbose){outstream.println("Started cris");}
485 }
486 boolean paired=cris.paired();
487 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
488
489 //Optionally create read output streams
490 final ConcurrentReadOutputStream ros, rosb;
491 if(ffout1!=null){
492 //Select output buffer size based on whether it needs to be ordered
493 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
494
495 //Notify user of output mode
496 if(cris.paired() && out2==null && (in1!=null && !ffin1.samOrBam() && !ffout1.samOrBam())){
497 outstream.println("Writing interleaved.");
498 }
499
500 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, null, null, buff, null, false);
501 ros.start(); //Start the stream
502 }else{ros=null;}
503
504 if(ffoutm1!=null){
505 //Select output buffer size based on whether it needs to be ordered
506 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
507
508 rosb=ConcurrentReadOutputStream.getStream(ffoutm1, ffoutm2, null, null, buff, null, false);
509 rosb.start(); //Start the stream
510 }else{rosb=null;}
511
512 //Reset counters
513 readsProcessed=readsOut=0;
514 basesProcessed=basesOut=0;
515
516 Timer t2=new Timer(outstream, true);
517
518 //Process the reads in separate threads
519 spawnThreads(cris, ros, rosb);
520
521 if(verbose){outstream.println("Finished; closing streams.");}
522
523 //Write anything that was accumulated by ReadStats
524 errorState|=ReadStats.writeAll();
525 //Close the read streams
526 errorState|=ReadWrite.closeStreams(cris, ros, rosb);
527
528 //Reset read validation
529 Read.VALIDATE_IN_CONSTRUCTOR=vic;
530
531 //Report timing and results
532 t.stop();
533 t2.stop("\nFiltering Time: \t\t");
534 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
535 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, true));
536 if(merge) {
537 outstream.println(Tools.numberPercent("Merged Reads:", readsMerged, readsMerged*100.0/readsProcessed, 4, 8));
538 }
539 if(polymers!=null && polymers.length>0) {
540 for(int i=0; i<polymers.length; i++) {
541 final String b=Character.toString((char)polymers[i]);
542 final long x=polymerFlagged[i];
543 outstream.println(Tools.numberPercent("Poly-"+b+" Reads:", x, x*100.0/readsProcessed, 4, 8));
544 }
545 }
546 if(entropyCutoff2>0) {
547 outstream.println(Tools.numberPercent("Low Entropy Reads:", entropyFlagged, entropyFlagged*100.0/readsProcessed, 4, 8));
548 }
549 if(qualityCutoff2>0) {
550 outstream.println(Tools.numberPercent("Low Quality Reads:", qualityFlagged, qualityFlagged*100.0/readsProcessed, 4, 8));
551 }
552 if(filter!=null && lowCountFraction2<=1) {
553 outstream.println(Tools.numberPercent("Low Depth Reads:", depthFlagged, depthFlagged*100.0/readsProcessed, 4, 8));
554 }
555 if(trimLeft>0 || trimRight>0) {
556 outstream.println(Tools.numberPercent("Trimmed Reads:", readsTrimmed, readsTrimmed*100.0/readsProcessed, 4, 8));
557 }
558 {
559 lastReadsOut=readsOut;
560 lastReadsRemoved=readsProcessed-readsOut;
561 lastBasesOut=basesOut;
562 lastBasesRemoved=basesProcessed-basesOut;
563
564 long x=readsProcessed-readsOut;
565 outstream.println(Tools.numberPercent("Total Discards:", x, x*100.0/readsProcessed, 4, 8));
566 }
567 if(loglogOut!=null){
568 outstream.println("Unique "+loglogOut.k+"-mers out: \t"+loglogOut.cardinality());
569 }
570
571 MetadataWriter.write(null, readsProcessed, basesProcessed, readsOut, basesOut, false);
572
573 //Throw an exception of there was an error in a thread
574 if(errorState){
575 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
576 }
577 }
578
579 /** Spawn process threads */
580 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros, final ConcurrentReadOutputStream rosb){
581
582 //Do anything necessary prior to processing
583
584 //Determine how many threads may be used
585 final int threads=Shared.threads();
586
587 //Fill a list with ProcessThreads
588 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
589 for(int i=0; i<threads; i++){
590 alpt.add(new ProcessThread(cris, ros, rosb, i));
591 }
592
593 //Start the threads and wait for them to finish
594 boolean success=ThreadWaiter.startAndWait(alpt, this);
595 errorState&=!success;
596
597 // //Do anything necessary after processing
598
599 }
600
601 @Override
602 public final void accumulate(ProcessThread pt){
603 synchronized(pt) {
604 readsProcessed+=pt.readsProcessedT;
605 basesProcessed+=pt.basesProcessedT;
606 readsMerged+=pt.readsMergedT;
607 readsTrimmed+=pt.readsTrimmedT;
608 basesTrimmed+=pt.basesTrimmedT;
609 readsOut+=pt.readsOutT;
610 basesOut+=pt.basesOutT;
611 errorState|=(!pt.success);
612
613 Tools.add(polymerFlagged, pt.polymerFlaggedT);
614 entropyFlagged+=pt.entropyFlaggedT;
615 qualityFlagged+=pt.qualityFlaggedT;
616 depthFlagged+=pt.depthFlaggedT;
617 }
618 }
619
620 @Override
621 public final boolean success(){return !errorState;}
622
623 @Override
624 public ReadWriteLock rwlock() {return null;}
625
626 /*--------------------------------------------------------------*/
627 /*---------------- Inner Methods ----------------*/
628 /*--------------------------------------------------------------*/
629
630 /**
631 * Calculate the length of the longest homopolymer region in this sequence,
632 * allowing a specified error rate, using the Phred algorithm.
633 * There may be longer regions, but they will have flanking subregions with
634 * greater than the specified error rate.
635 * @param bases Sequence to examine.
636 * @param mer Subunit of the homopolymer to count (e.g. 'G').
637 * @param nonFraction Maximal allowed fraction of nonmatching bases in the region.
638 * @return Length of the longest homopolymer.
639 */
640 public static int polymerLen_old(final byte[] bases, final byte mer, final float nonFraction) {
641 if(nonFraction<=0) {return polymerLen(bases, mer);}
642
643 float score=0;
644 float maxScore=0;
645 int maxLen=0;
646 int lastZero=-1;
647
648 for(int i=0; i<bases.length; i++) {
649 final byte b=bases[i];
650 if(b!=mer) {//common case
651 score=Tools.max(0, score-1);
652 if(score<=0) {
653 lastZero=i;
654 maxScore=0;
655 }
656 }else {
657 score+=nonFraction;
658 if(score>=maxScore) {
659 maxScore=score;
660 maxLen=Tools.max(maxLen, i-lastZero);
661 }
662 }
663 }
664
665 return maxLen;
666 }
667
668 //This version does not look for a peak, just a maximal distance above 0.
669 //It is not bidirectionally symmetric though, until the second loop.
670 public static int polymerLen(final byte[] bases, final byte mer, final float nonFraction) {
671 if(nonFraction<=0) {return polymerLen(bases, mer);}
672
673 float score=0;
674 int maxLen=0;
675 int lastZero=-1;
676
677 for(int i=0; i<bases.length; i++) {
678 final byte b=bases[i];
679 if(b!=mer) {//common case
680 score=Tools.max(0, score-1);
681 if(score<=0) {
682 lastZero=i;
683 }
684 }else {
685 score+=nonFraction;
686 maxLen=Tools.max(maxLen, i-lastZero);
687 }
688 }
689
690 score=0;
691 lastZero=-1;
692 for(int i=0; i<bases.length; i++) {
693 final byte b=bases[bases.length-i-1];
694 if(b!=mer) {//common case
695 score=Tools.max(0, score-1);
696 if(score<=0) {
697 lastZero=i;
698 }
699 }else {
700 score+=nonFraction;
701 maxLen=Tools.max(maxLen, i-lastZero);
702 }
703 }
704
705 return maxLen;
706 }
707
708 /**
709 * Calculate the length of the longest homopolymer in this sequence.
710 * @param bases Sequence to examine.
711 * @param mer Subunit of the homopolymer to count (e.g. 'G').
712 * @return Length of the longest homopolymer.
713 */
714 public static int polymerLen(final byte[] bases, final byte mer) {
715 int max=0, current=0;
716 for(byte b : bases) {
717 if(b==mer) {current++;}
718 else {
719 max=Tools.max(max, current);
720 current=0;
721 }
722 }
723 return Tools.max(current, max);
724 }
725
726 public int trimRead(Read r) {
727 if(r==null) {return 0;}
728 int trimmed=0;
729 for(int i=0; i<trimPolymers.length; i++) {
730 final byte b=trimPolymers[i];
731 int x=BBDuk.trimPoly(r, trimLeft, trimRight, maxNonPoly, b);
732 trimmed+=x;
733 }
734 return trimmed;
735 }
736
737 /*--------------------------------------------------------------*/
738 /*---------------- Inner Classes ----------------*/
739 /*--------------------------------------------------------------*/
740
741 class ProcessThread extends Thread {
742
743 //Constructor
744 ProcessThread(final ConcurrentReadInputStream cris_, final ConcurrentReadOutputStream ros_, final ConcurrentReadOutputStream rosb_, final int tid_){
745 cris=cris_;
746 ros=ros_;
747 rosb=rosb_;
748 tid=tid_;
749
750 eTracker=new EntropyTracker(false, Tools.max(0, entropyCutoff), entropyHighpass);
751 }
752
753 //Called by start()
754 @Override
755 public void run(){
756
757 //Process the reads
758 processInner();
759
760 //Do anything necessary after processing
761
762 //Indicate successful exit status
763 success=true;
764 }
765
766 /** Iterate through the reads */
767 void processInner(){
768
769 //Grab the first ListNum of reads
770 ListNum<Read> ln=cris.nextList();
771 //Grab the actual read list from the ListNum
772 ArrayList<Read> reads=(ln!=null ? ln.list : null);
773
774 //Check to ensure pairing is as expected
775 if(reads!=null && !reads.isEmpty()){
776 Read r=reads.get(0);
777 assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
778 }
779
780 //As long as there is a nonempty read list...
781 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
782 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
783 ArrayList<Read> keepList=new ArrayList<Read>(reads.size());
784 ArrayList<Read> tossList=new ArrayList<Read>(reads.size());
785
786 //Loop through each read in the list
787 for(int idx=0; idx<reads.size(); idx++){
788 Read r1=reads.get(idx);
789 Read r2=r1.mate;
790
791 //Validate reads in worker threads
792 if(!r1.validated()){r1.validate(true);}
793 if(r2!=null && !r2.validated()){r2.validate(true);}
794
795 //Track the initial length for statistics
796 final int initialLength1=r1.length();
797 final int initialLength2=r1.mateLength();
798
799 //Increment counters
800 readsProcessedT+=r1.pairCount();
801 basesProcessedT+=initialLength1+initialLength2;
802
803 final int insert=(r2==null || !merge ? -1 :
804 BBMerge.findOverlapVStrict(r1, r2, false));
805 final boolean junk1=isJunk(r1, insert);
806 final boolean junk2=isJunk(r2, insert);
807 boolean keep=!junk1 && !junk2;
808 if(keep && (trimLeft>0 || trimRight>0)) {
809 int trimmed1=trimRead(r1);
810 int trimmed2=trimRead(r2);
811 keep=r1.length()>minLength && (r2==null || r2.length()>=minLength);
812 readsTrimmedT+=(trimmed1>0 ? 1 : 0)+(trimmed2>0 ? 1 : 0);
813 basesTrimmedT+=trimmed1+trimmed2;
814 }
815
816
817 readsMergedT+=(insert>0 ? 2 : 0);
818 assert(r1.mate==r2);
819
820 if(keep){
821 if(quantizeQuality) {
822 Quantizer.quantize(r1);
823 Quantizer.quantize(r2);
824 }
825 if(loglogOut!=null){loglogOut.hash(r1);}
826 readsOutT+=r1.pairCount();
827 basesOutT+=r1.pairLength();
828 keepList.add(r1);
829 }else{
830 tossList.add(r1);
831 }
832 }
833
834 //Output reads to the output streams
835 if(ros!=null){ros.add(keepList, ln.id);}
836 if(rosb!=null){rosb.add(tossList, ln.id);}
837
838 //Notify the input stream that the list was used
839 cris.returnList(ln);
840
841 //Fetch a new list
842 ln=cris.nextList();
843 reads=(ln!=null ? ln.list : null);
844 }
845
846 //Notify the input stream that the final list was used
847 if(ln!=null){
848 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
849 }
850 }
851
852 private boolean isJunk(Read r, int insert) {
853 if(r==null) {return false;}
854
855 //Reads merged with a short insert; probably OK regardless of poly-G
856 if(insert>0 && insert<r.length()+10) {
857 return false;
858 }
859
860 final float entropy=(eTracker==null ? 1 : eTracker.averageEntropy(r.bases, true));
861 final float quality=(float)r.avgQualityByProbabilityDouble(false, r.length());
862 final float lcf=(filter==null ? 0 : filter.lowCountFraction(r, minCount, true));
863
864 int worstBase=0, worstLen=0;
865 for(int i=0; i<polymers.length; i++) {
866 final byte b=polymers[i];
867 int len=polymerLen(r.bases, b, nonPolyFraction);
868 if(len>worstLen) {
869 worstLen=len;
870 worstBase=i;
871 }
872 }
873
874 if(worstLen>minPolymer2) {
875 polymerFlaggedT[worstBase]++;
876 return true;
877 }
878
879 if(set!=null && kmerScan(r, kpoly, kmerMask, midMask, set)) {
880 polymerFlaggedT[worstBase]++;
881 return true;
882 }
883
884 //Reads merged with a long insert; increase stringency
885 if(insert>0 && insert>=r.length()+10) {
886 return false;
887 }
888
889 if(worstLen>minPolymer &&
890 (entropy<entropyCutoff || lcf>lowCountFraction || quality<qualityCutoff)) {
891 polymerFlaggedT[worstBase]++;
892 return true;
893 }
894 if(entropy<entropyCutoff2) {
895 entropyFlaggedT++;
896 return true;
897 }
898 if(quality<qualityCutoff2) {
899 qualityFlaggedT++;
900 return true;
901 }
902 if(lcf>=lowCountFraction2) {
903 depthFlaggedT++;
904 return true;
905 }
906 return false;
907 }
908
909 /** Number of reads processed by this thread */
910 protected long readsProcessedT=0;
911 /** Number of bases processed by this thread */
912 protected long basesProcessedT=0;
913 protected long readsTrimmedT=0;
914 protected long basesTrimmedT=0;
915 protected long readsMergedT=0;
916
917 /** Number of reads retained by this thread */
918 protected long readsOutT=0;
919 /** Number of bases retained by this thread */
920 protected long basesOutT=0;
921
922 /** True only if this thread has completed successfully */
923 boolean success=false;
924
925 /** Shared input stream */
926 private final ConcurrentReadInputStream cris;
927 /** Shared output stream */
928 private final ConcurrentReadOutputStream ros;
929 /** Matched output stream */
930 private final ConcurrentReadOutputStream rosb;
931 /** Thread ID */
932 final int tid;
933
934 final EntropyTracker eTracker;
935
936 final long[] polymerFlaggedT=new long[polymers.length];
937 long entropyFlaggedT=0;
938 long qualityFlaggedT=0;
939 long depthFlaggedT=0;
940 }
941
942 /*--------------------------------------------------------------*/
943 /*---------------- Fields ----------------*/
944 /*--------------------------------------------------------------*/
945
946 private ArrayList<String> ref=new ArrayList<String>();
947 private ArrayList<String> extra=new ArrayList<String>();
948
949 /** Primary input file path */
950 private String in1=null;
951 /** Secondary input file path */
952 private String in2=null;
953
954 /** Primary output file path */
955 private String out1=null;
956 /** Secondary output file path */
957 private String out2=null;
958
959 /** Output file path for bad reads */
960 private String outbad1=null;
961 /** Secondary output file path for bad reads */
962 private String outbad2=null;
963
964 /** Override input file extension */
965 private String extin=null;
966 /** Override output file extension */
967 private String extout=null;
968
969 /** For calculating kmer cardinality in output */
970 final CardinalityTracker loglogOut;
971
972 /*--------------------------------------------------------------*/
973
974 /** Number of reads processed */
975 public long readsProcessed=0;
976 /** Number of bases processed */
977 public long basesProcessed=0;
978 /** Number of reads trimmed */
979 public long readsTrimmed=0;
980 /** Number of bases trimmed */
981 public long basesTrimmed=0;
982 protected long readsMerged=0;
983
984 /** Number of reads retained */
985 public long readsOut=0;
986 /** Number of bases retained */
987 public long basesOut=0;
988
989 /** Quit after processing this many input reads; -1 means no limit */
990 private long maxReads=-1;
991
992 public static long lastReadsOut=-1;
993 public static long lastReadsRemoved=-1;
994 public static long lastBasesOut=-1;
995 public static long lastBasesRemoved=-1;
996
997 /*--------------------------------------------------------------*/
998 /*---------------- Final Fields ----------------*/
999 /*--------------------------------------------------------------*/
1000
1001 /** Primary input file */
1002 final FileFormat ffin1;
1003 /** Secondary input file */
1004 final FileFormat ffin2;
1005
1006 /** Primary output file */
1007 private final FileFormat ffout1;
1008 /** Secondary output file */
1009 private final FileFormat ffout2;
1010
1011 /** Primary output file for matching reads */
1012 private final FileFormat ffoutm1;
1013 /** Secondary output file for matching reads */
1014 private final FileFormat ffoutm2;
1015
1016 final BloomFilter filter;
1017
1018 final int kbloom;
1019 final int ksmall;
1020 final int hashes;
1021 final int bits;
1022 final boolean rcomp;
1023 final boolean tossjunk;
1024 final boolean merge;
1025 int junkWidth=1;
1026 float memFraction=1.0f;
1027 float maxLoad=1.0f; //Crash if this is exceeded
1028
1029 int trimLeft=6;
1030 int trimRight=6;
1031 int minLength=50;
1032 int maxNonPoly=2;
1033
1034 int kpoly=29;
1035 int hdist=2;
1036 long midMask=-1;
1037 long kmerMask=-1;
1038 boolean maskMiddle=true;
1039 LongHashSet set=null;
1040
1041 int minCount=2;
1042 float lowCountFraction=0.24f;
1043 float lowCountFraction2=1.1f;
1044 int minPolymer=20;
1045 int minPolymer2=29;
1046 float entropyCutoff=0.67f;
1047 float entropyCutoff2=0.20f;
1048 float qualityCutoff=12.5f;
1049 float qualityCutoff2=7.5f;
1050 float nonPolyFraction=1-0.85f;//0.15f;//These numbers are slightly different.
1051 byte[] polymers="GC".getBytes();
1052 byte[] trimPolymers=null;
1053
1054 long[] polymerFlagged;
1055 long entropyFlagged;
1056 long qualityFlagged;
1057 long depthFlagged;
1058
1059 boolean entropyHighpass=true;
1060
1061 /** Quantize quality scores to reduce file size */
1062 boolean quantizeQuality=false;
1063
1064 /*--------------------------------------------------------------*/
1065 /*---------------- Common Fields ----------------*/
1066 /*--------------------------------------------------------------*/
1067
1068 /** Print status messages to this output stream */
1069 private PrintStream outstream=System.err;
1070 /** Print verbose messages */
1071 public static boolean verbose=false;
1072 /** True if an error was encountered */
1073 public boolean errorState=false;
1074 /** Overwrite existing output files */
1075 private boolean overwrite=true;
1076 /** Append to existing output files */
1077 private boolean append=false;
1078 /** Reads are output in input order */
1079 private boolean ordered=false;
1080
1081 }