Debian Codegraph @

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