Debian Codegraph @

current/jgi/KmerCountMulti.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.Arrays;
7
8 import cardinality.MultiLogLog;
9 import fileIO.ByteFile;
10 import fileIO.FileFormat;
11 import fileIO.ReadWrite;
12 import fileIO.TextStreamWriter;
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.FASTQ;
21 import stream.FastaReadInputStream;
22 import stream.Read;
23 import structures.ListNum;
24 import tracker.ReadStats;
25
26 /**
27 * Counts unique kmers in a file.
28 * Tracks multiple kmer lengths independently.
29 *
30 * @author Brian Bushnell
31 * @date December 30, 2016
32 *
33 */
34 public class KmerCountMulti {
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 KmerCountMulti x=new KmerCountMulti(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 KmerCountMulti(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 //Set shared static variables
71 ReadWrite.USE_UNPIGZ=true;
72
73 //Create a parser object
74 Parser parser=new Parser();
75 parser.out1="stdout.txt";
76
77 //Parse each argument
78 for(int i=0; i<args.length; i++){
79 String arg=args[i];
80
81 //Break arguments into their constituent parts, in the form of "a=b"
82 String[] split=arg.split("=");
83 String a=split[0].toLowerCase();
84 String b=split.length>1 ? split[1] : null;
85
86 if(a.equals("verbose")){
87 verbose=Parse.parseBoolean(b);
88 }else if(a.equals("k")){
89 assert(b!=null) : "Bad parameter: "+arg;
90 String[] split2=b.split(",");
91 for(String k : split2){
92 parser.loglogKlist.add(Integer.parseInt(k));
93 }
94 }else if(a.equals("ways") || a.equals("hashes")){
95 ways=Integer.parseInt(b);
96 }else if(a.equals("showstdev") || a.equals("showstddev") || a.equals("stdev") || a.equals("stddev")){
97 showStdev=Parse.parseBoolean(b);
98 }else if(a.equals("wavg")){
99 useWavg=Parse.parseBoolean(b);
100 }else if(a.equals("seed")){
101 parser.parse(null, "loglogseed", b);
102 }else if(a.equals("buckets")){
103 parser.parse(null, "loglogbuckets", b);
104 }else if(a.equals("minprob")){
105 parser.parse(null, "loglogminprob", b);
106 }else if(a.equals("sweep")){
107 assert(b!=null) : "Bad parameter: "+arg;
108 String[] split2=b.split(",");
109 int mink=Integer.parseInt(split2[0]);
110 int maxk=Integer.parseInt(split2[1]);
111 int incr=Integer.parseInt(split2[2]);
112 for(int k=mink; k<=maxk; k+=incr){
113 parser.loglogKlist.add(k);
114 }
115 }else if(a.equals("parse_flag_goes_here")){
116 long fake_variable=Parse.parseKMG(b);
117 //Set a variable here
118 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
119 //do nothing
120 }else{
121 outstream.println("Unknown parameter "+args[i]);
122 assert(false) : "Unknown parameter "+args[i];
123 }
124 }
125
126 {//Process parser fields
127 Parser.processQuality();
128
129 maxReads=parser.maxReads;
130
131 overwrite=ReadStats.overwrite=parser.overwrite;
132 append=ReadStats.append=parser.append;
133
134 in1=parser.in1;
135 in2=parser.in2;
136 qfin1=parser.qfin1;
137 qfin2=parser.qfin2;
138
139 out=parser.out1;
140
141 extin=parser.extin;
142
143 overwrite=parser.overwrite;
144 append=parser.append;
145 }
146
147 mlogArray=new MultiLogLog[ways];
148 for(int i=0; i<ways; i++){
149 mlogArray[i]=new MultiLogLog(parser);
150 if(parser.loglogseed>=0){
151 parser.loglogseed++;
152 }
153 }
154
155 //Do input file # replacement
156 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
157 in2=in1.replace("#", "2");
158 in1=in1.replace("#", "1");
159 }
160
161 //Adjust interleaved detection based on the number of input files
162 if(in2!=null){
163 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
164 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
165 }
166
167 assert(FastaReadInputStream.settingsOK());
168
169 //Ensure there is an input file
170 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
171
172 //Adjust the number of threads for input file reading
173 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
174 ByteFile.FORCE_MODE_BF2=true;
175 }
176
177 //Ensure output files can be written
178 if(!Tools.testOutputFiles(overwrite, append, false, out)){
179 outstream.println((out==null)+", "+out);
180 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out+"\n");
181 }
182
183 //Ensure input files can be read
184 if(!Tools.testInputFiles(false, true, in1, in2)){
185 throw new RuntimeException("\nCan't read some input files.\n");
186 }
187
188 //Ensure that no file was specified multiple times
189 if(!Tools.testForDuplicateFiles(true, in1, in2, out)){
190 throw new RuntimeException("\nSome file names were specified multiple times.\n");
191 }
192
193 //Create output FileFormat objects
194 ffout=FileFormat.testOutput(out, FileFormat.TEXT, null, true, overwrite, append, false);
195
196 //Create input FileFormat objects
197 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
198 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
199 }
200
201 /*--------------------------------------------------------------*/
202 /*---------------- Outer Methods ----------------*/
203 /*--------------------------------------------------------------*/
204
205 /** Create read streams and process all data */
206 void process(Timer t){
207
208 //Turn off read validation in the input threads to increase speed
209 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
210 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
211
212 //Create a read input stream
213 final ConcurrentReadInputStream cris;
214 {
215 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
216 cris.start(); //Start the stream
217 if(verbose){outstream.println("Started cris");}
218 }
219 boolean paired=cris.paired();
220 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
221
222 //Reset counters
223 readsProcessed=0;
224 basesProcessed=0;
225
226 //Process the reads in separate threads
227 spawnThreads(cris);
228
229 if(verbose){outstream.println("Finished; closing streams.");}
230
231 //Close the read streams
232 errorState|=ReadWrite.closeStreams(cris);
233
234 //Reset read validation
235 Read.VALIDATE_IN_CONSTRUCTOR=vic;
236
237 //Report timing and results
238 t.stop();
239 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
240
241 //Throw an exception of there was an error in a thread
242 if(errorState){
243 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
244 }
245 }
246
247 /** Spawn process threads */
248 private void spawnThreads(final ConcurrentReadInputStream cris){
249
250 //Do anything necessary prior to processing
251
252 //Determine how many threads may be used
253 final int threads=Shared.threads();
254
255 //Fill a list with ProcessThreads
256 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
257 for(int i=0; i<threads; i++){
258 alpt.add(new ProcessThread(cris, i));
259 }
260
261 //Start the threads
262 for(ProcessThread pt : alpt){
263 pt.start();
264 }
265
266 //Wait for completion of all threads
267 boolean success=true;
268 for(ProcessThread pt : alpt){
269
270 //Wait until this thread has terminated
271 while(pt.getState()!=Thread.State.TERMINATED){
272 try {
273 //Attempt a join operation
274 pt.join();
275 } catch (InterruptedException e) {
276 //Potentially handle this, if it is expected to occur
277 e.printStackTrace();
278 }
279 }
280
281 //Accumulate per-thread statistics
282 readsProcessed+=pt.readsProcessedT;
283 basesProcessed+=pt.basesProcessedT;
284 success&=pt.success;
285 }
286
287 //Track whether any threads failed
288 if(!success){errorState=true;}
289
290 //Do anything necessary after processing
291 if(ffout!=null){
292 writeOutput();
293 }
294 }
295
296 /*--------------------------------------------------------------*/
297 /*---------------- Inner Methods ----------------*/
298 /*--------------------------------------------------------------*/
299
300 private void writeOutput0(){
301 TextStreamWriter tsw=new TextStreamWriter(ffout);
302 tsw.start();
303 if(ffout.stdio()){tsw.println();}
304 tsw.print("#K\tCount\n");
305 int numK=mlogArray[0].counters.length;
306 for(int knum=0; knum<numK; knum++){
307 long sum=0;
308 for(MultiLogLog mlog : mlogArray){
309 sum+=mlog.counters[knum].cardinality();
310 }
311 tsw.print(mlogArray[0].counters[knum].k+"\t"+((sum+ways-1)/ways)+"\n");
312 }
313 if(ffout.stdio()){tsw.println();}
314 errorState|=tsw.poisonAndWait();
315 }
316
317 private void writeOutput(){
318 TextStreamWriter tsw=new TextStreamWriter(ffout);
319 tsw.start();
320 if(ffout.stdio()){tsw.println();}
321 tsw.print("#K\tCount "+(ways>1 && showStdev ? "\tStdDev" : "")+"\n");
322
323 int numK=mlogArray[0].counters.length;
324 long[][] counts=new long[numK][ways];
325
326 for(int way=0; way<ways; way++){
327 MultiLogLog mlog=mlogArray[way];
328 for(int knum=0; knum<numK; knum++){
329 counts[knum][way]=mlog.counters[knum].cardinality();
330 }
331 }
332
333 for(int knum=0; knum<numK; knum++){
334 long[] array=counts[knum];
335 Arrays.sort(array);
336 double avg=shared.Vector.sum(array)/(double)ways;
337 double wavg=Tools.weightedAverage(array);
338 double stdev=Tools.standardDeviation(array)*100/avg;
339 int k=mlogArray[0].counters[knum].k;
340 String avgs=""+(long)Math.round(useWavg ? wavg : avg);
341 while(avgs.length()<11){avgs=avgs+" ";}
342 if(ways>1 && showStdev){
343 tsw.print(Tools.format("%d\t%s\t%.2f%%\n",k,avgs,stdev));
344 }else{
345 tsw.print(Tools.format("%d\t%s\n",k,avgs));
346 }
347
348 }
349 if(ffout.stdio()){tsw.println();}
350 errorState|=tsw.poisonAndWait();
351 }
352
353 /*--------------------------------------------------------------*/
354 /*---------------- Inner Classes ----------------*/
355 /*--------------------------------------------------------------*/
356
357 /** This class is static to prevent accidental writing to shared variables.
358 * It is safe to remove the static modifier. */
359 private class ProcessThread extends Thread {
360
361 //Constructor
362 ProcessThread(final ConcurrentReadInputStream cris_, final int tid_){
363 cris=cris_;
364 tid=tid_;
365 }
366
367 //Called by start()
368 @Override
369 public void run(){
370 //Do anything necessary prior to processing
371
372 //Process the reads
373 processInner();
374
375 //Do anything necessary after processing
376
377 //Indicate successful exit status
378 success=true;
379 }
380
381 /** Iterate through the reads */
382 void processInner(){
383
384 //Grab the first ListNum of reads
385 ListNum<Read> ln=cris.nextList();
386 //Grab the actual read list from the ListNum
387 ArrayList<Read> reads=(ln!=null ? ln.list : null);
388
389 //As long as there is a nonempty read list...
390 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
391 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
392
393 //Loop through each read in the list
394 for(int idx=0; idx<reads.size(); idx++){
395 final Read r1=reads.get(idx);
396 final Read r2=r1.mate;
397
398 //Validate reads in worker threads
399 if(!r1.validated()){r1.validate(true);}
400 if(r2!=null && !r2.validated()){r2.validate(true);}
401
402 //Track the initial length for statistics
403 final int initialLength1=r1.length();
404 final int initialLength2=r1.mateLength();
405
406 //Increment counters
407 readsProcessedT+=r1.pairCount();
408 basesProcessedT+=initialLength1+initialLength2;
409
410 {
411 //Reads are processed in this block.
412 processReadPair(r1, r2);
413 }
414 }
415
416 //Notify the input stream that the list was used
417 cris.returnList(ln);
418 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
419
420 //Fetch a new list
421 ln=cris.nextList();
422 reads=(ln!=null ? ln.list : null);
423 }
424
425 //Notify the input stream that the final list was used
426 if(ln!=null){
427 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
428 }
429 }
430
431 /**
432 * Process a read or a read pair.
433 * @param r1 Read 1
434 * @param r2 Read 2 (may be null)
435 */
436 void processReadPair(final Read r1, final Read r2){
437 for(MultiLogLog mlog : mlogArray){
438 mlog.hash(r1);
439 }
440 }
441
442 /** Number of reads processed by this thread */
443 protected long readsProcessedT=0;
444 /** Number of bases processed by this thread */
445 protected long basesProcessedT=0;
446
447 /** True only if this thread has completed successfully */
448 boolean success=false;
449
450 /** Shared input stream */
451 private final ConcurrentReadInputStream cris;
452 /** Thread ID */
453 final int tid;
454 }
455
456 /*--------------------------------------------------------------*/
457 /*---------------- Fields ----------------*/
458 /*--------------------------------------------------------------*/
459
460 /** Primary input file path */
461 private String in1=null;
462 /** Secondary input file path */
463 private String in2=null;
464
465 private String qfin1=null;
466 private String qfin2=null;
467
468 /** Primary output file path */
469 private String out=null;
470
471 /** Override input file extension */
472 private String extin=null;
473
474 /*--------------------------------------------------------------*/
475
476 /** Number of reads processed */
477 protected long readsProcessed=0;
478 /** Number of bases processed */
479 protected long basesProcessed=0;
480
481 /** Quit after processing this many input reads; -1 means no limit */
482 private long maxReads=-1;
483
484 /** Number of hash functions to use */
485 int ways=1;
486
487 boolean showStdev=false;
488 boolean useWavg=false;
489
490 /*--------------------------------------------------------------*/
491 /*---------------- Final Fields ----------------*/
492 /*--------------------------------------------------------------*/
493
494 /** Primary input file */
495 private final FileFormat ffin1;
496 /** Secondary input file */
497 private final FileFormat ffin2;
498
499 /** Primary output file */
500 private final FileFormat ffout;
501
502 private final MultiLogLog[] mlogArray;
503
504 /*--------------------------------------------------------------*/
505 /*---------------- Common Fields ----------------*/
506 /*--------------------------------------------------------------*/
507
508 /** Print status messages to this output stream */
509 private PrintStream outstream=System.err;
510 /** Print verbose messages */
511 public static boolean verbose=false;
512 /** True if an error was encountered */
513 public boolean errorState=false;
514 /** Overwrite existing output files */
515 private boolean overwrite=true;
516 /** Append to existing output files */
517 private boolean append=false;
518
519 }