Debian Codegraph @

current/template/A_Sample.java

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