Debian Codegraph @

current/prok/MergeRibo_Fast.java

raw symbols SCIP
1 package prok;
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.locks.ReadWriteLock;
9 import java.util.concurrent.locks.ReentrantReadWriteLock;
10
11 import aligner.SingleStateAlignerFlat2;
12 import fileIO.ByteFile;
13 import fileIO.FileFormat;
14 import fileIO.ReadWrite;
15 import shared.Parse;
16 import shared.Parser;
17 import shared.PreParser;
18 import shared.Shared;
19 import shared.Timer;
20 import shared.Tools;
21 import stream.ConcurrentReadInputStream;
22 import stream.ConcurrentReadOutputStream;
23 import stream.FASTQ;
24 import stream.FastaReadInputStream;
25 import stream.Read;
26 import structures.ListNum;
27 import tax.GiToTaxid;
28 import template.Accumulator;
29 import template.ThreadWaiter;
30 import tracker.ReadStats;
31
32 /**
33 * Picks one ribosomal (16S) sequence per taxID.
34 * This is the old version that does not make a consensus per taxID.
35 * Instead it just picks whatever aligns best to the global consensus.
36 *
37 * @author Brian Bushnell
38 * @date November 19, 2015
39 *
40 */
41 public class MergeRibo_Fast implements Accumulator<MergeRibo_Fast.ProcessThread> {
42
43 /*--------------------------------------------------------------*/
44 /*---------------- Initialization ----------------*/
45 /*--------------------------------------------------------------*/
46
47 /**
48 * Code entrance from the command line.
49 * @param args Command line arguments
50 */
51 public static void main(String[] args){
52 //Start a timer immediately upon code entrance.
53 Timer t=new Timer();
54
55 //Create an instance of this class
56 MergeRibo_Fast x=new MergeRibo_Fast(args);
57
58 //Run the object
59 x.process(t);
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 public MergeRibo_Fast(String[] args){
70
71 {//Preparse block for help, config files, and outstream
72 PreParser pp=new PreParser(args, getClass(), false);
73 args=pp.args;
74 outstream=pp.outstream;
75 }
76
77 //Set shared static variables prior to parsing
78 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
79 ReadWrite.setZipThreads(Shared.threads());
80
81 {//Parse the arguments
82 final Parser parser=parse(args);
83 Parser.processQuality();
84
85 maxReads=parser.maxReads;
86 overwrite=ReadStats.overwrite=parser.overwrite;
87 append=ReadStats.append=parser.append;
88
89 extin=parser.extin;
90
91 out1=parser.out1;
92 extout=parser.extout;
93 }
94
95 validateParams();
96 adjustInterleaving(); //Make sure interleaving agrees with number of input and output files
97 checkFileExistence(); //Ensure files can be read and written
98 checkStatics(); //Adjust file-related static fields as needed for this program
99
100 //Create output FileFormat objects
101 ffout1=FileFormat.testOutput(out1, FileFormat.FASTA, extout, true, overwrite, append, ordered);
102
103 //Create input FileFormat objects
104 ffin=new ArrayList<FileFormat>(in.size());
105 ffalt=FileFormat.testInput(alt, FileFormat.FASTA, extin, true, true);
106 for(String s : in){
107 FileFormat ff=FileFormat.testInput(s, FileFormat.FASTA, extin, true, true);
108 ffin.add(ff);
109 }
110 }
111
112 /*--------------------------------------------------------------*/
113 /*---------------- Initialization Helpers ----------------*/
114 /*--------------------------------------------------------------*/
115
116 /** Parse arguments from the command line */
117 private Parser parse(String[] args){
118
119 //Create a parser object
120 Parser parser=new Parser();
121
122 //Set any necessary Parser defaults here
123 //parser.foo=bar;
124
125 //Parse each argument
126 for(int i=0; i<args.length; i++){
127 String arg=args[i];
128
129 //Break arguments into their constituent parts, in the form of "a=b"
130 String[] split=arg.split("=");
131 String a=split[0].toLowerCase();
132 String b=split.length>1 ? split[1] : null;
133 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
134
135 if(a.equals("verbose")){
136 verbose=Parse.parseBoolean(b);
137 }else if(a.equals("ordered")){
138 ordered=Parse.parseBoolean(b);
139 }else if(a.equals("in")){
140 Tools.addFiles(b, in);
141 }else if(a.equals("alt")){
142 alt=b;
143 }else if(a.equals("parse_flag_goes_here")){
144 long fake_variable=Parse.parseKMG(b);
145 //Set a variable here
146 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
147 //do nothing
148 }else if(b==null && new File(arg).exists()){
149 in.add(arg);
150 }else{
151 outstream.println("Unknown parameter "+args[i]);
152 assert(false) : "Unknown parameter "+args[i];
153 }
154 }
155 assert(!in.isEmpty()) : "No input file.";
156 return parser;
157 }
158
159 /** Ensure files can be read and written */
160 private void checkFileExistence(){
161 //Ensure output files can be written
162 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
163 outstream.println((out1==null)+", "+out1);
164 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+"\n");
165 }
166
167 //Ensure input files can be read
168 if(!Tools.testInputFiles(false, true, in)){
169 throw new RuntimeException("\nCan't read some input files.\n");
170 }
171
172 // //Ensure that no file was specified multiple times
173 // if(!Tools.testForDuplicateFiles(true, out1, in.toArray(new String[0]))){
174 // throw new RuntimeException("\nSome file names were specified multiple times.\n");
175 // }
176 }
177
178 /** Make sure interleaving agrees with number of input and output files */
179 private void adjustInterleaving(){
180 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
181 }
182
183 /** Adjust file-related static fields as needed for this program */
184 private static void checkStatics(){
185 //Adjust the number of threads for input file reading
186 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
187 ByteFile.FORCE_MODE_BF2=true;
188 }
189
190 assert(FastaReadInputStream.settingsOK());
191 }
192
193 /** Ensure parameter ranges are within bounds and required parameters are set */
194 private boolean validateParams(){
195 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
196 // assert(false) : "TODO";
197 return true;
198 }
199
200 /*--------------------------------------------------------------*/
201 /*---------------- Outer Methods ----------------*/
202 /*--------------------------------------------------------------*/
203
204 /** Create read streams and process all data */
205 void process(Timer t){
206
207 if(process16S){
208 Read[] data=ProkObject.loadConsensusSequenceType("16S", true, true);
209 consensus16S=data[0].bases;
210 }
211 if(process18S){
212 Read[] data=ProkObject.loadConsensusSequenceType("18S", true, true);
213 consensus18S=data[0].bases;
214 }
215
216 //Turn off read validation in the input threads to increase speed
217 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
218 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
219
220 //Reset counters
221 readsProcessed=readsOut=0;
222 basesProcessed=basesOut=0;
223
224 for(FileFormat ff : ffin) {
225 //Create a read input stream
226 final ConcurrentReadInputStream cris=makeCris(ff);
227
228 //Process the reads in separate threads
229 spawnThreads(cris);
230 errorState|=ReadWrite.closeStream(cris);
231 }
232
233 //Do anything necessary after processing
234 if(ffout1!=null){
235 //Optionally create a read output stream
236 final ConcurrentReadOutputStream ros=makeCros(false);
237 long num=0;
238 for(Entry<Integer, Ribo> e : bestMap.entrySet()){
239 Read r=e.getValue().r;
240 readsOut++;
241 basesOut+=r.length();
242 ArrayList<Read> list=new ArrayList<Read>(1);
243 list.add(r);
244 ros.add(list, num);
245 num++;
246 }
247 //Close the read streams
248 errorState|=ReadWrite.closeStream(ros);
249 }
250
251 if(verbose){outstream.println("Finished; closing streams.");}
252
253 //Write anything that was accumulated by ReadStats
254 errorState|=ReadStats.writeAll();
255
256 //Reset read validation
257 Read.VALIDATE_IN_CONSTRUCTOR=vic;
258
259 //Report timing and results
260 t.stop();
261 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
262 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
263
264 //Throw an exception of there was an error in a thread
265 if(errorState){
266 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
267 }
268 }
269
270 private ConcurrentReadInputStream makeCris(FileFormat ff){
271 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ff, null);
272 cris.start(); //Start the stream
273 if(verbose){outstream.println("Started cris");}
274 boolean paired=cris.paired();
275 assert(!paired) : "This should not be paired input.";
276 return cris;
277 }
278
279 private ConcurrentReadOutputStream makeCros(boolean pairedInput){
280 if(ffout1==null){return null;}
281
282 //Select output buffer size based on whether it needs to be ordered
283 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
284
285 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout1, null, buff, null, false);
286 ros.start(); //Start the stream
287 return ros;
288 }
289
290 /*--------------------------------------------------------------*/
291 /*---------------- Thread Management ----------------*/
292 /*--------------------------------------------------------------*/
293
294 /** Spawn process threads */
295 private void spawnThreads(final ConcurrentReadInputStream cris){
296
297 //Do anything necessary prior to processing
298
299 //Determine how many threads may be used
300 final int threads=Shared.threads();
301
302 //Fill a list with ProcessThreads
303 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
304 for(int i=0; i<threads; i++){
305 alpt.add(new ProcessThread(cris, i));
306 }
307
308 //Start the threads and wait for them to finish
309 boolean success=ThreadWaiter.startAndWait(alpt, this);
310 errorState&=!success;
311 }
312
313 @Override
314 public final void accumulate(ProcessThread pt){
315 readsProcessed+=pt.readsProcessedT;
316 basesProcessed+=pt.basesProcessedT;
317 errorState|=(!pt.success);
318 }
319
320 @Override
321 public final boolean success(){return !errorState;}
322
323 /*--------------------------------------------------------------*/
324 /*---------------- Inner Methods ----------------*/
325 /*--------------------------------------------------------------*/
326
327 /*--------------------------------------------------------------*/
328 /*---------------- Inner Classes ----------------*/
329 /*--------------------------------------------------------------*/
330
331 /** This class is static to prevent accidental writing to shared variables.
332 * It is safe to remove the static modifier. */
333 class ProcessThread extends Thread {
334
335 //Constructor
336 ProcessThread(final ConcurrentReadInputStream cris_, final int tid_){
337 cris=cris_;
338 tid=tid_;
339 }
340
341 //Called by start()
342 @Override
343 public void run(){
344 //Do anything necessary prior to processing
345
346 //Process the reads
347 processInner();
348
349 //Do anything necessary after processing
350
351 //Indicate successful exit status
352 success=true;
353 }
354
355 /** Iterate through the reads */
356 void processInner(){
357
358 //Grab the first ListNum of reads
359 ListNum<Read> ln=cris.nextList();
360
361 //Check to ensure pairing is as expected
362 if(ln!=null && !ln.isEmpty()){
363 Read r=ln.get(0);
364 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
365 }
366
367 //As long as there is a nonempty read list...
368 while(ln!=null && ln.size()>0){
369 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
370
371 processList(ln);
372
373 //Notify the input stream that the list was used
374 cris.returnList(ln);
375 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
376
377 //Fetch a new list
378 ln=cris.nextList();
379 }
380
381 //Notify the input stream that the final list was used
382 if(ln!=null){
383 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
384 }
385 }
386
387 void processList(ListNum<Read> ln){
388
389 //Grab the actual read list from the ListNum
390 final ArrayList<Read> reads=ln.list;
391
392 //Loop through each read in the list
393 for(int idx=0; idx<reads.size(); idx++){
394 final Read r1=reads.get(idx);
395
396 //Validate reads in worker threads
397 if(!r1.validated()){r1.validate(true);}
398
399 //Track the initial length for statistics
400 final int initialLength1=r1.length();
401
402 //Increment counters
403 readsProcessedT++;
404 basesProcessedT+=initialLength1;
405
406 boolean keep=processRead(r1);
407 }
408 }
409
410 /**
411 * Process a read or a read pair.
412 * @return True if the reads should be kept, false if they should be discarded.
413 */
414 boolean processRead(final Read r){
415 Integer key=GiToTaxid.parseTaxidNumber(r.id, '|');
416 if(key==null || key==-1){return false;}
417 float id=align(r);
418 float product=id*r.length();
419 Ribo ribo=new Ribo(r, key, id);
420
421
422 synchronized(bestMap){
423 Ribo old=bestMap.get(key);
424 if(old==null || old.product<product){
425 bestMap.put(key, ribo);
426 return true;
427 }
428 }
429 return false;
430 }
431
432 float align(Read r){
433 float a=(process16S ? align(r.bases, consensus16S) : 0);
434 float b=(process18S ? align(r.bases, consensus18S) : 0);
435 return Tools.max(a, b);
436 }
437
438 float align(byte[] query, byte[] ref){
439 int a=0, b=ref.length-1;
440 int[] max=ssa.fillUnlimited(query, ref, a, b, -9999);
441 if(max==null){return 0;}
442
443 final int rows=max[0];
444 final int maxCol=max[1];
445 final int maxState=max[2];
446 final float id=ssa.tracebackIdentity(query, ref, a, b, rows, maxCol, maxState, null);
447 return id;
448 }
449
450 SingleStateAlignerFlat2 ssa=new SingleStateAlignerFlat2();
451
452 /** Number of reads processed by this thread */
453 protected long readsProcessedT=0;
454 /** Number of bases processed by this thread */
455 protected long basesProcessedT=0;
456
457 /** True only if this thread has completed successfully */
458 boolean success=false;
459
460 /** Shared input stream */
461 private final ConcurrentReadInputStream cris;
462 /** Thread ID */
463 final int tid;
464 }
465
466 private static class Ribo implements Comparable<Ribo>{
467 Ribo(Read r_, int tid_, float identity_){
468 r=r_;
469 tid=tid_;
470 identity=identity_;
471 product=r.length()*identity;
472 }
473
474 @Override
475 public int compareTo(Ribo o) {
476 if(o.product>product){return -1;}
477 else if(o.product<product){return 1;}
478 else if(o.r.length()>r.length()){return -1;}
479 else if(o.r.length()<r.length()){return 1;}
480 return 0;
481 }
482
483 Read r;
484 int tid;
485 float identity;
486 float product;
487 }
488
489 /*--------------------------------------------------------------*/
490 /*---------------- Fields ----------------*/
491 /*--------------------------------------------------------------*/
492
493 /** Primary input file path */
494 private ArrayList<String> in=new ArrayList<String>();
495
496 /** Alternate input file path */
497 private String alt=null;
498
499 /** Primary output file path */
500 private String out1=null;
501
502 /** Override input file extension */
503 private String extin=null;
504 /** Override output file extension */
505 private String extout=null;
506
507 HashMap<Integer, Ribo> bestMap=new HashMap<Integer, Ribo>(10000000);
508 HashMap<Integer, ArrayList<Ribo>> listMap=new HashMap<Integer, ArrayList<Ribo>>(10000000);
509
510 static byte[] consensus16S;
511 byte[] consensus18S;
512
513 /*--------------------------------------------------------------*/
514
515 /** Number of reads processed */
516 protected long readsProcessed=0;
517 /** Number of bases processed */
518 protected long basesProcessed=0;
519
520 /** Number of reads retained */
521 protected long readsOut=0;
522 /** Number of bases retained */
523 protected long basesOut=0;
524
525 /** Quit after processing this many input reads; -1 means no limit */
526 private long maxReads=-1;
527
528 private boolean process16S=true;
529 private boolean process18S=false;
530
531 /*--------------------------------------------------------------*/
532 /*---------------- Final Fields ----------------*/
533 /*--------------------------------------------------------------*/
534
535 /** Primary input file */
536 private final ArrayList<FileFormat> ffin;
537 private final FileFormat ffalt;
538
539 /** Primary output file */
540 private final FileFormat ffout1;
541
542 @Override
543 public final ReadWriteLock rwlock() {return rwlock;}
544 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
545
546 /*--------------------------------------------------------------*/
547 /*---------------- Common Fields ----------------*/
548 /*--------------------------------------------------------------*/
549
550 /** Print status messages to this output stream */
551 private PrintStream outstream=System.err;
552 /** Print verbose messages */
553 public static boolean verbose=false;
554 /** True if an error was encountered */
555 public boolean errorState=false;
556 /** Overwrite existing output files */
557 private boolean overwrite=true;
558 /** Append to existing output files */
559 private boolean append=false;
560 /** Reads are output in input order */
561 private boolean ordered=false;
562
563 }