Debian Codegraph @

current/sketch/KmerLimit2.java

raw symbols SCIP
1 package sketch;
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.Random;
8
9 import dna.AminoAcid;
10 import fileIO.ByteFile;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import shared.Parse;
14 import shared.Parser;
15 import shared.PreParser;
16 import shared.Shared;
17 import shared.Timer;
18 import shared.Tools;
19 import stream.ConcurrentReadInputStream;
20 import stream.ConcurrentReadOutputStream;
21 import stream.FASTQ;
22 import stream.FastaReadInputStream;
23 import stream.Read;
24 import structures.IntMap;
25 import structures.ListNum;
26 import tracker.ReadStats;
27
28 /**
29 *
30 * @author Brian Bushnell
31 * @date July 30, 2018
32 *
33 */
34 public class KmerLimit2 extends SketchObject {
35
36 /*--------------------------------------------------------------*/
37 /*---------------- Initialization ----------------*/
38 /*--------------------------------------------------------------*/
39
40 /**
41 * Code entrance from the command line.
42 * @param args Command line arguments
43 */
44 public static void main(String[] args){
45 //Start a timer immediately upon code entrance.
46 Timer t=new Timer();
47
48 //Create an instance of this class
49 KmerLimit2 x=new KmerLimit2(args);
50
51 //Run the object
52 x.process(t);
53
54 //Close the print stream if it was redirected
55 Shared.closeStream(x.outstream);
56 }
57
58 /**
59 * Constructor.
60 * @param args Command line arguments
61 */
62 public KmerLimit2(String[] args){
63
64 {//Preparse block for help, config files, and outstream
65 PreParser pp=new PreParser(args, getClass(), false);
66 args=pp.args;
67 outstream=pp.outstream;
68 }
69
70 boolean setInterleaved=false; //Whether interleaved was explicitly set.
71
72 //Set shared static variables
73 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
74 ReadWrite.setZipThreads(Shared.threads());
75 SketchObject.setKeyFraction(0.1);
76 defaultParams.minEntropy=0;
77 defaultParams.minProb=0.2f;
78
79 boolean setHeapSize=false;
80 int heapSize_=8091;
81 long targetKmers_=0;
82 int k_=32;
83 int minCount_=1;
84
85 //Create a parser object
86 Parser parser=new Parser();
87 parser.overwrite=true;
88
89 //Parse each argument
90 for(int i=0; i<args.length; i++){
91 String arg=args[i];
92
93 //Break arguments into their constituent parts, in the form of "a=b"
94 String[] split=arg.split("=");
95 String a=split[0].toLowerCase();
96 String b=split.length>1 ? split[1] : null;
97 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
98
99 if(a.equals("verbose")){
100 verbose=Parse.parseBoolean(b);
101 }else if(a.equals("ordered")){
102 ordered=Parse.parseBoolean(b);
103 }else if(a.equals("size") || a.equals("heapsize")){
104 heapSize_=Parse.parseIntKMG(b);
105 setHeapSize=true;
106 }else if(a.equals("kmers") || a.equals("target") || a.equals("limit")){
107 targetKmers_=Parse.parseKMG(b);
108 }else if(a.equals("mincount")){
109 minCount_=Parse.parseIntKMG(b);
110 }else if(a.equals("maxexpandedlength") || a.equals("maxlength") || a.equals("maxlen")){
111 maxExpandedLength=Parse.parseIntKMG(b);
112 }else if(a.equals("seed")){
113 seed=Parse.parseKMG(b);
114 }else if(a.equals("trials")){
115 trials=Parse.parseIntKMG(b);
116 }else if(parseSketchFlags(arg, a, b)){
117 parser.parse(arg, a, b);
118 }else if(defaultParams.parse(arg, a, b)){
119 parser.parse(arg, a, b);
120 }else if(a.equals("parse_flag_goes_here")){
121 long fake_variable=Parse.parseKMG(b);
122 //Set a variable here
123 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
124 //do nothing
125 }else{
126 outstream.println("Unknown parameter "+args[i]);
127 assert(false) : "Unknown parameter "+args[i];
128 }
129 }
130
131 if(!setHeapSize && minCount_>1){heapSize_=32000;}
132 heapSize=heapSize_;
133 targetKmers=targetKmers_;
134 k=k_;
135 minCount=minCount_;
136 assert(targetKmers>0) : "Must set a kmer limit.";
137 assert(heapSize>0) : "Heap size must be positive.";
138 assert(k>0 && k<=32) : "0<k<33; k="+k;
139 postParse();
140
141 // if(minCount>1){
142 // Shared.setBufferLen(800);
143 // }
144
145 {//Process parser fields
146 Parser.processQuality();
147
148 maxReads=parser.maxReads;
149
150 overwrite=ReadStats.overwrite=parser.overwrite;
151 append=ReadStats.append=parser.append;
152 setInterleaved=parser.setInterleaved;
153
154 in1=parser.in1;
155 in2=parser.in2;
156 qfin1=parser.qfin1;
157 qfin2=parser.qfin2;
158
159 out1=parser.out1;
160 out2=parser.out2;
161 qfout1=parser.qfout1;
162 qfout2=parser.qfout2;
163
164 extin=parser.extin;
165 extout=parser.extout;
166 }
167
168 //Do input file # replacement
169 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
170 in2=in1.replace("#", "2");
171 in1=in1.replace("#", "1");
172 }
173
174 //Do output file # replacement
175 if(out1!=null && out2==null && out1.indexOf('#')>-1){
176 out2=out1.replace("#", "2");
177 out1=out1.replace("#", "1");
178 }
179
180 //Adjust interleaved detection based on the number of input files
181 if(in2!=null){
182 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
183 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
184 }
185
186 assert(FastaReadInputStream.settingsOK());
187
188 //Ensure there is an input file
189 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
190
191 //Adjust the number of threads for input file reading
192 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
193 ByteFile.FORCE_MODE_BF2=true;
194 }
195
196 //Ensure out2 is not set without out1
197 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
198
199 //Adjust interleaved settings based on number of output files
200 if(!setInterleaved){
201 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
202 if(in2!=null){ //If there are 2 input streams.
203 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
204 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
205 }else{ //There is one input stream.
206 if(out2!=null){
207 FASTQ.FORCE_INTERLEAVED=true;
208 FASTQ.TEST_INTERLEAVED=false;
209 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
210 }
211 }
212 }
213
214 //Ensure output files can be written
215 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
216 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
217 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
218 }
219
220 //Ensure input files can be read
221 if(!Tools.testInputFiles(false, true, in1, in2)){
222 throw new RuntimeException("\nCan't read some input files.\n");
223 }
224
225 //Ensure that no file was specified multiple times
226 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2)){
227 throw new RuntimeException("\nSome file names were specified multiple times.\n");
228 }
229
230 //Create output FileFormat objects
231 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
232 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
233
234 //Create input FileFormat objects
235 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
236 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
237
238 minProb=defaultParams.minProb;
239 minQual=defaultParams.minQual;
240
241 shift=2*k;
242 shift2=shift-2;
243 mask=(shift>63 ? -1L : ~((-1L)<<shift)); //Conditional allows K=32
244 sharedHeap=new SketchHeap(heapSize, 0, true);
245 }
246
247 /*--------------------------------------------------------------*/
248 /*---------------- Outer Methods ----------------*/
249 /*--------------------------------------------------------------*/
250
251 /** Create read streams and process all data */
252 void process(Timer t){
253
254 //Turn off read validation in the input threads to increase speed
255 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
256 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
257
258 // //Optionally create a read output stream
259 // final ConcurrentReadOutputStream ros;
260 // if(ffout1!=null){
261 // //Select output buffer size based on whether it needs to be ordered
262 // final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
263 //
264 // //Notify user of output mode
265 // if(cris.paired() && out2==null && (in1!=null && !ffin1.samOrBam() && !ffout1.samOrBam())){
266 // outstream.println("Writing interleaved.");
267 // }
268 //
269 // ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, false);
270 // ros.start(); //Start the stream
271 // }else{ros=null;}
272
273 //Reset counters
274 readsProcessed=readsOut=0;
275 basesProcessed=basesOut=0;
276
277 //Process the reads in separate threads
278 spawnThreads0();
279
280 // if(verbose){outstream.println("Finished; closing streams.");}
281
282 //Reset read validation
283 Read.VALIDATE_IN_CONSTRUCTOR=vic;
284
285
286 Sketch sketch=new Sketch(sharedHeap, true, true, null);
287 sketch=capLengthAtCountSum(sketch, maxExpandedLength);
288 final long reads=Tools.max(1, sketch.genomeSequences);
289 final long targetReads=calcTargetReads(sketch, targetKmers, minCount, trials, seed);
290 final double targetRate=Tools.min(1, targetReads/(double)reads);
291 final String targetRateS=Tools.format("%.4f%%",targetRate*100);
292
293 //Report timing and results
294 t.stop();
295 outstream.println("Finished counting kmers.");
296 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
297
298 String kstring0=Tools.padKMB(sketch.genomeSizeEstimate(minCount), 8);
299 String rstring0=Tools.padKMB(targetReads, 8);
300 outstream.println("Unique Kmers: "+kstring0);
301 outstream.println("Target Reads: "+rstring0+"\t"+targetRateS);
302
303 // outstream.println("Reads: \t"+reads);
304 // outstream.println("Unique Kmers: \t"+sketch.genomeSizeEstimate(minCount));
305 // outstream.println("Target Reads: \t"+targetReads);
306 // outstream.println("Sample Rate: \t"+targetRateS);
307 // outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
308
309 t.start();
310 outstream.println("\nSubsampling reads.");
311
312 // String kstring=Tools.padKM(sharedHeap.genomeSizeEstimate(minCount), 8);
313 // outstream.println("Unique Kmers Out: "+kstring);
314
315
316 // ArrayList<String> args=new ArrayList<String>();
317 // args.add("in="+in1);
318 // if(in2!=null){args.add("in2="+in2);}
319 // args.add("out="+out1);
320 // if(out2!=null){args.add("out2="+out2);}
321 // args.add("ordered="+ordered);
322 // args.add("ow="+(overwrite ? "t" : "f"));
323 // if(targetRate<1){args.add("samplerate="+targetRateS);}
324 // args.add("loglogout");
325 // args.add("loglogk="+k);
326 // args.add("loglogminprob="+minProb);
327 // BBDukF.main(args.toArray(new String[0]));
328
329 // Sketch sk=new Sketch(sharedHeap, true, true, null);
330 // outstream.println(sk.genomeSizeEstimate());
331 spawnThreads2(targetRate);
332 t.stop();
333 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
334
335 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
336 String kstring=Tools.padKMB(sharedHeap.genomeSizeEstimate(minCount), 8);
337 outstream.println("Unique Kmers Out: "+kstring);
338
339 //Throw an exception of there was an error in a thread
340 if(errorState){
341 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
342 }
343 }
344
345 /** Spawn process threads */
346 private void spawnThreads0(){
347
348 //Create a read input stream
349 final ConcurrentReadInputStream cris;
350 {
351 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
352 cris.start(); //Start the stream
353 if(verbose){outstream.println("Started cris");}
354 }
355 paired=cris.paired();
356 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
357
358 //Determine how many threads may be used
359 final int threads=Tools.min(10, Shared.threads());
360
361 //Fill a list with ProcessThreads
362 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
363 for(int i=0; i<threads; i++){
364 alpt.add(new ProcessThread(cris, null, i, heapSize));
365 }
366
367 //Start the threads
368 for(ProcessThread pt : alpt){
369 pt.start();
370 }
371
372 //Wait for completion of all threads
373 boolean success=true;
374 for(ProcessThread pt : alpt){
375
376 //Wait until this thread has terminated
377 while(pt.getState()!=Thread.State.TERMINATED){
378 try {
379 //Attempt a join operation
380 pt.join();
381 } catch (InterruptedException e) {
382 //Potentially handle this, if it is expected to occur
383 e.printStackTrace();
384 }
385 }
386
387 //Accumulate per-thread statistics
388 readsProcessed+=pt.readsProcessedT;
389 basesProcessed+=pt.basesProcessedT;
390 readsOut+=pt.readsOutT;
391 basesOut+=pt.basesOutT;
392 success&=pt.success;
393 }
394
395 //Track whether any threads failed
396 if(!success){errorState=true;}
397
398 //Do anything necessary after processing
399
400 //Close the read streams
401 errorState|=ReadWrite.closeStreams(cris);
402
403 }
404
405 /** Spawn process threads */
406 private void spawnThreads2(double rate){
407
408 //Create a read input stream
409 final ConcurrentReadInputStream cris;
410 {
411 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
412 cris.setSampleRate((float)rate, seed);
413 cris.start(); //Start the stream
414 if(verbose){outstream.println("Started cris");}
415 }
416 // paired=cris.paired();
417 // if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
418
419 //Optionally create a read output stream
420 final ConcurrentReadOutputStream ros;
421 if(ffout1!=null){
422 //Select output buffer size based on whether it needs to be ordered
423 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
424
425 //Notify user of output mode
426 if(cris.paired() && out2==null && (in1!=null && !ffin1.samOrBam() && !ffout1.samOrBam())){
427 outstream.println("Writing interleaved.");
428 }
429
430 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, false);
431 ros.start(); //Start the stream
432 }else{ros=null;}
433
434 //Determine how many threads may be used
435 final int threads=Tools.min(10, Shared.threads());
436
437 sharedHeap.clear();
438 // readsProcessed=0;
439 // basesProcessed=0;
440 readsOut=0;
441 basesOut=0;
442
443 //Fill a list with ProcessThreads
444 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
445 for(int i=0; i<threads; i++){
446 alpt.add(new ProcessThread(cris, ros, i, heapSize));
447 }
448
449 //Start the threads
450 for(ProcessThread pt : alpt){
451 pt.start();
452 }
453
454 //Wait for completion of all threads
455 boolean success=true;
456 for(ProcessThread pt : alpt){
457
458 //Wait until this thread has terminated
459 while(pt.getState()!=Thread.State.TERMINATED){
460 try {
461 //Attempt a join operation
462 pt.join();
463 } catch (InterruptedException e) {
464 //Potentially handle this, if it is expected to occur
465 e.printStackTrace();
466 }
467 }
468
469 //Accumulate per-thread statistics
470 // readsProcessed+=pt.readsProcessedT;
471 // basesProcessed+=pt.basesProcessedT;
472 readsOut+=pt.readsOutT;
473 basesOut+=pt.basesOutT;
474 success&=pt.success;
475 }
476
477 //Track whether any threads failed
478 if(!success){errorState=true;}
479
480 //Do anything necessary after processing
481
482 //Write anything that was accumulated by ReadStats
483 errorState|=ReadStats.writeAll();
484 //Close the read streams
485 errorState|=ReadWrite.closeStreams(cris, ros);
486
487 }
488
489 /*--------------------------------------------------------------*/
490 /*---------------- Inner Methods ----------------*/
491 /*--------------------------------------------------------------*/
492
493 public static Sketch capLengthAtCountSum(Sketch sketch0, int max) {
494 int len=0;
495 long sum=0;
496 for(; len<sketch0.keyCounts.length; len++){
497 sum=sum+sketch0.keyCounts[len];
498 if(sum>max){break;}
499 }
500 if(len>=sketch0.length()){return sketch0;}
501
502 long[] keys=Arrays.copyOf(sketch0.keys, len);
503 int[] counts=Arrays.copyOf(sketch0.keyCounts, len);
504
505 // long[] array_, int[] counts_, int taxID_, long imgID_, long gSizeBases_, long gSizeKmers_, long gSequences_, double probCorrect_,
506 // String taxName_, String name0_, String fname_, ArrayList<String> meta_
507
508 Sketch sk=new Sketch(keys, counts, null, null, null, -1, -1,
509 sketch0.genomeSizeBases, sketch0.genomeSizeKmers, sketch0.genomeSequences, sketch0.probCorrect,
510 null, null, null, null);
511
512 return sk;
513 }
514
515 public static long calcTargetReads(Sketch sketch, long targetKmers, int minCount, int trials, long seed){
516 final int[] counts0=sketch.keyCounts;
517 final int[] counts=Arrays.copyOf(counts0, counts0.length);
518 final long size=sketch.genomeSizeEstimate(minCount);
519 final long reads=sketch.genomeSequences;
520 final double targetKmerFraction=targetKmers/(double)size;
521 if(targetKmerFraction>=1){return reads;}
522
523 final int targetKeys=(int)(targetKmerFraction*counts.length);
524 final long countSum=shared.Vector.sum(counts0);
525 assert(countSum<Shared.MAX_ARRAY_LEN) : countSum;
526 // System.err.println("countsum: "+countSum);
527
528 final IntMap map=new IntMap(0, counts0.length);
529 final int[] expanded=new int[(int)countSum];
530
531 long roundSum=0;
532 final Random randy=Shared.threadLocalRandom(seed);
533 for(int i=0; i<trials; i++){
534 Tools.fill(counts, counts0);
535 // long rounds=reduceRounds(counts0, counts, minCount, targetKeys, randy);
536 long rounds=reduceRoundsIM(counts0, expanded, minCount, targetKeys, randy, map);
537 roundSum+=rounds;
538 }
539 double avgRounds=roundSum/(double)trials;
540 // System.err.println("avgRounds: "+avgRounds);
541 double targetCountFraction=1-(avgRounds/countSum);
542 // System.err.println("targetFraction: "+targetCountFraction);
543 return (long)(targetCountFraction*reads);
544 }
545
546 // public static int reduceRoundsOld(final int[] counts, final int minCount, final int targetKeys, final Random randy){
547 // assert(minCount>=0) : minCount;
548 // int rounds=0;
549 // int valid=0;
550 // for(int x : counts){
551 // if(x>=minCount){valid++;}
552 // }
553 //
554 // int len=counts.length;
555 // System.err.println(targetKeys+", "+counts.length+", "+valid+", "+len+", "+rounds+", "+shared.Vector.sum(counts)+", "+Arrays.toString(counts));
556 // for(; valid>targetKeys; rounds++){
557 // int pos=randy.nextInt(len);
558 //// assert(counts[pos]>0) : pos+"/"+len+": "+targetKeys+", "+counts.length+", "+valid+", "+len+", "+rounds+", "+Arrays.toString(counts);
559 // if(counts[pos]==minCount){valid--;}
560 // counts[pos]--;
561 // if(counts[pos]==0){
562 // len--;//shrink the array
563 // System.err.println("len="+len+", counts[len]="+counts[len]);
564 // System.err.println("pos="+pos+", counts[pos]="+counts[pos]);
565 // counts[pos]=counts[len];//move the last element to the empty slot
566 // counts[len]=0;
567 // if(pos!=len && len>0){
568 // assert(counts[pos]>0) : pos+"/"+len+": "+targetKeys+", "+counts.length+", "+valid+", "+len+", "+rounds+", "+Arrays.toString(counts);
569 // }
570 // }
571 // System.err.println(len+", "+pos+": "+Arrays.toString(counts));
572 // }
573 //
574 // System.err.println(targetKeys+", "+counts.length+", "+valid+", "+len+", "+rounds+", "+shared.Vector.sum(counts));
575 //
576 // return rounds;
577 // }
578
579 //This can be done faster with bins.
580 //Each bin contains all kmers with count x. When a bin is hit, one kmer moves to the next bin lower.
581 //Alternately, expand the array into one physical kmer per count. Store the current counts in an IntMap. Remove key each time.
582 public static long reduceRounds(final int[] counts0, final int[] counts, final int minCount, final int targetKeys, final Random randy){
583 assert(minCount>=0) : minCount;
584 long rounds=0;
585 int valid=0;
586 for(int x : counts){
587 if(x>=minCount){valid++;}
588 }
589
590 int len=counts.length;
591 final long sum0=shared.Vector.sum(counts);
592 long sum=sum0;
593 // System.err.println(targetKeys+", "+counts.length+", "+valid+", "+len+", "+rounds+", "+shared.Vector.sum(counts)+", "+Arrays.toString(counts));
594 for(; valid>targetKeys; rounds++){
595 long posNum=(Long.MAX_VALUE&randy.nextLong())%sum;
596 long sum2=0;
597 int pos=0;
598
599 for(int i=0; i<counts.length; i++){
600 int x=counts[i];
601 if(x>0){
602 sum2+=x;
603 if(sum2>=posNum){
604 pos=i;
605 break;
606 }
607 }
608 }
609
610 // for(int i=0; i<counts0.length; i++){
611 // int x=counts0[i];
612 // if(x>0){
613 // sum2+=x;
614 // if(sum2>=posNum){
615 // pos=i;
616 // break;
617 // }
618 // }
619 // }
620
621 sum--;
622
623 assert(counts[pos]>0) : pos+"/"+len+": "+targetKeys+", "+counts.length+", "+valid+", "+len+", "+rounds+", "+Arrays.toString(counts);
624 if(counts[pos]==minCount){valid--;}
625 counts[pos]--;
626 if(counts[pos]==0){
627 len--;//shrink the array
628 }
629 // System.err.println(len+", "+pos+": "+Arrays.toString(counts));
630 }
631
632 // System.err.println(targetKeys+", "+counts.length+", "+valid+", "+len+", "+rounds+", "+shared.Vector.sum(counts));
633
634 return rounds;
635 }
636
637 //This can be done faster with bins.
638 //Each bin contains all kmers with count x. When a bin is hit, one kmer moves to the next bin lower.
639 //Alternately, expand the array into one physical kmer per count. Store the current counts in an IntMap. Remove key each time.
640 public static long reduceRoundsIM(final int[] counts0, final int[] expanded, final int minCount, final int targetKeys, final Random randy, final IntMap map){
641 assert(minCount>=0) : minCount;
642 long rounds=0;
643 int valid=0;
644 map.clear();
645 for(int i=0, k=0; i<counts0.length; i++){
646 int x=counts0[i];
647 // counts[i]=counts0[i];
648 if(x>=minCount){valid++;}
649 map.put(i, x);
650 for(int j=0; j<x; j++, k++){
651 expanded[k]=i;
652 }
653 }
654 assert(expanded.length==shared.Vector.sum(counts0));
655
656 int len=expanded.length;
657 // System.err.println(targetKeys+", "+counts.length+", "+valid+", "+len+", "+rounds+", "+shared.Vector.sum(counts)+", "+Arrays.toString(counts));
658 for(; valid>targetKeys; rounds++){
659 final int pos=randy.nextInt(len);
660 final int key=expanded[pos];
661 final int x=map.get(key);
662 assert(x>0);
663
664
665 if(x==minCount){valid--;}
666 map.put(key, x-1);
667
668 len--;//shrink the array
669 // System.err.println("len="+len+", counts[len]="+counts[len]);
670 // System.err.println("pos="+pos+", counts[pos]="+counts[pos]);
671 expanded[pos]=expanded[len];//move the last element to the empty slot
672 expanded[len]=0;
673
674 // System.err.println(len+", "+pos+": "+Arrays.toString(counts));
675 }
676
677 // System.err.println(targetKeys+", "+counts.length+", "+valid+", "+len+", "+rounds+", "+shared.Vector.sum(counts));
678
679 return rounds;
680 }
681
682 /*--------------------------------------------------------------*/
683 /*---------------- Inner Classes ----------------*/
684 /*--------------------------------------------------------------*/
685
686 /** This class is static to prevent accidental writing to shared variables.
687 * It is safe to remove the static modifier. */
688 private class ProcessThread extends Thread {
689
690 //Constructor
691 ProcessThread(final ConcurrentReadInputStream cris_, final ConcurrentReadOutputStream ros_, final int tid_, final int size){
692 cris=cris_;
693 ros=ros_;
694 tid=tid_;
695 localHeap=new SketchHeap(size, 0, true);
696 }
697
698 //Called by start()
699 @Override
700 public void run(){
701 //Do anything necessary prior to processing
702
703 //Process the reads
704 processInner();
705
706 //Do anything necessary after processing
707 dumpHeap();
708
709 //Indicate successful exit status
710 success=true;
711 }
712
713 /** Iterate through the reads */
714 void processInner(){
715
716 //Grab the first ListNum of reads
717 ListNum<Read> ln=cris.nextList();
718 //Grab the actual read list from the ListNum
719 ArrayList<Read> reads=(ln!=null ? ln.list : null);
720
721 //Check to ensure pairing is as expected
722 if(reads!=null && !reads.isEmpty()){
723 Read r=reads.get(0);
724 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
725 }
726
727 //As long as there is a nonempty read list...
728 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
729 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
730
731 //Loop through each read in the list
732 for(int idx=0; idx<reads.size(); idx++){
733 final Read r1=reads.get(idx);
734 final Read r2=r1.mate;
735
736 //Validate reads in worker threads
737 if(!r1.validated()){r1.validate(true);}
738 if(r2!=null && !r2.validated()){r2.validate(true);}
739
740 //Track the initial length for statistics
741 final int initialLength1=r1.length();
742 final int initialLength2=r1.mateLength();
743
744 //Increment counters
745 readsProcessedT+=r1.pairCount();
746 basesProcessedT+=initialLength1+initialLength2;
747
748 //Reads are processed in this block.
749 processReadPair(r1, r2);
750 }
751
752 if(ros!=null){
753 for(Read r1 : reads){
754 readsOutT+=r1.pairCount();
755 basesOutT+=r1.pairLength();
756 }
757
758 //Output reads to the output stream
759 if(ros!=null){ros.add(reads, ln.id);}
760 }
761
762 //Notify the input stream that the list was used
763 cris.returnList(ln);
764 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
765
766 //Fetch a new list
767 ln=cris.nextList();
768 reads=(ln!=null ? ln.list : null);
769 }
770
771 //Notify the input stream that the final list was used
772 if(ln!=null){
773 if(ln.list!=null){ln.list.clear();}
774 cris.returnList(ln.id, true);
775 }
776 }
777
778 /**
779 * Process a read or a read pair.
780 * @param r1 Read 1
781 * @param r2 Read 2 (may be null)
782 */
783 void processReadPair(final Read r1, final Read r2){
784 processReadNucleotide(r1);
785 if(r2!=null){processReadNucleotide(r2);}
786 }
787
788 void processReadNucleotide(final Read r){
789 final byte[] bases=r.bases;
790 final byte[] quals=r.quality;
791 long kmer=0;
792 long rkmer=0;
793 int len=0;
794 assert(!r.aminoacid());
795
796 final long min=minHashValue;
797 localHeap.genomeSizeBases+=r.length();
798 localHeap.genomeSequences++;
799
800 if(quals==null || (minProb<=0 && minQual<2)){
801 for(int i=0; i<bases.length; i++){
802 byte b=bases[i];
803 long x=AminoAcid.baseToNumber[b];
804 long x2=AminoAcid.baseToComplementNumber[b];
805
806 kmer=((kmer<<2)|x)&mask;
807 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
808
809 if(x<0){len=0; rkmer=0;}else{len++;}
810 if(len>=k){
811 localHeap.genomeSizeKmers++;
812 final long hashcode=hash(kmer, rkmer);
813 if(hashcode>min){localHeap.add(hashcode);}
814 }
815 }
816 }else{
817 float prob=1;
818 for(int i=0; i<bases.length; i++){
819 final byte b=bases[i];
820 final long x=AminoAcid.baseToNumber[b];
821 final long x2=AminoAcid.baseToComplementNumber[b];
822
823 {//Quality-related stuff
824 final byte q=quals[i];
825 assert(q>=0) : Arrays.toString(quals)+"\n"+minProb+", "+minQual;
826 prob=prob*align2.QualityTools.PROB_CORRECT[q];
827 if(len>k){
828 byte oldq=quals[i-k];
829 prob=prob*align2.QualityTools.PROB_CORRECT_INVERSE[oldq];
830 }
831 if(x<0 || q<minQual){
832 len=0;
833 kmer=rkmer=0;
834 prob=1;
835 }else{
836 len++;
837 }
838 }
839
840 kmer=((kmer<<2)|x)&mask;
841 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
842
843 if(len>=k && prob>=minProb){
844 localHeap.genomeSizeKmers++;
845 localHeap.probSum+=prob;
846 final long hashcode=hash(kmer, rkmer);
847 if(hashcode>min){localHeap.checkAndAdd(hashcode);}
848 }
849 }
850 }
851 }
852
853 private void dumpHeap(){
854 synchronized(sharedHeap){
855 sharedHeap.add(localHeap);
856 }
857 }
858
859 /** Number of reads processed by this thread */
860 protected long readsProcessedT=0;
861 /** Number of bases processed by this thread */
862 protected long basesProcessedT=0;
863
864 /** Number of reads retained by this thread */
865 protected long readsOutT=0;
866 /** Number of bases retained by this thread */
867 protected long basesOutT=0;
868
869 /** True only if this thread has completed successfully */
870 boolean success=false;
871
872 /** Shared input stream */
873 private final ConcurrentReadInputStream cris;
874 /** Shared output stream */
875 private final ConcurrentReadOutputStream ros;
876 /** Thread ID */
877 final int tid;
878
879 final SketchHeap localHeap;
880 }
881
882 /*--------------------------------------------------------------*/
883 /*---------------- Fields ----------------*/
884 /*--------------------------------------------------------------*/
885
886 /** Primary input file path */
887 private String in1=null;
888 /** Secondary input file path */
889 private String in2=null;
890
891 private String qfin1=null;
892 private String qfin2=null;
893
894 /** Primary output file path */
895 private String out1=null;
896 /** Secondary output file path */
897 private String out2=null;
898
899 private String qfout1=null;
900 private String qfout2=null;
901
902 /** Override input file extension */
903 private String extin=null;
904 /** Override output file extension */
905 private String extout=null;
906
907 /*--------------------------------------------------------------*/
908
909 /** Number of reads processed */
910 protected long readsProcessed=0;
911 /** Number of bases processed */
912 protected long basesProcessed=0;
913
914 /** Number of reads retained */
915 protected long readsOut=0;
916 /** Number of bases retained */
917 protected long basesOut=0;
918
919 /** Quit after processing this many input reads; -1 means no limit */
920 private long maxReads=-1;
921
922 private boolean paired=false;
923 private int trials=25;
924 private long seed=-1;
925 private int maxExpandedLength=50000000;
926
927 /*--------------------------------------------------------------*/
928 /*---------------- Final Fields ----------------*/
929 /*--------------------------------------------------------------*/
930
931 /** Primary input file */
932 private final FileFormat ffin1;
933 /** Secondary input file */
934 private final FileFormat ffin2;
935
936 /** Primary output file */
937 private final FileFormat ffout1;
938 /** Secondary output file */
939 private final FileFormat ffout2;
940
941 private final SketchHeap sharedHeap;
942 private final int heapSize;
943 private final long targetKmers;
944 private final int minCount;
945
946 final int shift;
947 final int shift2;
948 final long mask;
949
950 final float minProb;
951 final byte minQual;
952
953 /*--------------------------------------------------------------*/
954 /*---------------- Common Fields ----------------*/
955 /*--------------------------------------------------------------*/
956
957 /** Print status messages to this output stream */
958 private PrintStream outstream=System.err;
959 /** Print verbose messages */
960 public static boolean verbose=false;
961 /** True if an error was encountered */
962 public boolean errorState=false;
963 /** Overwrite existing output files */
964 private boolean overwrite=true;
965 /** Append to existing output files */
966 private boolean append=false;
967 /** Reads are output in input order (not enabled) */
968 private boolean ordered=true;
969
970 }