Debian Codegraph @

current/sketch/BlacklistMaker2.java

raw symbols SCIP
1 package sketch;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Collections;
6 import java.util.HashMap;
7 import java.util.Map.Entry;
8 import java.util.concurrent.atomic.AtomicInteger;
9
10 import bloom.KmerCountAbstract;
11 import bloom.ReadCounter;
12 import fileIO.ByteFile;
13 import fileIO.ByteStreamWriter;
14 import fileIO.FileFormat;
15 import fileIO.ReadWrite;
16 import kmer.HashArrayHybridFast;
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.FastaReadInputStream;
24 import structures.IntList;
25 import structures.IntListCompressor;
26 import structures.LongList;
27 import tax.TaxNode;
28 import tax.TaxTree;
29
30 /**
31 * Makes blacklists from existing sketches.
32 *
33 * @author Brian Bushnell
34 * @date November 12, 2019
35 *
36 */
37 public class BlacklistMaker2 extends SketchObject {
38
39 /*--------------------------------------------------------------*/
40 /*---------------- Initialization ----------------*/
41 /*--------------------------------------------------------------*/
42
43 /**
44 * Code entrance from the command line.
45 * @param args Command line arguments
46 */
47 public static void main(String[] args){
48 //Start a timer immediately upon code entrance.
49 Timer t=new Timer();
50
51 ReadCounter.maxShortKmerLength=32;
52
53 //Create an instance of this class
54 BlacklistMaker2 x=new BlacklistMaker2(args);
55
56 //Run the object
57 x.process(t);
58
59 ReadCounter.maxShortKmerLength=31;
60
61 //Close the print stream if it was redirected
62 Shared.closeStream(x.outstream);
63 }
64
65 /**
66 * Constructor.
67 * @param args Command line arguments
68 */
69 @SuppressWarnings("unchecked")
70 public BlacklistMaker2(String[] args){
71
72 {//Preparse block for help, config files, and outstream
73 PreParser pp=new PreParser(args, getClass(), false);
74 args=pp.args;
75 outstream=pp.outstream;
76 }
77
78 //Set shared static variables
79 if(Shared.threads()>=32){Shared.capThreads(Shared.threads()/2);}//Deals with hyperthreading, which causes excessive memory usage
80 Shared.capBuffers(Tools.max(4, Shared.threads()+1));
81 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
82 ReadWrite.setZipThreads(Shared.threads());
83 KmerCountAbstract.SKETCH_MODE=true;
84 KmerCountAbstract.STORE_HASHED=true;
85 KmerCountAbstract.KEEP_DUPLICATE_KMERS=true;
86 setKeyFraction(1); //Prevents an assertion error by ignoring min hash value
87
88 //Create a parser object
89 Parser parser=new Parser();
90
91 int mode_=PER_TAXA;
92
93 //Parse each argument
94 for(int i=0; i<args.length; i++){
95 String arg=args[i];
96
97 //Break arguments into their constituent parts, in the form of "a=b"
98 String[] split=arg.split("=");
99 String a=split[0].toLowerCase();
100 String b=split.length>1 ? split[1] : null;
101
102 if(a.equals("verbose")){
103 verbose=Parse.parseBoolean(b);
104 }else if(a.equals("parse_flag_goes_here")){
105 long fake_variable=Parse.parseKMG(b);
106 //Set a variable here
107 }else if(parseMode(arg, a, b)>-1){
108 mode_=parseMode(arg, a, b);
109 }else if(a.equals("tossjunk")){
110 tossJunk=Parse.parseBoolean(b);
111 }
112
113 else if(a.equals("taxtree") || a.equals("tree")){
114 taxTreeFile=b;
115 }else if(a.equals("imgfile") || a.equals("imgdump")){
116 imgFile=b;
117 }
118
119
120 else if(a.equals("mincount") || a.equals("mintaxcount")){
121 minTaxCount=Parse.parseIntKMG(b);
122 }else if(a.equals("maxkeys") || a.equals("keys") || a.equals("length") || a.equals("size")){
123 maxKeys=Parse.parseIntKMG(b);
124 }else if(a.equals("name")){
125 outName=b;
126 }else if(a.equalsIgnoreCase("name0") || a.equalsIgnoreCase("nm0")){
127 sketchName=b;
128 }else if(a.equals("hist")){
129 outHist=b;
130 }
131
132 else if(a.equals("taxlevel") || a.equals("tl") || a.equals("level") || a.equals("lv")){
133 if(b==null){taxLevel=-1;}
134 else if(Tools.isDigit(b.charAt(0))){
135 taxLevel=Integer.parseInt(b);
136 }else{
137 taxLevel=TaxTree.parseLevel(b);
138 }
139 }
140
141
142
143 else if(searcher.parse(arg, a, b, false)){
144 // System.err.println("*"+arg);
145 parser.parse(arg, a, b); //Catches shared flags like "threads"
146 }else if(parseSketchFlags(arg, a, b)){
147 //do nothing
148 }else if(defaultParams.parse(arg, a, b)){
149 //do nothing
150 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
151 //do nothing
152 }else if(searcher.parse(arg, a, b, true)){
153 // System.err.println("**"+arg);
154 //do nothing
155 }else{
156 outstream.println("Unknown parameter "+args[i]);
157 assert(false) : "Unknown parameter "+args[i];
158 }
159 }
160
161 if("auto".equalsIgnoreCase(imgFile)){imgFile=TaxTree.defaultImgFile();}
162 if("auto".equalsIgnoreCase(taxTreeFile)){taxTreeFile=TaxTree.defaultTreeFile();}
163
164 mode=mode_;
165 assert((mode!=PER_TAXA && mode!=PER_IMG) || taxTreeFile!=null) : "Please specify a TaxTree.";
166 assert(mode!=PER_IMG || imgFile!=null);
167 assert(mode==PER_TAXA || mode==PER_SEQUENCE || mode==PER_IMG);
168
169 {//Process parser fields
170 Parser.processQuality();
171
172 overwrite=parser.overwrite;
173 append=parser.append;
174
175 outSketch=parser.out1;
176 }
177
178 postParse();
179
180 assert(FastaReadInputStream.settingsOK());
181
182 //Adjust the number of threads for input file reading
183 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
184 ByteFile.FORCE_MODE_BF2=true;
185 }
186
187 //Ensure output files can be written
188 if(!Tools.testOutputFiles(overwrite, append, false, outSketch)){
189 outstream.println((outSketch==null)+", "+outSketch);
190 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+outSketch+"\n");
191 }
192
193 //Ensure that no file was specified multiple times
194 if(!Tools.testForDuplicateFiles(true, outSketch, outHist)){
195 throw new RuntimeException("\nSome file names were specified multiple times.\n");
196 }
197
198 if(sketchName==null && outSketch!=null){
199 sketchName=outSketch;
200 sketchName=ReadWrite.stripToCore(sketchName);
201 }
202
203 //Create output FileFormat objects
204 ffsketch=FileFormat.testOutput(outSketch, FileFormat.SKETCH, null, true, overwrite, append, false);
205 ffhist=FileFormat.testOutput(outHist, FileFormat.TXT, null, true, overwrite, append, false);
206
207 if(taxTreeFile!=null){setTaxtree(taxTreeFile, outstream);}
208
209 if(imgFile!=null){
210 TaxTree.loadIMG(imgFile, false, outstream);
211 }
212
213 maps=new HashMap[ways];
214 for(int i=0; i<ways; i++){
215 maps[i]=new HashMap<Long, IntListCompressor>();
216 }
217 }
218
219 /*--------------------------------------------------------------*/
220 /*---------------- Outer Methods ----------------*/
221 /*--------------------------------------------------------------*/
222
223 /** Create read streams and process all data */
224 void process(Timer t){
225
226 makeIndex=true; //(searcher.refFileCount()>0); //Index is required in whitelist mode.
227 searcher.loadReferences(mode, defaultParams);
228 sketchesProcessed=searcher.refSketchCount();
229
230 //Reset counters
231 keysProcessed=0;
232
233 //Process the reads in separate threads
234 spawnThreads();
235
236 if(verbose){outstream.println("Finished; closing streams.");}
237
238 //Report timing and results
239 t.stop();
240 outstream.println("Blacklist size: \t"+resultingSize+"\n");
241 outstream.println(Tools.timeSketchesKeysProcessed(t, sketchesProcessed, keysProcessed, 8));
242
243 //Throw an exception of there was an error in a thread
244 if(errorState){
245 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
246 }
247 }
248
249 /** Spawn process threads */
250 private void spawnThreads(){
251
252 //Do anything necessary prior to processing
253
254 //Determine how many threads may be used
255 final int threads=Shared.threads();
256
257 //Fill a list with ProcessThreads
258 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
259 for(int i=0; i<threads; i++){
260 alpt.add(new ProcessThread(i, threads));
261 }
262
263 //Start the threads
264 for(ProcessThread pt : alpt){
265 pt.start();
266 }
267
268 //Wait for completion of all threads
269 boolean success=true;
270 for(ProcessThread pt : alpt){
271
272 //Wait until this thread has terminated
273 while(pt.getState()!=Thread.State.TERMINATED){
274 try {
275 //Attempt a join operation
276 pt.join();
277 } catch (InterruptedException e) {
278 //Potentially handle this, if it is expected to occur
279 e.printStackTrace();
280 }
281 }
282
283 //Accumulate per-thread statistics
284 keysProcessed+=pt.keysProcessedT;
285 success&=pt.success;
286 }
287
288 shrinkListsAndWriteHist();
289 writeSketch(true);
290
291 //Track whether any threads failed
292 if(!success){errorState=true;}
293
294 //Do anything necessary after processing
295
296 }
297
298 /*--------------------------------------------------------------*/
299 /*---------------- Inner Methods ----------------*/
300 /*--------------------------------------------------------------*/
301
302 private void writeSketch(boolean destroy){
303 Sketch sk=toSketch(destroy);
304 if(ffsketch!=null){errorState|=SketchTool.write(sk, ffsketch);}
305 }
306
307 private void shrinkListsAndWriteHist(){
308 int max=1000000;
309 long[] counts=new long[max+1];
310 for(int i=0; i<ways; i++){
311 for(Entry<Long, IntListCompressor> entry : maps[i].entrySet()){
312 IntListCompressor value=entry.getValue();
313 value.sortAndShrink();
314 IntList list=value.list;
315 int index=Tools.min(max, list.size);
316 counts[index]++;
317 }
318 }
319 if(ffhist!=null){
320 ByteStreamWriter bsw=new ByteStreamWriter(ffhist);
321 bsw.start();
322 bsw.print("#count\tkmers\n".getBytes());
323 for(int i=0; i<counts.length; i++){
324 long count=counts[i];
325 if(count>0){
326 bsw.print(i);
327 bsw.print('\t');
328 bsw.print(count);
329 bsw.print('\n');
330 }
331 }
332 errorState|=bsw.poisonAndWait();
333 }
334 }
335
336 private Sketch toSketch(boolean destroy){
337 long[] array=toArray(destroy);
338 hashArrayToSketchArray(array);
339 ArrayList<String> meta=new ArrayList<String>();
340 meta.add("minTaxCount:"+minTaxCount);
341 meta.add("taxLevel:"+taxLevel);
342 Sketch sk=new Sketch(array, null, null, null, null, outTaxid, -1, -1, -1, -1, -1, outName, sketchName, ffsketch.simpleName(), meta);
343 return sk;
344 }
345
346 private long[] toArray(boolean destroy){
347 ArrayList<KeyPair> pairs=new ArrayList<KeyPair>();
348 long entries=0;
349
350 for(int i=0; i<ways; i++){
351 for(Entry<Long, IntListCompressor> entry : maps[i].entrySet()){
352 Long key=entry.getKey();
353 IntList value=entry.getValue().list;
354 entries++;
355 if(value.size()>=minTaxCount){
356 KeyPair p=new KeyPair(key.longValue(), value.size());
357 pairs.add(p);
358 }
359 }
360 if(destroy){maps[i]=null;}
361 }
362 System.err.println("Pruned "+entries+" high-count keys down to "+pairs.size()+" after tax level promotion.");
363 if(pairs.isEmpty()){
364 System.err.println("*** Warning - no keys retained! ***");
365 assert(false);
366 }
367 LongList list=new LongList(Tools.mid(1, pairs.size(), maxKeys));
368 Collections.sort(pairs);
369 for(KeyPair p : pairs){
370 list.add(p.key);
371 if(list.size()>=maxKeys){break;}
372 }
373 list.sort();
374 resultingSize=list.size();
375 return list.toArray();
376 }
377
378 /*--------------------------------------------------------------*/
379 /*---------------- Inner Classes ----------------*/
380 /*--------------------------------------------------------------*/
381
382 /** This class is static to prevent accidental writing to shared variables.
383 * It is safe to remove the static modifier. */
384 private class ProcessThread extends Thread {
385
386 //Constructor
387 ProcessThread(final int tid_, final int threads_){
388 threadID=tid_;
389 threads=threads_;
390 }
391
392 //Called by start()
393 @Override
394 public void run(){
395 //Do anything necessary prior to processing
396
397 //Process the reads
398 processInner();
399
400 //Do anything necessary after processing
401
402 //Indicate successful exit status
403 success=true;
404 }
405
406 /** Iterate through the reads */
407 void processInner(){
408 SketchIndex index=searcher.index;
409 for(int i=threadID; i<index.tableArray.length; i+=threads) {
410 HashArrayHybridFast table=(HashArrayHybridFast)index.tableArray[i];
411 long[] array=table.array();
412 for(long key : array){
413 if(key>=0){
414 processKey(key, table);
415 }
416 }
417 }
418 }
419
420 void processKey(final long key0, HashArrayHybridFast table){
421 keysProcessedT++;
422 final int[] sketchIds=table.getValues(key0, singleton); //searcher.index.getSketchIdsMap(key, singleton);
423 if(sketchIds==null){//Keys should be 63 bits so this should not happen
424 assert(key0<0) : Long.toHexString(key0);
425 return;
426 }
427 if(sketchIds.length<minTaxCount){return;}
428
429 long key=Long.MAX_VALUE-key0;
430 // System.err.println(key+", "+minHashValue);
431 // System.err.print(key<minHashValue ? "L" : "G");
432 for(int sid : sketchIds){
433 if(sid<0){break;}
434 final int trueID=sid-1;//Minimum id is 1, indicating sketch 0.
435 if(mode==PER_SEQUENCE){
436 // System.err.print("A");
437 addToMap(key, trueID);
438 }else{
439 // System.err.print("B");
440 Sketch sk=searcher.refSketches.get(trueID);
441 int taxID=sk.taxID;
442 taxID=taxtree.promote(taxID, taxLevel);
443
444 boolean ok=true;
445 if(tossJunk){
446 if(taxID<=1){ok=false;}
447 else{
448 TaxNode tn=taxtree.getNode(taxID);
449 if(tn==null || !tn.isRanked() || tn.pid==TaxTree.LIFE_ID){ok=false;}
450 }
451 }
452 if(ok){
453 if(taxID<0){
454 taxID=nextUnknown.getAndIncrement();
455 }
456 // System.err.print("C");
457 addToMap(key, taxID);
458 }
459 }
460 }
461 }
462
463 void addToMap(long key0, int value){
464 keysAddedT++;
465 Long key=Long.valueOf(key0);
466 // Long key=new Long(key0);
467 HashMap<Long, IntListCompressor> map=maps[(int)(key%ways)];
468 IntListCompressor lh=map.get(key);
469 if(lh==null){
470 synchronized(map){
471 lh=map.get(key);
472 if(lh==null){
473 lh=new IntListCompressor();
474 map.put(key, lh);
475 }
476 }
477 }
478 synchronized(lh){
479 lh.add(value);
480 }
481 }
482
483 /** Number of bases processed by this thread */
484 protected long keysProcessedT=0;
485
486 protected long keysAddedT=0;
487
488 /** True only if this thread has completed successfully */
489 boolean success=false;
490
491 /** Thread ID */
492 final int threadID;
493 final int threads;
494
495 private final int[] singleton=new int[1];
496 }
497
498 /*--------------------------------------------------------------*/
499
500 private static class KeyPair implements Comparable<KeyPair> {
501
502 KeyPair(long key_, int count_){
503 key=key_;
504 count=count_;
505 }
506
507 @Override
508 public int compareTo(KeyPair o) {
509 if(count!=o.count){return o.count-count;}
510 return key>o.key ? -1 : key<o.key ? 1 : 0;
511 }
512
513 long key;
514 int count;
515
516 }
517
518 /*--------------------------------------------------------------*/
519 /*---------------- Fields ----------------*/
520 /*--------------------------------------------------------------*/
521
522 public final SketchSearcher searcher=new SketchSearcher();
523
524 private final int mode;
525
526 private String taxTreeFile=null;
527 private String imgFile=null;
528
529 private String outName="blacklist";
530 private String sketchName=null;
531 private int outTaxid=-1;
532
533 private int taxLevel=1;
534 private boolean tossJunk=true;
535 private int minTaxCount=20;
536 private int maxKeys=300000;
537
538 private HashMap<Long, IntListCompressor>[] maps;
539
540 final int ways=63;
541
542 int resultingSize=-1;
543
544 private final AtomicInteger nextUnknown=new AtomicInteger(SketchObject.minFakeID);
545
546 /*--------------------------------------------------------------*/
547
548 /** Primary output file path */
549 private String outSketch=null;
550
551 /** Histogram output file path */
552 private String outHist=null;
553
554 /*--------------------------------------------------------------*/
555
556 /** Number of reads processed */
557 protected long sketchesProcessed=0;
558 /** Number of bases processed */
559 protected long keysProcessed=0;
560
561 /*--------------------------------------------------------------*/
562 /*---------------- Final Fields ----------------*/
563 /*--------------------------------------------------------------*/
564
565 /** Primary output file */
566 private final FileFormat ffsketch;
567 /** Histogram output file */
568 private final FileFormat ffhist;
569
570 /*--------------------------------------------------------------*/
571 /*---------------- Common Fields ----------------*/
572 /*--------------------------------------------------------------*/
573
574 /** Print status messages to this output stream */
575 private PrintStream outstream=System.err;
576 /** Print verbose messages */
577 public static boolean verbose=false;
578 /** True if an error was encountered */
579 public boolean errorState=false;
580 /** Overwrite existing output files */
581 private boolean overwrite=true;
582 /** Append to existing output files */
583 private boolean append=false;
584
585 }