Debian Codegraph @

current/driver/RenameAndMux.java

raw symbols SCIP
1 package driver;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.concurrent.atomic.AtomicInteger;
7 import java.util.concurrent.atomic.AtomicLong;
8
9 import fileIO.ByteFile;
10 import fileIO.FileFormat;
11 import fileIO.ReadWrite;
12 import shared.Parse;
13 import shared.Parser;
14 import shared.PreParser;
15 import shared.Shared;
16 import shared.Timer;
17 import shared.Tools;
18 import stream.ConcurrentReadInputStream;
19 import stream.ConcurrentReadOutputStream;
20 import stream.FASTQ;
21 import stream.FastaReadInputStream;
22 import stream.Read;
23 import structures.ListNum;
24
25 /**
26 * @author Brian Bushnell
27 * @date June 1, 2016
28 *
29 */
30 public class RenameAndMux {
31
32 /*--------------------------------------------------------------*/
33 /*---------------- Initialization ----------------*/
34 /*--------------------------------------------------------------*/
35
36 /**
37 * Code entrance from the command line.
38 * @param args Command line arguments
39 */
40 public static void main(String[] args){
41 Timer t=new Timer();
42 RenameAndMux x=new RenameAndMux(args);
43 x.process(t);
44
45 //Close the print stream if it was redirected
46 Shared.closeStream(x.outstream);
47 }
48
49 /**
50 * Constructor.
51 * @param args Command line arguments
52 */
53 public RenameAndMux(String[] args){
54
55 {//Preparse block for help, config files, and outstream
56 PreParser pp=new PreParser(args, getClass(), false);
57 args=pp.args;
58 outstream=pp.outstream;
59 }
60
61 //Set shared static variables
62 ReadWrite.USE_PIGZ=true;
63 ReadWrite.USE_UNPIGZ=false;
64 ReadWrite.USE_UNBGZIP=false;
65 ReadWrite.setZipThreads((Shared.threads()*3+1)/4);
66
67 //Create a parser object
68 Parser parser=new Parser();
69
70 //Parse each argument
71 for(int i=0; i<args.length; i++){
72 String arg=args[i];
73
74 //Break arguments into their constituent parts, in the form of "a=b"
75 String[] split=arg.split("=");
76 String a=split[0].toLowerCase();
77 String b=split.length>1 ? split[1] : null;
78
79 if(parser.parse(arg, a, b)){//Parse standard flags in the parser
80 //do nothing
81 }else if(a.equals("verbose")){
82 verbose=Parse.parseBoolean(b);
83 }else if(!arg.contains("=")){
84 String[] x=(new File(arg).exists() ? new String[] {arg} : arg.split(","));
85 for(String x2 : x){readPaths.add(x2);}
86 }else if(a.equals("parse_flag_goes_here")){
87 //Set a variable here
88 }else{
89 outstream.println("Unknown parameter "+args[i]);
90 assert(false) : "Unknown parameter "+args[i];
91 // throw new RuntimeException("Unknown parameter "+args[i]);
92 }
93 }
94
95 {//Process parser fields
96 Parser.processQuality();
97
98 maxReads=parser.maxReads;
99
100 overwrite=parser.overwrite;
101 setInterleaved=parser.setInterleaved;
102
103 if(parser.in1!=null){
104 for(String s : parser.in1.split(",")){
105 readPaths.add(s);
106 }
107 }
108
109 out1=parser.out1;
110 out2=parser.out2;
111
112 extin=parser.extin;
113 extout=parser.extout;
114 }
115
116 //Do output file # replacement
117 if(out1!=null && out2==null && out1.indexOf('#')>-1){
118 out2=out1.replace("#", "2");
119 out1=out1.replace("#", "1");
120 }
121 // System.err.println("out1="+out1+", out2="+out2);
122
123 assert(FastaReadInputStream.settingsOK());
124
125 //Ensure there is an input file
126 if(readPaths.isEmpty()){throw new RuntimeException("Error - at least one input file is required.");}
127
128 //Adjust the number of threads for input file reading
129 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
130 ByteFile.FORCE_MODE_BF2=true;
131 }
132
133 if(out1==null){throw new RuntimeException("Error - output destination is required.");}
134
135 //Ensure out2 is not set without out1
136 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
137
138 //Ensure output files can be written
139 if(!Tools.testOutputFiles(overwrite, false, false, out1, out2)){
140 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
141 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
142 }
143 }
144
145 /*--------------------------------------------------------------*/
146 /*---------------- Outer Methods ----------------*/
147 /*--------------------------------------------------------------*/
148
149 /** Create read streams and process all data */
150 void process(Timer t){
151
152 //Reset counters
153 readsProcessedA.set(0);
154 basesProcessedA.set(0);
155 nextListNumber.set(0);
156
157 //Process the read stream
158 renameAndMerge_MT();
159
160 final long readsProcessed=readsProcessedA.get();
161 final long basesProcessed=basesProcessedA.get();
162
163 //Report timing and results
164 t.stop();
165 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
166
167 //Throw an exception of there was an error in a thread
168 if(errorState){
169 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
170 }
171 }
172
173
174 // private void renameAndMerge_ST(){
175 //
176 // long readsProcessed=0;
177 // long basesProcessed=0;
178 //
179 // FileFormat ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, false, false);
180 // FileFormat ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, false, false);
181 //
182 // for(String path : readPaths){
183 //
184 // String in1=null, in2=null;
185 //
186 // //Do input file # replacement
187 // if(path.indexOf('#')>-1 && !new File(path).exists()){
188 // in2=path.replace("#", "2");
189 // in1=path.replace("#", "1");
190 // }
191 //
192 // //Adjust interleaved settings based on number of output files
193 // if(!setInterleaved){
194 // assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
195 // if(in2!=null){ //If there are 2 input streams.
196 // FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
197 // if(!printedInterleavedMessage){
198 // outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
199 // printedInterleavedMessage=true;
200 // }
201 // }else{ //There is one input stream.
202 // if(out2!=null){
203 // FASTQ.FORCE_INTERLEAVED=true;
204 // FASTQ.TEST_INTERLEAVED=false;
205 // if(!printedInterleavedMessage){
206 // outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
207 // printedInterleavedMessage=true;
208 // }
209 // }
210 // }
211 // }
212 //
213 // //Ensure input files can be read
214 // if(!Tools.testInputFiles(false, true, in1, in2)){
215 // throw new RuntimeException("\nCan't read some input files.\n");
216 // }
217 //
218 // //Ensure that no file was specified multiple times
219 // if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2)){
220 // throw new RuntimeException("\nSome file names were specified multiple times.\n");
221 // }
222 //
223 // final FileFormat ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
224 // final FileFormat ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
225 // final ConcurrentReadInputStream cris;
226 // final String core=ReadWrite.stripToCore(in1);
227 // {
228 // cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
229 // if(verbose){outstream.println("Started cris");}
230 // cris.start(); //4567
231 // }
232 // boolean paired=cris.paired();
233 // if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
234 // final ConcurrentReadOutputStream ros;
235 //
236 // final int buff=4;
237 //
238 // if(cris.paired()){
239 // outstream.println("Writing interleaved.");
240 // }
241 //
242 // ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, buff, null, false);
243 // ros.start();
244 //
245 // {
246 //
247 // ListNum<Read> ln=cris.nextList();
248 // ArrayList<Read> reads=(ln!=null ? ln.list : null);
249 //
250 // if(reads!=null && !reads.isEmpty()){
251 // Read r=reads.get(0);
252 // assert((r.mate!=null)==cris.paired());
253 // }
254 //
255 // while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
256 //
257 // for(int idx=0; idx<reads.size(); idx++){
258 // final Read r1=reads.get(idx);
259 // final Read r2=r1.mate;
260 //
261 // final int initialLength1=r1.length();
262 // final int initialLength2=(r1.mateLength());
263 //
264 // {
265 // readsProcessed++;
266 // basesProcessed+=initialLength1;
267 // r1.id=core+"_"+r1.numericID+" /1";
268 // }
269 // if(r2!=null){
270 // readsProcessed++;
271 // basesProcessed+=initialLength2;
272 // r2.id=core+"_"+r1.numericID+" /2";
273 // }
274 //
275 //
276 // }
277 //
278 // final ArrayList<Read> listOut=reads;
279 //
280 // if(ros!=null){ros.add(listOut, ln.id);}
281 //
282 // cris.returnList(ln);
283 // ln=cris.nextList();
284 // reads=(ln!=null ? ln.list : null);
285 // }
286 // if(ln!=null){
287 // cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
288 // }
289 // }
290 //
291 // errorState|=ReadWrite.closeStreams(cris, ros);
292 //
293 // ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, null, true, false, true, false);
294 // ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, null, true, false, true, false);
295 // }
296 // readsProcessedA.addAndGet(readsProcessed);
297 // basesProcessedA.addAndGet(basesProcessed);
298 // }
299
300 private void renameAndMerge_MT(){
301 FileFormat ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, false, ordered);
302 FileFormat ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, false, ordered);
303
304 final ConcurrentReadOutputStream ros;
305
306 final int buff=4;
307
308 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, buff, null, false);
309 ros.start();
310 // System.err.println("Started ros.");
311
312 final int threads=Shared.threads();
313 ArrayList<MuxThread> list=new ArrayList<MuxThread>(threads);
314 for(int i=0; i<threads; i++){
315 MuxThread mt=new MuxThread(ros);
316 list.add(mt);
317 mt.start();
318 }
319
320 // System.err.println("Started threads.");
321 for(MuxThread mt : list){
322 while(mt.getState()!=Thread.State.TERMINATED){
323 try {
324 mt.join();
325 // System.err.println("Joined.");
326 } catch (InterruptedException e) {
327 // TODO Auto-generated catch block
328 e.printStackTrace();
329 }
330 }
331 // System.err.println(mt.getState());
332 }
333 // System.err.println("All threads finished.");
334
335 errorState|=ReadWrite.closeStream(ros);
336 }
337
338 void renameAndMergeOneFile(final String path, final ConcurrentReadOutputStream ros){
339
340 long readsProcessed=0;
341 long basesProcessed=0;
342
343 String in1=path, in2=null;
344
345 //Do input file # replacement
346 if(path.indexOf('#')>-1 && !new File(path).exists()){
347 in2=path.replace("#", "2");
348 in1=path.replace("#", "1");
349 }
350
351 synchronized(getClass()){
352
353 //Adjust interleaved settings based on number of output files
354 if(!setInterleaved){
355 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
356 if(in2!=null){ //If there are 2 input streams.
357 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
358 if(!printedInterleavedMessage){
359 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
360 printedInterleavedMessage=true;
361 }
362 }else{ //There is one input stream.
363 if(out2!=null){
364 FASTQ.FORCE_INTERLEAVED=true;
365 FASTQ.TEST_INTERLEAVED=false;
366 if(!printedInterleavedMessage){
367 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
368 printedInterleavedMessage=true;
369 }
370 }
371 }
372 }
373
374 //Ensure input files can be read
375 if(!Tools.testInputFiles(false, true, in1, in2)){
376 throw new RuntimeException("\nCan't read some input files.\n");
377 }
378
379 //Ensure that no file was specified multiple times
380 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2)){
381 throw new RuntimeException("\nSome file names were specified multiple times.\n");
382 }
383 }
384
385 final FileFormat ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
386 final FileFormat ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
387 final ConcurrentReadInputStream cris;
388 final String core=ReadWrite.stripToCore(in1);
389 {
390 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2);
391 if(verbose){outstream.println("Started cris");}
392 cris.start(); //4567
393 }
394 boolean paired=cris.paired();
395 // if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
396
397
398 {
399
400 ListNum<Read> ln=cris.nextList();
401 ArrayList<Read> reads=(ln!=null ? ln.list : null);
402
403 if(reads!=null && !reads.isEmpty()){
404 Read r=reads.get(0);
405 assert((r.mate!=null)==cris.paired());
406 }
407
408 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
409
410 for(int idx=0; idx<reads.size(); idx++){
411 final Read r1=reads.get(idx);
412 final Read r2=r1.mate;
413
414 final int initialLength1=r1.length();
415 final int initialLength2=(r1.mateLength());
416
417 {
418 readsProcessed++;
419 basesProcessed+=initialLength1;
420 r1.id=core+"_"+r1.numericID+" 1:";
421 }
422 if(r2!=null){
423 readsProcessed++;
424 basesProcessed+=initialLength2;
425 r2.id=core+"_"+r1.numericID+" 2:";
426 }
427
428
429 }
430
431 final ArrayList<Read> listOut=reads;
432
433 if(ros!=null){ros.add(listOut, 0/*nextListNumber.getAndIncrement()*/);}
434
435 cris.returnList(ln);
436 ln=cris.nextList();
437 reads=(ln!=null ? ln.list : null);
438 }
439 if(ln!=null){
440 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
441 }
442 }
443
444 synchronized(getClass()){
445 errorState|=ReadWrite.closeStream(cris);
446 }
447 readsProcessedA.addAndGet(readsProcessed);
448 basesProcessedA.addAndGet(basesProcessed);
449 }
450
451
452 /*--------------------------------------------------------------*/
453 /*---------------- Nested Classes ----------------*/
454 /*--------------------------------------------------------------*/
455
456 private class MuxThread extends Thread{
457
458 MuxThread(ConcurrentReadOutputStream ros_){
459 ros=ros_;
460 }
461
462 @Override
463 public void run(){
464 for(int i=nextPathNumber.getAndIncrement(); i<readPaths.size(); i=nextPathNumber.getAndIncrement()){
465 renameAndMergeOneFile(readPaths.get(i), ros);
466 }
467 }
468
469 final ConcurrentReadOutputStream ros;
470 }
471
472 /*--------------------------------------------------------------*/
473 /*---------------- Inner Methods ----------------*/
474 /*--------------------------------------------------------------*/
475
476 /*--------------------------------------------------------------*/
477 /*---------------- Fields ----------------*/
478 /*--------------------------------------------------------------*/
479
480 protected ArrayList<String> readPaths=new ArrayList<String>();
481
482 protected String out1, out2;
483
484 protected String extin;
485 protected String extout;
486
487 /*--------------------------------------------------------------*/
488
489 /** Number of reads processed */
490 protected AtomicLong readsProcessedA=new AtomicLong(0);
491 /** Number of bases processed */
492 protected AtomicLong basesProcessedA=new AtomicLong(0);
493
494 protected AtomicLong nextListNumber=new AtomicLong(0);
495
496 protected AtomicInteger nextPathNumber=new AtomicInteger(0);
497
498 /** Quit after processing this many input reads; -1 means no limit */
499 private long maxReads=-1;
500
501 /*--------------------------------------------------------------*/
502 /*---------------- Common Fields ----------------*/
503 /*--------------------------------------------------------------*/
504
505 /** Print status messages to this output stream */
506 private PrintStream outstream=System.err;
507 /** Print verbose messages */
508 public static boolean verbose=false;
509 /** True if an error was encountered */
510 public boolean errorState=false;
511 /** Overwrite existing output files */
512 private boolean overwrite=true;
513 /** This flag has no effect on singlethreaded programs */
514 private final boolean ordered=false;
515 /** Whether interleaved was explicitly set. */
516 private boolean setInterleaved=false;
517
518 private boolean printedInterleavedMessage=false;
519 }