Debian Codegraph @

current/jgi/ReplaceHeaders.java

raw symbols SCIP
1 package jgi;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6
7 import fileIO.ByteFile;
8 import fileIO.FileFormat;
9 import fileIO.ReadWrite;
10 import shared.KillSwitch;
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 structures.ListNum;
23 import tracker.ReadStats;
24
25 /**
26 * Replaces read headers with other headers.
27 *
28 * @author Brian Bushnell
29 * @date May 23, 2016
30 *
31 */
32 public class ReplaceHeaders {
33
34 /*--------------------------------------------------------------*/
35 /*---------------- Initialization ----------------*/
36 /*--------------------------------------------------------------*/
37
38 /**
39 * Code entrance from the command line.
40 * @param args Command line arguments
41 */
42 public static void main(String[] args){
43 Timer t=new Timer();
44 ReplaceHeaders x=new ReplaceHeaders(args);
45 x.process(t);
46
47 //Close the print stream if it was redirected
48 Shared.closeStream(x.outstream);
49 }
50
51 /**
52 * Constructor.
53 * @param args Command line arguments
54 */
55 public ReplaceHeaders(String[] args){
56
57 {//Preparse block for help, config files, and outstream
58 PreParser pp=new PreParser(args, getClass(), false);
59 args=pp.args;
60 outstream=pp.outstream;
61 }
62
63 boolean setInterleaved=false; //Whether interleaved was explicitly set.
64
65 //Set shared static variables
66 Shared.setBufferLen(1);//Tools.min(200, Shared.bufferLen());
67 Shared.capBuffers(4);
68 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
69 ReadWrite.setZipThreads(Shared.threads());
70
71 //Create a parser object
72 Parser parser=new Parser();
73
74 //Parse each argument
75 for(int i=0; i<args.length; i++){
76 String arg=args[i];
77
78 //Break arguments into their constituent parts, in the form of "a=b"
79 String[] split=arg.split("=");
80 String a=split[0].toLowerCase();
81 String b=split.length>1 ? split[1] : null;
82
83 if(parser.parse(arg, a, b)){//Parse standard flags in the parser
84 //do nothing
85 }else if(a.equals("hin") || a.equals("hin1") || a.equals("inh") || a.equals("inh1") || a.equals("headerin") || a.equals("headerin1")){
86 hin1=b;
87 }else if(a.equals("hin2") || a.equals("inh2") || a.equals("headerin2")){
88 hin2=b;
89 }else if(a.equals("prefix") || a.equals("addprefix")){
90 prefix=Parse.parseBoolean(b);
91 }else if(a.equals("verbose")){
92 verbose=Parse.parseBoolean(b);
93 }else if(a.equals("parse_flag_goes_here")){
94 //Set a variable here
95 }else{
96 outstream.println("Unknown parameter "+args[i]);
97 assert(false) : "Unknown parameter "+args[i];
98 // throw new RuntimeException("Unknown parameter "+args[i]);
99 }
100 }
101
102 {//Process parser fields
103 Parser.processQuality();
104
105 maxReads=parser.maxReads;
106
107 overwrite=ReadStats.overwrite=parser.overwrite;
108 append=ReadStats.append=parser.append;
109 setInterleaved=parser.setInterleaved;
110
111 in1=parser.in1;
112 in2=parser.in2;
113 qfin1=parser.qfin1;
114 qfin2=parser.qfin2;
115
116 out1=parser.out1;
117 out2=parser.out2;
118 qfout1=parser.qfout1;
119 qfout2=parser.qfout2;
120
121 extin=parser.extin;
122 extout=parser.extout;
123 }
124
125 //Do input file # replacement
126 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
127 in2=in1.replace("#", "2");
128 in1=in1.replace("#", "1");
129 }
130
131 //Do header input file # replacement
132 if(hin1!=null && hin2==null && hin1.indexOf('#')>-1 && !new File(hin1).exists()){
133 hin2=hin1.replace("#", "2");
134 hin1=hin1.replace("#", "1");
135 }
136
137 //Do output file # replacement
138 if(out1!=null && out2==null && out1.indexOf('#')>-1){
139 out2=out1.replace("#", "2");
140 out1=out1.replace("#", "1");
141 }
142
143 //Adjust interleaved detection based on the number of input files
144 if(in2!=null){
145 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
146 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
147 }
148
149 assert(FastaReadInputStream.settingsOK());
150
151 //Ensure there is an input file
152 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
153
154 //Ensure there is an input file
155 if(hin1==null){throw new RuntimeException("Error - at least one header input file is required.");}
156
157 //Adjust the number of threads for input file reading
158 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
159 ByteFile.FORCE_MODE_BF2=true;
160 }
161
162 //Ensure out2 is not set without out1
163 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
164
165 //Adjust interleaved settings based on number of output files
166 if(!setInterleaved){
167 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
168 if(in2!=null){ //If there are 2 input streams.
169 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
170 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
171 }else{ //There is one input stream.
172 if(out2!=null){
173 FASTQ.FORCE_INTERLEAVED=true;
174 FASTQ.TEST_INTERLEAVED=false;
175 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
176 }
177 }
178 }
179
180 //Ensure output files can be written
181 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
182 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
183 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
184 }
185
186 //Ensure input files can be read
187 if(!Tools.testInputFiles(false, true, in1, in2, hin1, hin2)){
188 throw new RuntimeException("\nCan't read some input files.\n");
189 }
190
191 //Ensure that no file was specified multiple times
192 if(!Tools.testForDuplicateFiles(true, in1, in2, hin1, hin2, out1, out2)){
193 throw new RuntimeException("\nSome file names were specified multiple times.\n");
194 }
195
196 //Create output FileFormat objects
197 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
198 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
199
200 //Create input FileFormat objects
201 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
202 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
203
204 //Create input FileFormat objects
205 ffhin1=FileFormat.testInput(hin1, FileFormat.HEADER, null, true, true);
206 ffhin2=FileFormat.testInput(hin2, FileFormat.HEADER, null, true, true);
207 }
208
209 /*--------------------------------------------------------------*/
210 /*---------------- Outer Methods ----------------*/
211 /*--------------------------------------------------------------*/
212
213 /** Create read streams and process all data */
214 void process(Timer t){
215
216 //Create a read input stream
217 final ConcurrentReadInputStream cris;
218 {
219 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
220 cris.start(); //Start the stream
221 if(verbose){outstream.println("Started cris");}
222 }
223 final boolean paired=cris.paired();
224 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
225
226 //Create a read input stream for headers
227 final ConcurrentReadInputStream hcris;
228 {
229 hcris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffhin1, ffhin2, null, null);
230 hcris.start(); //Start the stream
231 boolean paired2=hcris.paired();
232 if(verbose){outstream.println("Started hcris");}
233 if(paired!=paired2){
234 KillSwitch.kill("Reads and heades must agree on pairedness: reads="+paired+", headers="+paired2);
235 }
236 }
237
238 //Optionally create a read output stream
239 final ConcurrentReadOutputStream ros;
240 if(ffout1!=null){
241 final int buff=4;
242
243 if(cris.paired() && out2==null && (in1!=null && !ffin1.samOrBam() && !ffout1.samOrBam())){
244 outstream.println("Writing interleaved.");
245 }
246
247 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, false);
248 ros.start(); //Start the stream
249 }else{ros=null;}
250
251 //Reset counters
252 readsProcessed=0;
253 basesProcessed=0;
254
255 //Process the read stream
256 processInner(cris, hcris, ros);
257
258 if(verbose){outstream.println("Finished; closing streams.");}
259
260 //Write anything that was accumulated by ReadStats
261 errorState|=ReadStats.writeAll();
262 //Close the read streams
263 errorState|=ReadWrite.closeStreams(hcris);
264 errorState|=ReadWrite.closeStreams(cris, ros);
265
266 //Report timing and results
267 t.stop();
268 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
269
270 //Throw an exception of there was an error in a thread
271 if(errorState){
272 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
273 }
274 }
275
276 /** Iterate through the reads */
277 void processInner(final ConcurrentReadInputStream cris, final ConcurrentReadInputStream hcris, final ConcurrentReadOutputStream ros){
278
279 //Do anything necessary prior to processing
280
281 {
282 //Grab the first ListNum of reads
283 ListNum<Read> ln=cris.nextList();
284 //Grab the actual read list from the ListNum
285 ArrayList<Read> reads=(ln!=null ? ln.list : null);
286
287 //Grab the first ListNum of headers
288 ListNum<Read> hln=hcris.nextList();
289 //Grab the actual read list from the ListNum
290 ArrayList<Read> hreads=(hln!=null ? hln.list : null);
291
292 if(hreads==null || hreads.size()!=reads.size()){
293 KillSwitch.kill("Wrong number of headers for the reads: "+reads.size()+"!="+hreads.size());
294 }
295
296 //Check to ensure pairing is as expected
297 if(reads!=null && !reads.isEmpty()){
298 Read r=reads.get(0);
299 Read h=hreads.get(0);
300 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
301 assert((r.mate!=null) == (h.mate!=null));
302 }
303
304 //As long as there is a nonempty read list...
305 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
306 if(verbose){
307 outstream.println("Fetched "+reads.size()+" reads: "+reads.get(0).id+"\n"+reads.get(0).length());
308 outstream.println("Fetched "+hreads.size()+" headers.");
309 }
310
311 //Loop through each read in the list
312 for(int idx=0; idx<reads.size(); idx++){
313 final Read r1=reads.get(idx);
314 final Read r2=r1.mate;
315
316 final Read h1=hreads.get(idx);
317 final Read h2=h1.mate;
318
319 //Track the initial length for statistics
320 final int initialLength1=r1.length();
321 final int initialLength2=(r1.mateLength());
322
323 //Increment counters
324 readsProcessed+=r1.pairCount();
325 basesProcessed+=initialLength1+initialLength2;
326
327 boolean keep=processReadPair(r1, r2, h1, h2);
328 if(!keep){reads.set(idx, null);}
329 }
330
331 //Output reads to the output stream
332 if(ros!=null){ros.add(reads, ln.id);}
333
334 //Notify the input stream that the list was used
335 cris.returnList(ln);
336 if(verbose){outstream.println("Returned a read list.");}
337
338 //Notify the input stream that the list was used
339 hcris.returnList(hln.id, hln.list.isEmpty());
340 if(verbose){outstream.println("Returned a header list.");}
341
342 //Fetch a new list
343 ln=cris.nextList();
344 reads=(ln!=null ? ln.list : null);
345
346 //Fetch a new header list
347 hln=hcris.nextList();
348 hreads=(hln!=null ? hln.list : null);
349 }
350
351 //Notify the input stream that the final list was used
352 if(ln!=null){
353 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
354 }
355
356 //Notify the input stream that the final header list was used
357 if(hln!=null){
358 hcris.returnList(hln.id, hln.list==null || hln.list.isEmpty());
359 }
360 }
361
362 //Do anything necessary after processing
363
364 }
365
366 /*--------------------------------------------------------------*/
367 /*---------------- Inner Methods ----------------*/
368 /*--------------------------------------------------------------*/
369
370 /**
371 * Process a single read pair.
372 * @param r1 Read 1
373 * @param r2 Read 2 (may be null)
374 * @return True if the reads should be kept, false if they should be discarded.
375 */
376 boolean processReadPair(final Read r1, final Read r2, final Read h1, final Read h2){
377 if(prefix){
378 r1.id=h1.id+" "+r1.id;
379 if(r2!=null){r2.id=h2.id+" "+r2.id;}
380 }else{
381 r1.id=h1.id;
382 if(r2!=null){r2.id=h2.id;}
383 }
384 return true;
385 }
386
387 /*--------------------------------------------------------------*/
388 /*---------------- Fields ----------------*/
389 /*--------------------------------------------------------------*/
390
391 /** Primary input file path */
392 private String in1=null;
393 /** Secondary input file path */
394 private String in2=null;
395
396 /** Primary header input file path */
397 private String hin1=null;
398 /** Secondary header input file path */
399 private String hin2=null;
400
401 private String qfin1=null;
402 private String qfin2=null;
403
404 /** Primary output file path */
405 private String out1=null;
406 /** Secondary output file path */
407 private String out2=null;
408
409 private String qfout1=null;
410 private String qfout2=null;
411
412 /** Override input file extension */
413 private String extin=null;
414 /** Override output file extension */
415 private String extout=null;
416
417 /** Prepend the new name to the old name */
418 private boolean prefix=false;
419
420 /*--------------------------------------------------------------*/
421
422 /** Number of reads processed */
423 protected long readsProcessed=0;
424 /** Number of bases processed */
425 protected long basesProcessed=0;
426
427 /** Quit after processing this many input reads; -1 means no limit */
428 private long maxReads=-1;
429
430 /*--------------------------------------------------------------*/
431 /*---------------- Final Fields ----------------*/
432 /*--------------------------------------------------------------*/
433
434 /** Primary input file */
435 private final FileFormat ffin1;
436 /** Secondary input file */
437 private final FileFormat ffin2;
438
439 /** Primary header input file */
440 private final FileFormat ffhin1;
441 /** Secondary header input file */
442 private final FileFormat ffhin2;
443
444 /** Primary output file */
445 private final FileFormat ffout1;
446 /** Secondary output file */
447 private final FileFormat ffout2;
448
449 /*--------------------------------------------------------------*/
450 /*---------------- Common Fields ----------------*/
451 /*--------------------------------------------------------------*/
452
453 /** Print status messages to this output stream */
454 private PrintStream outstream=System.err;
455 /** Print verbose messages */
456 public static boolean verbose=false;
457 /** True if an error was encountered */
458 public boolean errorState=false;
459 /** Overwrite existing output files */
460 private boolean overwrite=true;
461 /** Append to existing output files */
462 private boolean append=false;
463
464 }