Debian Codegraph @

current/template/BBTool_ST.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 * @author Brian Bushnell
26 * @date Jan 12, 2015
27 *
28 */
29 public abstract class BBTool_ST {
30
31 /*--------------------------------------------------------------*/
32 /*---------------- Initialization ----------------*/
33 /*--------------------------------------------------------------*/
34
35 /**
36 * Code entrance from the command line.
37 * Must be overridden; the commented body is an example.
38 * @param args Command line arguments
39 */
40 public static void main(String[] args){
41 throw new RuntimeException("This method must be overridden.");
42 /*
43 //Example:
44 Timer t=new Timer();
45 BBTool_ST bbt=new BBTool_ST(args);
46 bbt.process(t);
47 */
48 }
49
50 /**
51 * Constructor. Parses argument list and sets relevant fields.
52 * Must be called by subclass.
53 * @param args Command line arguments
54 */
55 public BBTool_ST(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 it was explicitly set.
64
65 Shared.capBuffers(4);
66 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
67 ReadWrite.setZipThreads(Tools.max(Shared.threads()>1 ? 2 : 1, Shared.threads()>20 ? Shared.threads()/2 : Shared.threads()));
68
69 setDefaults();
70
71 Parser parser=new Parser();
72 for(int i=0; i<args.length; i++){
73 String arg=args[i];
74 String[] split=arg.split("=");
75 String a=split[0].toLowerCase();
76 String b=split.length>1 ? split[1] : null;
77
78 if(parseArgument(arg, a, b)){
79 // do nothing
80 }else if(parser.parse(arg, a, b)){
81 //do nothing
82 }else if(a.equals("parse_flag_goes_here")){
83 //Set a variable here
84 }else if(a.equals("verbose")){
85 verbose=Parse.parseBoolean(b);
86 }else{
87 throw new RuntimeException("Unknown parameter "+args[i]);
88 }
89 }
90
91 {//Process parser fields
92 Parser.processQuality();
93
94 maxReads=parser.maxReads;
95
96 overwrite=ReadStats.overwrite=parser.overwrite;
97 append=ReadStats.append=parser.append;
98
99 setInterleaved=parser.setInterleaved;
100
101 in1=parser.in1;
102 in2=parser.in2;
103 qfin1=parser.qfin1;
104 qfin2=parser.qfin2;
105
106 out1=parser.out1;
107 out2=parser.out2;
108 qfout1=parser.qfout1;
109 qfout2=parser.qfout2;
110
111 extin=parser.extin;
112 extout=parser.extout;
113 }
114
115 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
116 in2=in1.replace("#", "2");
117 in1=in1.replace("#", "1");
118 }
119 if(out1!=null && out2==null && out1.indexOf('#')>-1){
120 out2=out1.replace("#", "2");
121 out1=out1.replace("#", "1");
122 }
123 if(in2!=null){
124 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
125 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
126 }
127
128 assert(FastaReadInputStream.settingsOK());
129
130 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
131 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
132 ByteFile.FORCE_MODE_BF2=true;
133 }
134
135 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
136
137 if(!setInterleaved){
138 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
139 if(in2!=null){ //If there are 2 input streams.
140 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
141 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
142 }else{ //There is one input stream.
143 if(out2!=null){
144 FASTQ.FORCE_INTERLEAVED=true;
145 FASTQ.TEST_INTERLEAVED=false;
146 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
147 }
148 }
149 }
150
151 if(out1!=null && out1.equalsIgnoreCase("null")){out1=null;}
152 if(out2!=null && out2.equalsIgnoreCase("null")){out2=null;}
153
154 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
155 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
156 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
157 }
158
159 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, false);
160 ffout2=FileFormat.testOutput(out2, FileFormat.FASTQ, extout, true, overwrite, append, false);
161
162 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
163 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
164 }
165
166 /** Must be overridden if variables are defined at bottom of class file. */
167 protected abstract void setDefaults();
168
169 protected void reparse(String[] args){
170 for(int i=0; i<args.length; i++){
171 String arg=args[i];
172 String[] split=arg.split("=");
173 String a=split[0].toLowerCase();
174 String b=split.length>1 ? split[1] : null;
175
176 if(parseArgument(arg, a, b)){
177 // do nothing
178 }
179 }
180 }
181
182 /**
183 * Must be overridden; this body is just for example.
184 * Parses an argument from the command line.
185 * Assumed to be in "key=value" form, but this is not required.
186 * @param arg The full original argument.
187 * @param a Left hand side, to lower case.
188 * @param b Right hand side, unaltered.
189 * @return true if a matched some keyword.
190 */
191 public abstract boolean parseArgument(String arg, String a, String b);
192
193 // //Example
194 // @Override
195 // public boolean parseArgument(String arg, String a, String b){
196 // if(a.equals("keepunmapped") | a.equals("ku")){
197 // keepUnmapped=Parse.parseBoolean(b);
198 // return true;
199 // }else if(a.equals("ignorepairorder") | a.equals("ipo")){
200 // usePairOrder=!Parse.parseBoolean(b);
201 // return true;
202 // }else if(a.equals("sorted")){
203 // sorted=Parse.parseBoolean(b);
204 // return true;
205 // }
206 // return false;
207 // }
208
209 /**
210 * And example of how to override parseArgument.
211 */
212 private boolean parseArgument_EXAMPLE(String arg, String a, String b){
213 if(true){throw new RuntimeException("parseArgument() must be overridden.");}
214
215 //These are dummy values for demonstration purposes.
216 //In real code they should be class fields.
217 int value1;
218 boolean value2;
219 String value3;
220
221 if(a.equals("key1")){
222 value1=Parse.parseIntKMG(b);
223 //do anything else necessary here
224 return true;
225 }else if(a.equals("key2")){
226 value2=Parse.parseBoolean(b);
227 //do anything else necessary here
228 return true;
229 }else if(a.equals("key3")){
230 value3=b;
231 //do anything else necessary here
232 return true;
233 }
234
235 //There was no match to the argument
236 return false;
237 }
238
239
240 /*--------------------------------------------------------------*/
241 /*---------------- Outer Methods ----------------*/
242 /*--------------------------------------------------------------*/
243
244 public void process(){process(new Timer());}
245
246 /** Create read streams and process all data */
247 protected void process(Timer t){
248
249 //Start the read streams
250 startup();
251
252 readsProcessed=0;
253 basesProcessed=0;
254
255 //Process the read streams
256 processInner(cris_primary, ros_primary);
257
258 //Close the read streams
259 shutdown(cris_primary, ros_primary);
260
261 showStats(t);
262 }
263
264 /** Create read streams */
265 protected void startup(){
266 startupSubclass();
267
268 if(!Tools.testForDuplicateFiles(true, in1, in2, qfin1, qfin2, out1, out2, qfout1, qfout2)){
269 assert(false) : "Duplicate files.";
270 }
271
272 final ConcurrentReadInputStream cris;
273 final ConcurrentReadOutputStream ros;
274
275 {
276 cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
277 cris.start();
278 if(verbose){outstream.println("Started cris");}
279 }
280 final boolean paired=cris.paired();
281 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
282
283 if(out1!=null){
284 final int buff=4;
285
286 if(cris.paired() && out2==null && (in1==null || !in1.contains(".sam"))){
287 outstream.println("Writing interleaved.");
288 }
289
290 ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, useSharedHeader());
291 ros.start();
292 }else{ros=null;}
293
294 readsProcessed=0;
295 basesProcessed=0;
296 cris_primary=cris;
297 ros_primary=ros;
298 }
299
300 /** Called before startup().
301 * Implement if necessary */
302 protected abstract void startupSubclass();
303
304 protected final void shutdown(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
305 shutdownSubclass();
306
307 final boolean paired=cris.paired();
308 if(verbose){outstream.println("Finished.");}
309
310 errorState|=ReadStats.writeAll();
311 errorState|=ReadWrite.closeStreams(cris, ros);
312 }
313
314 /** Called before shutdown().
315 * Implement if necessary */
316 protected abstract void shutdownSubclass();
317
318 protected void showStats(final Timer t){
319 t.stop();
320 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
321
322 showStatsSubclass(t, readsProcessed, basesProcessed);
323
324 if(errorState){
325 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
326 }
327 }
328
329 /** Called AFTER showStats().
330 * Implement if necessary */
331 protected abstract void showStatsSubclass(final Timer t, long readsIn, long basesIn);
332
333 /** Iterate through the reads.
334 * This may optionally be overridden. */
335 protected void processInner(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
336
337 readsProcessed=0;
338 basesProcessed=0;
339
340 {
341
342 ListNum<Read> ln=cris.nextList();
343 ArrayList<Read> reads=(ln!=null ? ln.list : null);
344
345 if(reads!=null && !reads.isEmpty()){
346 Read r=reads.get(0);
347 assert((ffin1==null || ffin1.samOrBam()) || (r.mate!=null)==cris.paired());
348 }
349
350 while(ln!=null && reads!=null && reads.size()>0){//ln!=null prevents a compiler potential null access warning
351 if(verbose){outstream.println("Fetched "+reads.size()+" reads.");}
352
353 for(int idx=0; idx<reads.size(); idx++){
354 final Read r1=reads.get(idx);
355 final Read r2=r1.mate;
356
357 final int initialLength1=r1.length();
358 final int initialLength2=(r1.mateLength());
359
360 {
361 readsProcessed++;
362 basesProcessed+=initialLength1;
363 }
364 if(r2!=null){
365 readsProcessed++;
366 basesProcessed+=initialLength2;
367 }
368
369 boolean keep=processReadPair(r1, r2);
370 if(!keep){reads.set(idx, null);}
371
372 }
373
374 if(ros!=null){ros.add(reads, ln.id);}
375
376 cris.returnList(ln);
377 if(verbose){outstream.println("Returned a list.");}
378 ln=cris.nextList();
379 reads=(ln!=null ? ln.list : null);
380 }
381 if(ln!=null){
382 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
383 }
384 }
385 }
386
387 /*--------------------------------------------------------------*/
388 /*---------------- Inner Methods ----------------*/
389 /*--------------------------------------------------------------*/
390
391 /**
392 * Process a single read pair. Must be overidden.
393 * @param r1 Read 1
394 * @param r2 Read 2 (may be null)
395 * @return True if the reads should be kept, false if they should be discarded.
396 */
397 protected abstract boolean processReadPair(final Read r1, final Read r2);
398
399 /** For sam format */
400 protected abstract boolean useSharedHeader();
401
402 /*--------------------------------------------------------------*/
403 /*---------------- Fields ----------------*/
404 /*--------------------------------------------------------------*/
405
406 protected String in1=null;
407 protected String in2=null;
408
409 protected String qfin1=null;
410 protected String qfin2=null;
411
412 protected String out1=null;
413 protected String out2=null;
414
415 protected String qfout1=null;
416 protected String qfout2=null;
417
418 protected String extin=null;
419 protected String extout=null;
420
421 /*--------------------------------------------------------------*/
422
423 private ConcurrentReadInputStream cris_primary;
424 private ConcurrentReadOutputStream ros_primary;
425
426 protected long readsProcessed=0;
427 protected long basesProcessed=0;
428
429 private long maxReads=-1;
430
431 /*--------------------------------------------------------------*/
432 /*---------------- Final Fields ----------------*/
433 /*--------------------------------------------------------------*/
434
435 protected final FileFormat ffin1;
436 protected final FileFormat ffin2;
437
438 protected FileFormat ffout1;
439 protected FileFormat ffout2;
440
441 /*--------------------------------------------------------------*/
442 /*---------------- Common Fields ----------------*/
443 /*--------------------------------------------------------------*/
444
445 protected PrintStream outstream=System.err;
446 public static boolean verbose=false;
447 public boolean errorState=false;
448 protected boolean overwrite=true;
449 protected boolean append=false;
450
451 }