Debian Codegraph @

current/hiseq/BGI2Illumina.java

raw symbols SCIP
1 package hiseq;
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.Parse;
11 import shared.Parser;
12 import shared.PreParser;
13 import shared.Shared;
14 import shared.Timer;
15 import shared.Tools;
16 import stream.ConcurrentReadInputStream;
17 import stream.ConcurrentReadOutputStream;
18 import stream.FASTQ;
19 import stream.FastaReadInputStream;
20 import stream.Read;
21 import structures.ListNum;
22 import tracker.ReadStats;
23
24 /**
25 * Converts BGI to Illumina headers
26 *
27 * @author Brian Bushnell
28 * @date May 6, 2024
29 *
30 */
31 public class BGI2Illumina {
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 //Start a timer immediately upon code entrance.
43 Timer t=new Timer();
44
45 //Create an instance of this class
46 BGI2Illumina x=new BGI2Illumina(args);
47
48 //Run the object
49 x.process(t);
50
51 //Close the print stream if it was redirected
52 Shared.closeStream(x.outstream);
53 }
54
55 /**
56 * Constructor.
57 * @param args Command line arguments
58 */
59 public BGI2Illumina(String[] args){
60
61 {//Preparse block for help, config files, and outstream
62 PreParser pp=new PreParser(args, null /*getClass()*/, false);
63 args=pp.args;
64 outstream=pp.outstream;
65 }
66
67 //Set shared static variables prior to parsing
68 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
69 ReadWrite.setZipThreads(Shared.threads());
70 Shared.capBuffers(4); //Only for singlethreaded programs
71
72 FASTQ.ASCII_OFFSET=33;
73 FASTQ.ASCII_OFFSET_OUT=33;
74 FASTQ.DETECT_QUALITY=false;
75 FASTQ.TEST_INTERLEAVED=true;
76
77 {//Parse the arguments
78 final Parser parser=parse(args);
79 Parser.processQuality();
80
81 maxReads=parser.maxReads;
82 overwrite=ReadStats.overwrite=parser.overwrite;
83 append=ReadStats.append=parser.append;
84 setInterleaved=parser.setInterleaved;
85
86 in1=parser.in1;
87 in2=parser.in2;
88 qfin1=parser.qfin1;
89 qfin2=parser.qfin2;
90 extin=parser.extin;
91
92 out1=parser.out1;
93 out2=parser.out2;
94 qfout1=parser.qfout1;
95 qfout2=parser.qfout2;
96 extout=parser.extout;
97 }
98
99 doPoundReplacement(); //Replace # with 1 and 2
100 adjustInterleaving(); //Make sure interleaving agrees with number of input and output files
101 fixExtensions(); //Add or remove .gz or .bz2 as needed
102 checkFileExistence(); //Ensure files can be read and written
103 checkStatics(); //Adjust file-related static fields as needed for this program
104
105 //Create output FileFormat objects
106 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
107 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
108
109 //Create input FileFormat objects
110 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
111 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
112 }
113
114 /*--------------------------------------------------------------*/
115 /*---------------- Initialization Helpers ----------------*/
116 /*--------------------------------------------------------------*/
117
118 /** Parse arguments from the command line */
119 private Parser parse(String[] args){
120
121 //Create a parser object
122 Parser parser=new Parser();
123
124 //Set any necessary Parser defaults here
125 //parser.foo=bar;
126
127 //Parse each argument
128 for(int i=0; i<args.length; i++){
129 String arg=args[i];
130
131 //Break arguments into their constituent parts, in the form of "a=b"
132 String[] split=arg.split("=");
133 String a=split[0].toLowerCase();
134 String b=split.length>1 ? split[1] : null;
135 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
136
137 if(a.equals("verbose")){
138 verbose=Parse.parseBoolean(b);
139 }else if(a.equals("parseextra") || a.equals("extra")){
140 BGIHeaderParser2.PARSE_EXTRA=Parse.parseBoolean(b);
141 }else if(a.equals("barcode") || a.equals("index")){
142 barcode=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{
149 outstream.println("Unknown parameter "+args[i]);
150 assert(false) : "Unknown parameter "+args[i];
151 }
152 }
153
154 return parser;
155 }
156
157 /** Replace # with 1 and 2 in headers */
158 private void doPoundReplacement(){
159 //Do input file # replacement
160 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
161 in2=in1.replace("#", "2");
162 in1=in1.replace("#", "1");
163 }
164
165 //Do output file # replacement
166 if(out1!=null && out2==null && out1.indexOf('#')>-1){
167 out2=out1.replace("#", "2");
168 out1=out1.replace("#", "1");
169 }
170
171 //Ensure there is an input file
172 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
173
174 //Ensure out2 is not set without out1
175 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
176 }
177
178 /** Add or remove .gz or .bz2 as needed */
179 private void fixExtensions(){
180 in1=Tools.fixExtension(in1);
181 in2=Tools.fixExtension(in2);
182 qfin1=Tools.fixExtension(qfin1);
183 qfin2=Tools.fixExtension(qfin2);
184 }
185
186 /** Ensure files can be read and written */
187 private void checkFileExistence(){
188 //Ensure output files can be written
189 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
190 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
191 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
192 }
193
194 //Ensure input files can be read
195 if(!Tools.testInputFiles(false, true, in1, in2)){
196 throw new RuntimeException("\nCan't read some input files.\n");
197 }
198
199 //Ensure that no file was specified multiple times
200 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2)){
201 throw new RuntimeException("\nSome file names were specified multiple times.\n");
202 }
203 }
204
205 /** Make sure interleaving agrees with number of input and output files */
206 private void adjustInterleaving(){
207 //Adjust interleaved detection based on the number of input files
208 if(in2!=null){
209 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
210 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
211 }
212
213 //Adjust interleaved settings based on number of output files
214 if(!setInterleaved){
215 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
216 if(in2!=null){ //If there are 2 input streams.
217 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
218 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
219 }else{ //There is one input stream.
220 if(out2!=null){
221 FASTQ.FORCE_INTERLEAVED=true;
222 FASTQ.TEST_INTERLEAVED=false;
223 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
224 }
225 }
226 }
227 }
228
229 /** Adjust file-related static fields as needed for this program */
230 private static void checkStatics(){
231 //Adjust the number of threads for input file reading
232 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
233 ByteFile.FORCE_MODE_BF2=true;
234 }
235
236 assert(FastaReadInputStream.settingsOK());
237 }
238
239 /*--------------------------------------------------------------*/
240 /*---------------- Outer Methods ----------------*/
241 /*--------------------------------------------------------------*/
242
243 /** Create read streams and process all data */
244 void process(Timer t){
245
246 //Create a read input stream
247 final ConcurrentReadInputStream cris=makeCris();
248
249 //Optionally create a read output stream
250 final ConcurrentReadOutputStream ros=makeCros(cris.paired());
251
252 //Reset counters
253 readsProcessed=readsOut=0;
254 basesProcessed=basesOut=0;
255
256 //Process the read stream
257 processInner(cris, ros);
258
259 if(verbose){outstream.println("Finished; closing streams.");}
260
261 //Write anything that was accumulated by ReadStats
262 errorState|=ReadStats.writeAll();
263 //Close the read streams
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 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
270
271 //Throw an exception of there was an error in a thread
272 if(errorState){
273 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
274 }
275 }
276
277 /*--------------------------------------------------------------*/
278 /*---------------- Inner Methods ----------------*/
279 /*--------------------------------------------------------------*/
280
281 private ConcurrentReadInputStream makeCris(){
282 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
283 cris.start(); //Start the stream
284 if(verbose){outstream.println("Started cris");}
285 boolean paired=cris.paired();
286 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
287 return cris;
288 }
289
290 private ConcurrentReadOutputStream makeCros(boolean pairedInput){
291 if(ffout1==null){return null;}
292
293 //Select output buffer size based on whether it needs to be ordered
294 final int buff=4;
295
296 //Notify user of output mode
297 if(pairedInput && out2==null && (in1!=null && !ffin1.samOrBam() && !ffout1.samOrBam())){
298 outstream.println("Writing interleaved.");
299 }
300
301 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, false);
302 ros.start(); //Start the stream
303 return ros;
304 }
305
306 /** Iterate through the reads */
307 void processInner(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
308
309 //Do anything necessary prior to processing
310
311 {
312 //Grab the first ListNum of reads
313 ListNum<Read> ln=cris.nextList();
314
315 //Check to ensure pairing is as expected
316 if(ln!=null && !ln.isEmpty()){
317 Read r=ln.get(0);
318 assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired());
319 }
320
321 //As long as there is a nonempty read list...
322 while(ln!=null && ln.size()>0){
323 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
324
325 processList(ln, cris, ros);
326
327 //Fetch a new list
328 ln=cris.nextList();
329 }
330
331 //Notify the input stream that the final list was used
332 if(ln!=null){
333 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
334 }
335 }
336
337 //Do anything necessary after processing
338
339 }
340
341 /**
342 * Process a list of Reads.
343 * @param ln The list.
344 * @param cris Read Input Stream
345 * @param ros Read Output Stream for reads that will be retained
346 */
347 void processList(ListNum<Read> ln, final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
348
349 //Grab the actual read list from the ListNum
350 final ArrayList<Read> reads=ln.list;
351
352 //Loop through each read in the list
353 for(int idx=0; idx<reads.size(); idx++){
354 final Read r1=reads.get(idx);
355 final Read r2=r1.mate;
356
357 //Validate reads in worker threads
358 if(!r1.validated()){r1.validate(true);}
359 if(r2!=null && !r2.validated()){r2.validate(true);}
360
361 //Track the initial length for statistics
362 final int initialLength1=r1.length();
363 final int initialLength2=r1.mateLength();
364
365 //Increment counters
366 readsProcessed+=r1.pairCount();
367 basesProcessed+=initialLength1+initialLength2;
368
369 {
370 //Reads are processed in this block.
371 boolean keep=processReadPair(r1, r2);
372
373 if(!keep){reads.set(idx, null);}
374 else{
375 readsOut+=r1.pairCount();
376 basesOut+=r1.pairLength();
377 }
378 }
379 }
380
381 //Output reads to the output stream
382 if(ros!=null){ros.add(reads, ln.id);}
383
384 //Notify the input stream that the list was used
385 cris.returnList(ln);
386 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
387 }
388
389
390 /**
391 * Process a single read pair.
392 * @param r1 Read 1
393 * @param r2 Read 2 (may be null)
394 * @return True if the reads should be kept, false if they should be discarded.
395 */
396 boolean processReadPair(final Read r1, final Read r2){
397 bhp.parse(r1.id);
398 r1.id=bhp.toIllumina(barcode);
399 if(r2!=null) {
400 bhp.parse(r2.id);
401 r2.id=bhp.toIllumina(barcode);
402 }
403 return true;
404 }
405
406 /*--------------------------------------------------------------*/
407 /*---------------- Fields ----------------*/
408 /*--------------------------------------------------------------*/
409
410 /** Primary input file path */
411 private String in1=null;
412 /** Secondary input file path */
413 private String in2=null;
414
415 private String qfin1=null;
416 private String qfin2=null;
417
418 /** Primary output file path */
419 private String out1=null;
420 /** Secondary output file path */
421 private String out2=null;
422
423 private String qfout1=null;
424 private String qfout2=null;
425
426 /** Override input file extension */
427 private String extin=null;
428 /** Override output file extension */
429 private String extout=null;
430
431 /** Whether interleaved was explicitly set. */
432 private boolean setInterleaved=false;
433
434 private String barcode=null;
435
436 private BGIHeaderParser2 bhp=new BGIHeaderParser2();
437
438 /*--------------------------------------------------------------*/
439
440 /** Number of reads processed */
441 protected long readsProcessed=0;
442 /** Number of bases processed */
443 protected long basesProcessed=0;
444
445 /** Number of reads retained */
446 protected long readsOut=0;
447 /** Number of bases retained */
448 protected long basesOut=0;
449
450 /** Quit after processing this many input reads; -1 means no limit */
451 private long maxReads=-1;
452
453 /*--------------------------------------------------------------*/
454 /*---------------- Final Fields ----------------*/
455 /*--------------------------------------------------------------*/
456
457 /** Primary input file */
458 private final FileFormat ffin1;
459 /** Secondary input file */
460 private final FileFormat ffin2;
461
462 /** Primary output file */
463 private final FileFormat ffout1;
464 /** Secondary output file */
465 private final FileFormat ffout2;
466
467 /*--------------------------------------------------------------*/
468 /*---------------- Common Fields ----------------*/
469 /*--------------------------------------------------------------*/
470
471 /** Print status messages to this output stream */
472 private PrintStream outstream=System.err;
473 /** Print verbose messages */
474 public static boolean verbose=false;
475 /** True if an error was encountered */
476 public boolean errorState=false;
477 /** Overwrite existing output files */
478 private boolean overwrite=true;
479 /** Append to existing output files */
480 private boolean append=false;
481 /** This flag has no effect on singlethreaded programs */
482 private final boolean ordered=false;
483
484 }