Debian Codegraph @

current/sketch/BlacklistMaker.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.HashMap;
7 import java.util.Map.Entry;
8 import java.util.concurrent.atomic.AtomicInteger;
9
10 import bloom.KCountArray;
11 import bloom.KmerCountAbstract;
12 import bloom.ReadCounter;
13 import dna.AminoAcid;
14 import fileIO.ByteFile;
15 import fileIO.ByteStreamWriter;
16 import fileIO.FileFormat;
17 import fileIO.ReadWrite;
18 import shared.Parse;
19 import shared.Parser;
20 import shared.PreParser;
21 import shared.Shared;
22 import shared.Timer;
23 import shared.Tools;
24 import stream.ConcurrentReadInputStream;
25 import stream.FASTQ;
26 import stream.FastaReadInputStream;
27 import stream.Read;
28 import structures.IntList;
29 import structures.IntListCompressor;
30 import structures.ListNum;
31 import structures.LongList;
32 import tax.AccessionToTaxid;
33 import tax.GiToTaxid;
34 import tax.TaxNode;
35 import tax.TaxTree;
36 import tracker.EntropyTracker;
37
38 /**
39 * Makes blacklists in a taxa-aware manner.
40 *
41 * @author Brian Bushnell
42 * @date April 3, 2017
43 *
44 */
45 public class BlacklistMaker extends SketchObject {
46
47 /*--------------------------------------------------------------*/
48 /*---------------- Initialization ----------------*/
49 /*--------------------------------------------------------------*/
50
51 /**
52 * Code entrance from the command line.
53 * @param args Command line arguments
54 */
55 public static void main(String[] args){
56 //Start a timer immediately upon code entrance.
57 Timer t=new Timer();
58
59 ReadCounter.maxShortKmerLength=32;
60
61 //Create an instance of this class
62 BlacklistMaker x=new BlacklistMaker(args);
63
64 //Run the object
65 x.process(t);
66
67 ReadCounter.maxShortKmerLength=31;
68
69 //Close the print stream if it was redirected
70 Shared.closeStream(x.outstream);
71 }
72
73 /**
74 * Constructor.
75 * @param args Command line arguments
76 */
77 @SuppressWarnings("unchecked")
78 public BlacklistMaker(String[] args){
79
80 {//Preparse block for help, config files, and outstream
81 PreParser pp=new PreParser(args, getClass(), false);
82 args=pp.args;
83 outstream=pp.outstream;
84 }
85
86 //Set shared static variables
87 if(Shared.threads()>=32){Shared.capThreads(Shared.threads()/2);}//Deals with hyperthreading, which causes excessive memory usage
88 Shared.capBuffers(Tools.max(4, Shared.threads()+1));
89 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
90 ReadWrite.setZipThreads(Shared.threads());
91 KmerCountAbstract.SKETCH_MODE=true;
92 KmerCountAbstract.STORE_HASHED=true;
93 KmerCountAbstract.KEEP_DUPLICATE_KMERS=true;
94
95 //Create a parser object
96 Parser parser=new Parser();
97
98 int mode_=PER_SEQUENCE;
99 hashNames=true;
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 }else if(a.equals("parse_flag_goes_here")){
115 long fake_variable=Parse.parseKMG(b);
116 //Set a variable here
117 }
118
119
120 else if(a.equals("table") || a.equals("gi") || a.equals("gitable")){
121 if(b==null || "ignore".equalsIgnoreCase(b) || "skip".equalsIgnoreCase(b)){
122 giTableFile=null;
123 TaxTree.CRASH_IF_NO_GI_TABLE=false;
124 }else{giTableFile=b;}
125 }else if(a.equals("taxtree") || a.equals("tree")){
126 taxTreeFile=b;
127 }else if(a.equals("accession")){
128 accessionFile=b;
129 }else if(a.equals("imgfile") || a.equals("imgdump")){
130 imgFile=b;
131 }
132
133
134 else if(a.equals("mincount") || a.equals("mintaxcount")){
135 minTaxCount=Parse.parseIntKMG(b);
136 }else if(a.equals("prefilter")){
137 prefilter=Parse.parseBoolean(b);
138 }else if(a.equals("prepasses") || a.equals("passes")){
139 assert(b!=null) : "Bad parameter: "+arg;
140 if(b.equalsIgnoreCase("auto")){
141 prepasses=2;
142 autoPasses=true;
143 }else{
144 prepasses=Integer.parseInt(b);
145 autoPasses=false;
146 }
147 }else if(a.equals("prehashes") || a.equals("hashes")){
148 prehashes=Integer.parseInt(b);
149 }else if(a.equals("prebits") || a.equals("bits")){
150 prebits=Integer.parseInt(b);
151 }else if(a.equals("name")){
152 outName=b;
153 }else if(a.equalsIgnoreCase("name0") || a.equalsIgnoreCase("nm0")){
154 sketchName=b;
155 }else if(a.equals("taxid") || a.equals("tid")){
156 outTaxid=Integer.parseInt(b);
157 }else if(parseMode(arg, a, b)>-1){
158 mode_=parseMode(arg, a, b);
159 }else if(a.equals("hist")){
160 outHist=b;
161 }
162
163 else if(a.equals("taxlevel") || a.equals("tl") || a.equals("level") || a.equals("lv")){
164 if(b==null){taxLevel=-1;}
165 else if(Tools.isDigit(b.charAt(0))){
166 taxLevel=Integer.parseInt(b);
167 }else{
168 taxLevel=TaxTree.parseLevel(b);
169 }
170 }
171
172 else if(parseSketchFlags(arg, a, b)){
173 //do nothing
174 }else if(defaultParams.parse(arg, a, b)){
175 //do nothing
176 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
177 //do nothing
178 }else{
179 outstream.println("Unknown parameter "+args[i]);
180 assert(false) : "Unknown parameter "+args[i];
181 }
182 }
183
184 if("auto".equalsIgnoreCase(imgFile)){imgFile=TaxTree.defaultImgFile();}
185 if("auto".equalsIgnoreCase(taxTreeFile)){taxTreeFile=TaxTree.defaultTreeFile();}
186 if("auto".equalsIgnoreCase(giTableFile)){giTableFile=TaxTree.defaultTableFile();}
187 if("auto".equalsIgnoreCase(accessionFile)){accessionFile=TaxTree.defaultAccessionFile();}
188
189 mode=mode_;
190 assert((mode!=PER_TAXA && mode!=PER_IMG) || taxTreeFile!=null);
191 assert(mode!=PER_IMG || imgFile!=null);
192 assert(mode==PER_TAXA || mode==PER_SEQUENCE || mode==PER_IMG);
193
194 {//Process parser fields
195 Parser.processQuality();
196
197 maxReads=parser.maxReads;
198
199 overwrite=parser.overwrite;
200 append=parser.append;
201
202 in1=parser.in1;
203 in2=parser.in2;
204
205 outSketch=parser.out1;
206
207 extin=parser.extin;
208 }
209
210 postParse();
211
212 //Do input file # replacement
213 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
214 in2=in1.replace("#", "2");
215 in1=in1.replace("#", "1");
216 }
217
218 //Adjust interleaved detection based on the number of input files
219 if(in2!=null){
220 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
221 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
222 }
223
224 assert(FastaReadInputStream.settingsOK());
225
226 //Ensure there is an input file
227 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
228
229 //Adjust the number of threads for input file reading
230 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
231 ByteFile.FORCE_MODE_BF2=true;
232 }
233
234 //Ensure output files can be written
235 if(!Tools.testOutputFiles(overwrite, append, false, outSketch)){
236 outstream.println((outSketch==null)+", "+outSketch);
237 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+outSketch+"\n");
238 }
239
240 //Ensure input files can be read
241 if(!Tools.testInputFiles(false, true, in1, in2)){
242 throw new RuntimeException("\nCan't read some input files.\n");
243 }
244
245 //Ensure that no file was specified multiple times
246 if(!Tools.testForDuplicateFiles(true, in1, in2, outSketch, outHist)){
247 throw new RuntimeException("\nSome file names were specified multiple times.\n");
248 }
249
250 if(sketchName==null && outSketch!=null){
251 sketchName=outSketch;
252 sketchName=ReadWrite.stripToCore(sketchName);
253 }
254
255 //Create output FileFormat objects
256 ffsketch=FileFormat.testOutput(outSketch, FileFormat.SKETCH, null, true, overwrite, append, false);
257 ffhist=FileFormat.testOutput(outHist, FileFormat.TXT, null, true, overwrite, append, false);
258
259 //Create input FileFormat objects
260 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
261 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
262
263 // tool=new SketchTool(targetSketchSize, defaultParams.minKeyOccuranceCount, false, false);
264
265 if(taxTreeFile!=null){setTaxtree(taxTreeFile, outstream);}
266
267 if(giTableFile!=null){
268 loadGiToTaxid();
269 }
270 if(accessionFile!=null){
271 AccessionToTaxid.tree=taxtree;
272 outstream.println("Loading accession table.");
273 AccessionToTaxid.load(accessionFile);
274 System.gc();
275 }
276 if(imgFile!=null){
277 TaxTree.loadIMG(imgFile, false, outstream);
278 }
279
280 maps=new HashMap[ways];
281 for(int i=0; i<ways; i++){
282 maps[i]=new HashMap<Long, IntListCompressor>();
283 }
284
285 calcMemory();
286
287
288 }
289
290 /*--------------------------------------------------------------*/
291 /*---------------- Outer Methods ----------------*/
292 /*--------------------------------------------------------------*/
293
294 /** Create read streams and process all data */
295 void process(Timer t){
296
297 if(prefilter){
298 makePrefilter();
299 }
300
301 //Turn off read validation in the input threads to increase speed
302 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
303 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
304
305 //Create a read input stream
306 final ConcurrentReadInputStream cris;
307 {
308 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, null, null);
309 cris.start(); //Start the stream
310 if(verbose){outstream.println("Started cris");}
311 }
312 boolean paired=cris.paired();
313 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
314
315 //Reset counters
316 readsProcessed=0;
317 basesProcessed=0;
318
319 //Process the reads in separate threads
320 spawnThreads(cris);
321
322 prefilterArray=null;
323
324 if(verbose){outstream.println("Finished; closing streams.");}
325
326 //Close the read streams
327 errorState|=ReadWrite.closeStreams(cris);
328
329 //Reset read validation
330 Read.VALIDATE_IN_CONSTRUCTOR=vic;
331
332 //Report timing and results
333 t.stop();
334 outstream.println("Blacklist size: \t"+resultingSize+"\n");
335 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
336
337 //Throw an exception of there was an error in a thread
338 if(errorState){
339 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
340 }
341 }
342
343 /** Spawn process threads */
344 private void spawnThreads(final ConcurrentReadInputStream cris){
345
346 //Do anything necessary prior to processing
347
348 //Determine how many threads may be used
349 final int threads=Shared.threads();
350
351 //Fill a list with ProcessThreads
352 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
353 for(int i=0; i<threads; i++){
354 alpt.add(new ProcessThread(cris, i));
355 }
356
357 //Start the threads
358 for(ProcessThread pt : alpt){
359 pt.start();
360 }
361
362 //Wait for completion of all threads
363 boolean success=true;
364 for(ProcessThread pt : alpt){
365
366 //Wait until this thread has terminated
367 while(pt.getState()!=Thread.State.TERMINATED){
368 try {
369 //Attempt a join operation
370 pt.join();
371 } catch (InterruptedException e) {
372 //Potentially handle this, if it is expected to occur
373 e.printStackTrace();
374 }
375 }
376
377 //Accumulate per-thread statistics
378 readsProcessed+=pt.readsProcessedT;
379 basesProcessed+=pt.basesProcessedT;
380 success&=pt.success;
381 }
382
383 shrinkListsAndWriteHist();
384 writeSketch(true);
385
386 //Track whether any threads failed
387 if(!success){errorState=true;}
388
389 //Do anything necessary after processing
390
391 }
392
393 /*--------------------------------------------------------------*/
394 /*---------------- Inner Methods ----------------*/
395 /*--------------------------------------------------------------*/
396
397 private void writeSketch(boolean destroy){
398 Sketch sk=toSketch(destroy);
399 if(ffsketch!=null){errorState|=SketchTool.write(sk, ffsketch);}
400 }
401
402 private void shrinkListsAndWriteHist(){
403 int max=1000000;
404 long[] counts=new long[max+1];
405 for(int i=0; i<ways; i++){
406 for(Entry<Long, IntListCompressor> entry : maps[i].entrySet()){
407 IntList value=entry.getValue().list;
408 value.sort();
409 value.shrinkToUnique();
410 int index=Tools.min(max, value.size);
411 counts[index]++;
412 }
413 }
414 if(ffhist!=null){
415 ByteStreamWriter bsw=new ByteStreamWriter(ffhist);
416 bsw.start();
417 bsw.print("#count\tkmers\n".getBytes());
418 for(int i=0; i<counts.length; i++){
419 long count=counts[i];
420 if(count>0){
421 bsw.print(i);
422 bsw.print('\t');
423 bsw.print(count);
424 bsw.print('\n');
425 }
426 }
427 errorState|=bsw.poisonAndWait();
428 }
429 }
430
431 private Sketch toSketch(boolean destroy){
432 long[] array=toArray(destroy);
433 hashArrayToSketchArray(array);
434 ArrayList<String> meta=new ArrayList<String>();
435 meta.add("minTaxCount:"+minTaxCount);
436 meta.add("taxLevel:"+taxLevel);
437 Sketch sk=new Sketch(array, null, null, null, null, outTaxid, -1, -1, -1, -1, -1, "blacklist", sketchName, ffin1.simpleName(), meta);
438 return sk;
439 }
440
441 private long[] toArray(boolean destroy){
442 LongList list=new LongList();
443 for(int i=0; i<ways; i++){
444 for(Entry<Long, IntListCompressor> entry : maps[i].entrySet()){
445 Long key=entry.getKey();
446 IntList value=entry.getValue().list;
447 if(value.size()>=minTaxCount){
448 list.add(key.longValue());
449 }
450 }
451 if(destroy){maps[i]=null;}
452 }
453 resultingSize=list.size();
454 return list.toArray();
455 }
456
457 /*--------------------------------------------------------------*/
458 /*---------------- Prefilter ----------------*/
459 /*--------------------------------------------------------------*/
460
461 private void calcMemory(){
462 long usableMemory=Shared.memAvailableAdvanced();
463
464 // System.err.println(memory/1000000+", "+usableMemory/1000000+", "+usableMemory/1000000+", "+prepasses);
465
466 if(prepasses==0 || !prefilter){
467 filterMemory0=filterMemory1=0;
468 }else{
469 double low=Tools.min(prefilterFraction, 1-prefilterFraction);
470 double high=(autoPasses ? low : 1-low);
471 if((prepasses&1)==1){//odd passes
472 filterMemory0=(long)(usableMemory*low);
473 filterMemory1=(long)(usableMemory*high);
474 }else{//even passes
475 filterMemory0=(long)(usableMemory*high);
476 filterMemory1=(long)(usableMemory*low);
477 }
478 }
479 }
480
481 private long filterMemory(int pass){return ((pass&1)==0) ? filterMemory0 : filterMemory1;}
482
483 private void makePrefilter(){
484 prefilterArray=makePrefilter_inner(new KCountArray[1], 0, minTaxCount);
485 if(prefilterArray!=null){
486 prefilterArray.purgeFilter();
487 // filterMaxValue=Tools.min(filterMax, prefilterArray.maxValue-1);
488 }
489 }
490
491 public final KCountArray makePrefilter_inner(final KCountArray[] filter, int currentPass, int overallFilterMax){
492 // assert(false) : lastFilter+", "+prefilter+", "+filterMax()+", "+currentPass+", "+filterMemory(currentPass);
493 if(!prefilter){return null;}
494
495 if(filter[0]!=null){
496 filter[0].purgeFilter();
497 assert(filter[0].prefilter()==null);
498 }
499
500 KmerCountAbstract.CANONICAL=true;
501
502 long precells=-1;
503 int cbits=2;
504 int filterMax=3;
505
506 if(currentPass==0 && prebits>0){
507 cbits=prebits;
508 assert(Integer.bitCount(prebits)==1 && prebits<=32);
509 filterMax=Tools.min((1<<cbits)-1, overallFilterMax);
510 }else if(currentPass>0 || prepasses<2){
511 filterMax=overallFilterMax;
512 while(filterMax>=(1<<cbits)){cbits*=2;}
513 }
514
515 byte minq=0;
516 if(precells<1){
517 long prebits=(filterMemory(currentPass)-10)*8;
518
519 // System.err.println("prebits="+prebits+", currentPass="+currentPass);
520
521 precells=prebits/cbits;
522 if(precells<100000){ //Not enough memory - no point.
523 prefilter=false;
524 return null;
525 }
526 }
527 if(prehashes<1){prehashes=2;}
528
529 {
530 Timer ht=new Timer();
531
532 ArrayList<String> extra=null;
533 ReadCounter rc=new ReadCounter(k, rcomp, false, false, amino);
534 filter[0]=rc.makeKca(in1, in2, extra, cbits, precells, prehashes, minq, maxReads, 1, 1, 1, filter[0], filterMax);
535 assert(filterMax<=filter[0].maxValue || (currentPass==0)) : filterMax+", "+currentPass+", "+filter[0].maxValue;
536 outstream.println("Made prefilter: \t"+filter[0].toShortString(prehashes));
537 double uf=filter[0].usedFraction();
538 // System.err.println("cellsUsed: "+filter[0].cellsUsed(1)+" //123"); //123
539 if(uf>0.5){
540 outstream.println("Warning: This table is "+(uf>0.995 ? "totally" : uf>0.99 ? "crazy" : uf>0.95 ? "incredibly" : uf>0.9 ? "extremely" : uf>0.8 ? "very" :
541 uf>0.7 ? "rather" : uf>0.6 ? "fairly" : "somewhat")+" full. Ideal load is under 50% used." +
542 "\nFor better accuracy, run on a node with more memory; quality-trim or error-correct reads; or increase prefiltersize.");
543 }
544 ht.stop();
545
546 final double kmers=filter[0].estimateUniqueKmers(prehashes, Tools.min(overallFilterMax, filter[0].maxValue));
547 outstream.println("Estimated valid kmers: \t\t"+(long)kmers);
548
549 // outstream.println("Estimated valid kmers 1+: "+(long)filter[0].estimateUniqueKmers(prehashes, 1));
550 // outstream.println("Estimated valid kmers 2+: "+(long)filter[0].estimateUniqueKmers(prehashes, 2));
551 // outstream.println("Estimated valid kmers 3+: "+(long)filter[0].estimateUniqueKmers(prehashes, 3));
552 // outstream.println("Estimated valid kmers 4+: "+(long)filter[0].estimateUniqueKmers(prehashes, 4));
553
554 if(autoPasses && kmers<1000000){
555 prepasses=currentPass;
556 }
557
558 if(currentPass+1<prepasses){
559 return makePrefilter_inner(filter, currentPass+1, overallFilterMax);
560 }
561
562 // if(DISPLAY_PROGRESS){
563 outstream.println("Prefilter time:\t"+ht);
564 outstream.println("After prefilter:");
565 Shared.printMemory();
566 outstream.println();
567 // }
568 }
569
570 return filter[0];
571 }
572
573 /*--------------------------------------------------------------*/
574 /*---------------- Tax Methods ----------------*/
575 /*--------------------------------------------------------------*/
576
577 private void loadGiToTaxid(){
578 Timer t=new Timer();
579 outstream.println("Loading gi to taxa translation table.");
580 GiToTaxid.initialize(giTableFile);
581 t.stop();
582 if(true){
583 outstream.println("Time: \t"+t);
584 Shared.printMemory();
585 outstream.println();
586 }
587 }
588
589 /*--------------------------------------------------------------*/
590 /*---------------- Inner Classes ----------------*/
591 /*--------------------------------------------------------------*/
592
593 /** This class is static to prevent accidental writing to shared variables.
594 * It is safe to remove the static modifier. */
595 private class ProcessThread extends Thread {
596
597 //Constructor
598 ProcessThread(final ConcurrentReadInputStream cris_, final int tid_){
599 cris=cris_;
600 tid=tid_;
601
602 if(defaultParams.minEntropy>0){
603 eTracker=new EntropyTracker(entropyK, k, amino, defaultParams.minEntropy, true);
604 }else{
605 eTracker=null;
606 }
607 }
608
609 //Called by start()
610 @Override
611 public void run(){
612 //Do anything necessary prior to processing
613
614 //Process the reads
615 processInner();
616
617 //Do anything necessary after processing
618
619 //Indicate successful exit status
620 success=true;
621 }
622
623 /** Iterate through the reads */
624 void processInner(){
625 assert(!translate); //Translate first
626
627 //Grab the first ListNum of reads
628 ListNum<Read> ln=cris.nextList();
629 //Grab the actual read list from the ListNum
630 ArrayList<Read> reads=(ln!=null ? ln.list : null);
631
632 //Check to ensure pairing is as expected
633 if(reads!=null && !reads.isEmpty()){
634 Read r=reads.get(0);
635 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
636 }
637
638 //As long as there is a nonempty read list...
639 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
640 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
641
642 //Loop through each read in the list
643 for(int idx=0; idx<reads.size(); idx++){
644 final Read r1=reads.get(idx);
645 final Read r2=r1.mate;
646
647 //Validate reads in worker threads
648 if(!r1.validated()){r1.validate(true);}
649 if(r2!=null && !r2.validated()){r2.validate(true);}
650
651 //Track the initial length for statistics
652 final int initialLength1=r1.length();
653 final int initialLength2=r1.mateLength();
654
655 //Increment counters
656 readsProcessedT+=r1.pairCount();
657 basesProcessedT+=initialLength1+initialLength2;
658
659 if((initialLength1>=k || initialLength2>=k) && (!tossJunk || !r1.junk())){
660
661 int taxID=-1;
662
663 if(mode==PER_SEQUENCE){
664 taxID=(int)(r1.numericID & ((long)Integer.MAX_VALUE));
665 }else{
666 assert(mode==PER_TAXA || mode==PER_IMG) : mode;
667 TaxNode tn=null;
668 tn=taxtree.parseNodeFromHeader(r1.id, bestEffort);
669 while(tn!=null && tn.pid!=tn.id && tn.level<taxLevel){
670 TaxNode temp=taxtree.getNode(tn.pid);
671 if(temp==null || temp==tn || temp.level>=TaxTree.LIFE || temp.level>taxLevel){break;}
672 tn=temp;
673 }
674 if(tn!=null){taxID=tn.id;}
675 if(taxID<0){
676 taxID=nextUnknown.getAndIncrement();
677 }
678 }
679 assert(taxID>0) : r1.id+", "+mode;
680 // System.err.println("TID="+taxID);
681
682 //Process reads.
683 if(amino){
684 processReadAmino(r1, taxID);
685 if(r2!=null){processReadAmino(r2, taxID);}
686 }else{
687 processReadNucleotide(r1, taxID);
688 if(r2!=null){processReadNucleotide(r2, taxID);}
689 }
690 }
691 }
692
693 //Notify the input stream that the list was used
694 cris.returnList(ln);
695 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
696
697 //Fetch a new list
698 ln=cris.nextList();
699 reads=(ln!=null ? ln.list : null);
700 }
701
702 //Notify the input stream that the final list was used
703 if(ln!=null){
704 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
705 }
706 }
707
708 /**
709 * Process a read.
710 * @param r Read
711 */
712 void processReadNucleotide(final Read r, final int value){
713 assert(k<=32);
714
715 final byte[] bases=r.bases;
716
717 if(bases==null || bases.length<k){return;}
718
719 final int shift=2*k;
720 final int shift2=shift-2;
721 final long mask=(shift>63 ? -1L : ~((-1L)<<shift)); //Conditional allows K=32
722 long kmer=0;
723 long rkmer=0;
724 int len=0;
725 if(eTracker!=null){eTracker.clear();}
726
727 for(int i=0; i<bases.length; i++){
728 final byte b=bases[i];
729 long x=AminoAcid.baseToNumber[b];
730 long x2=AminoAcid.baseToComplementNumber[b];
731 kmer=((kmer<<2)|x)&mask;
732 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
733 if(eTracker!=null){eTracker.add(b);}
734
735 if(x<0){
736 len=0;
737 kmer=rkmer=0;
738 }else{
739 len++;
740 if(len>=k){
741 if(eTracker==null || eTracker.passes()){
742 final long hashcode=hash(kmer, rkmer);
743 // System.err.println("kmer="+kmer+", rkmer="+rkmer+", mask="+mask+", hashcode="+hashcode+", count="+prefilterArray.read(hashcode));
744 if(hashcode>=minHashValue){
745 int precount=prefilter ? prefilterArray.read(hashcode) : minTaxCount;
746 assert(!prefilter || precount>0) : "kmer="+kmer+", rkmer="+rkmer+", mask="+mask+", hashcode="+hashcode+", count="+precount;
747 // System.err.println("Sufficient hash for "+key+", "+value);
748 if(precount>=minTaxCount){
749 // if(prefilter){System.err.println("Passed prefilter.");}
750 addToMap(hashcode, value);
751 keysAddedT++;
752 }
753 }
754 }
755 }
756 }
757 }
758 }
759
760 /**
761 * Process a read.
762 * @param r Read
763 */
764 void processReadAmino(final Read r, final int value){
765 final int aminoShift=AminoAcid.AMINO_SHIFT;
766 assert(k*aminoShift<=64);
767
768 final byte[] bases=r.bases;
769 long kmer=0;
770 int len=0;
771 assert(r.aminoacid());
772
773 final int shift=aminoShift*k;
774 final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
775 final long min=minHashValue;
776
777 for(int i=0; i<bases.length; i++){
778 byte b=bases[i];
779 long x=AminoAcid.acidToNumberNoStops[b];
780 kmer=((kmer<<aminoShift)|x)&mask;
781
782 // System.err.println((char)b+" -> "+x);
783
784 if(x<0){
785 len=0;
786 kmer=0;
787 // System.err.println("Reset.");
788 }else{
789 len++;
790 // System.err.println("Incremented length to "+len);
791 if(len>=k){
792 final long hashcode=hash(kmer, kmer);
793 if(hashcode>=minHashValue){
794 // System.err.println("Sufficient hash for "+key+", "+value);
795 if(!prefilter || prefilterArray.read(hashcode)>=minTaxCount){
796 // if(prefilter){System.err.println("Passed prefilter.");}
797 addToMap(hashcode, value);
798 keysAddedT++;
799 }
800 }
801 }
802 }
803 }
804 // System.err.println(keysAddedT);
805 // assert(false);
806 }
807
808
809 void addToMap(long key0, int value){
810 Long key=Long.valueOf(key0);
811 // Long key=new Long(key0);
812 HashMap<Long, IntListCompressor> map=maps[(int)(key%ways)];
813 IntListCompressor lh=map.get(key);
814 if(lh==null){
815 synchronized(map){
816 lh=map.get(key);
817 if(lh==null){
818 lh=new IntListCompressor();
819 map.put(key, lh);
820 }
821 }
822 }
823 synchronized(lh){
824 lh.add(value);
825 }
826 }
827
828 /** Number of reads processed by this thread */
829 protected long readsProcessedT=0;
830 /** Number of bases processed by this thread */
831 protected long basesProcessedT=0;
832
833 protected long keysAddedT=0;
834
835 /** True only if this thread has completed successfully */
836 boolean success=false;
837
838 /** Shared input stream */
839 private final ConcurrentReadInputStream cris;
840 /** Thread ID */
841 final int tid;
842
843 private final EntropyTracker eTracker;
844 }
845
846 /*--------------------------------------------------------------*/
847 /*---------------- Fields ----------------*/
848 /*--------------------------------------------------------------*/
849
850 private final int mode;
851
852 private String giTableFile=null;
853 private String taxTreeFile=null;
854 private String accessionFile=null;
855 private String imgFile=null;
856
857 private String outName=null;
858 private String sketchName=null;
859 private int outTaxid=-1;
860
861 private int taxLevel=1;
862 private boolean prefilter=true;
863 private boolean tossJunk=true;
864 private boolean bestEffort=true;
865 private int minTaxCount=100;
866
867 private int prepasses=2;
868 private int prehashes=2;
869 private int prebits=-1;
870 private boolean autoPasses=false;
871
872 double prefilterFraction=0.2;
873
874 long filterMemory0;
875 long filterMemory1;
876
877 private HashMap<Long, IntListCompressor>[] maps;
878
879 public KCountArray prefilterArray=null;
880
881 final int ways=63;
882
883 int resultingSize=-1;
884
885 private final AtomicInteger nextUnknown=new AtomicInteger(SketchObject.minFakeID);
886
887 /*--------------------------------------------------------------*/
888
889 /** Primary input file path */
890 private String in1=null;
891 /** Secondary input file path */
892 private String in2=null;
893
894 /** Primary output file path */
895 private String outSketch=null;
896
897 /** Histogram output file path */
898 private String outHist=null;
899
900 /** Override input file extension */
901 private String extin=null;
902
903 /*--------------------------------------------------------------*/
904
905 /** Number of reads processed */
906 protected long readsProcessed=0;
907 /** Number of bases processed */
908 protected long basesProcessed=0;
909
910 /** Quit after processing this many input reads; -1 means no limit */
911 private long maxReads=-1;
912
913 /*--------------------------------------------------------------*/
914 /*---------------- Final Fields ----------------*/
915 /*--------------------------------------------------------------*/
916
917 /** Primary input file */
918 private final FileFormat ffin1;
919 /** Secondary input file */
920 private final FileFormat ffin2;
921
922 /** Primary output file */
923 private final FileFormat ffsketch;
924 /** Histogram output file */
925 private final FileFormat ffhist;
926
927 /*--------------------------------------------------------------*/
928 /*---------------- Common Fields ----------------*/
929 /*--------------------------------------------------------------*/
930
931 /** Print status messages to this output stream */
932 private PrintStream outstream=System.err;
933 /** Print verbose messages */
934 public static boolean verbose=false;
935 /** True if an error was encountered */
936 public boolean errorState=false;
937 /** Overwrite existing output files */
938 private boolean overwrite=true;
939 /** Append to existing output files */
940 private boolean append=false;
941 /** Reads are output in input order */
942 private boolean ordered=false;
943
944 }