Debian Codegraph @

current/template/A_SampleMT.java

raw symbols SCIP
1 package template;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.concurrent.locks.ReadWriteLock;
7 import java.util.concurrent.locks.ReentrantReadWriteLock;
8
9 import fileIO.ByteFile;
10 import fileIO.FileFormat;
11 import fileIO.ReadWrite;
12 import shared.Parse;
13 import shared.Parser;
14 import shared.PreParser;
15 import shared.Shared;
16 import shared.Timer;
17 import shared.Tools;
18 import stream.ConcurrentReadInputStream;
19 import stream.ConcurrentReadOutputStream;
20 import stream.FASTQ;
21 import stream.FastaReadInputStream;
22 import stream.Read;
23 import structures.ListNum;
24 import tracker.ReadStats;
25
26 /**
27 * This class does nothing.
28 * It is designed to be easily modified into a program
29 * that processes reads in multiple threads, by
30 * filling in the processReadPair method.
31 *
32 * @author Brian Bushnell
33 * @date November 19, 2015
34 *
35 */
36 public class A_SampleMT implements Accumulator<A_SampleMT.ProcessThread> {
37
38 /*--------------------------------------------------------------*/
39 /*---------------- Initialization ----------------*/
40 /*--------------------------------------------------------------*/
41
42 /**
43 * Code entrance from the command line.
44 * @param args Command line arguments
45 */
46 public static void main(String[] args){
47 //Start a timer immediately upon code entrance.
48 Timer t=new Timer();
49
50 //Create an instance of this class
51 A_SampleMT x=new A_SampleMT(args);
52
53 //Run the object
54 x.process(t);
55
56 //Close the print stream if it was redirected
57 Shared.closeStream(x.outstream);
58 }
59
60 /**
61 * Constructor.
62 * @param args Command line arguments
63 */
64 public A_SampleMT(String[] args){
65
66 {//Preparse block for help, config files, and outstream
67 PreParser pp=new PreParser(args, getClass(), false);
68 args=pp.args;
69 outstream=pp.outstream;
70 }
71
72 //Set shared static variables prior to parsing
73 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
74 ReadWrite.setZipThreads(Shared.threads());
75
76 {//Parse the arguments
77 final Parser parser=parse(args);
78 Parser.processQuality();
79
80 maxReads=parser.maxReads;
81 overwrite=ReadStats.overwrite=parser.overwrite;
82 append=ReadStats.append=parser.append;
83 setInterleaved=parser.setInterleaved;
84
85 in1=parser.in1;
86 in2=parser.in2;
87 qfin1=parser.qfin1;
88 qfin2=parser.qfin2;
89 extin=parser.extin;
90
91 out1=parser.out1;
92 out2=parser.out2;
93 qfout1=parser.qfout1;
94 qfout2=parser.qfout2;
95 extout=parser.extout;
96 }
97
98 validateParams();
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("ordered")){
140 ordered=Parse.parseBoolean(b);
141 }else if(a.equals("parse_flag_goes_here")){
142 long fake_variable=Parse.parseKMG(b);
143 //Set a variable here
144 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
145 //do nothing
146 }else{
147 outstream.println("Unknown parameter "+args[i]);
148 assert(false) : "Unknown parameter "+args[i];
149 }
150 }
151
152 return parser;
153 }
154
155 /** Replace # with 1 and 2 in headers */
156 private void doPoundReplacement(){
157 //Do input file # replacement
158 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
159 in2=in1.replace("#", "2");
160 in1=in1.replace("#", "1");
161 }
162
163 //Do output file # replacement
164 if(out1!=null && out2==null && out1.indexOf('#')>-1){
165 out2=out1.replace("#", "2");
166 out1=out1.replace("#", "1");
167 }
168
169 //Ensure there is an input file
170 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
171
172 //Ensure out2 is not set without out1
173 if(out1==null && out2!=null){throw new RuntimeException("Error - cannot define out2 without defining out1.");}
174 }
175
176 /** Add or remove .gz or .bz2 as needed */
177 private void fixExtensions(){
178 in1=Tools.fixExtension(in1);
179 in2=Tools.fixExtension(in2);
180 qfin1=Tools.fixExtension(qfin1);
181 qfin2=Tools.fixExtension(qfin2);
182 }
183
184 /** Ensure files can be read and written */
185 private void checkFileExistence(){
186 //Ensure output files can be written
187 if(!Tools.testOutputFiles(overwrite, append, false, out1, out2)){
188 outstream.println((out1==null)+", "+(out2==null)+", "+out1+", "+out2);
189 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+", "+out2+"\n");
190 }
191
192 //Ensure input files can be read
193 if(!Tools.testInputFiles(false, true, in1, in2)){
194 throw new RuntimeException("\nCan't read some input files.\n");
195 }
196
197 //Ensure that no file was specified multiple times
198 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, out2)){
199 throw new RuntimeException("\nSome file names were specified multiple times.\n");
200 }
201 }
202
203 /** Make sure interleaving agrees with number of input and output files */
204 private void adjustInterleaving(){
205 //Adjust interleaved detection based on the number of input files
206 if(in2!=null){
207 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
208 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
209 }
210
211 //Adjust interleaved settings based on number of output files
212 if(!setInterleaved){
213 assert(in1!=null && (out1!=null || out2==null)) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\nout2="+out2+"\n";
214 if(in2!=null){ //If there are 2 input streams.
215 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
216 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
217 }else{ //There is one input stream.
218 if(out2!=null){
219 FASTQ.FORCE_INTERLEAVED=true;
220 FASTQ.TEST_INTERLEAVED=false;
221 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
222 }
223 }
224 }
225 }
226
227 /** Adjust file-related static fields as needed for this program */
228 private static void checkStatics(){
229 //Adjust the number of threads for input file reading
230 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
231 ByteFile.FORCE_MODE_BF2=true;
232 }
233
234 assert(FastaReadInputStream.settingsOK());
235 }
236
237 /** Ensure parameter ranges are within bounds and required parameters are set */
238 private boolean validateParams(){
239 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
240 assert(false) : "TODO";
241 return true;
242 }
243
244 /*--------------------------------------------------------------*/
245 /*---------------- Outer Methods ----------------*/
246 /*--------------------------------------------------------------*/
247
248 /** Create read streams and process all data */
249 void process(Timer t){
250
251 //Turn off read validation in the input threads to increase speed
252 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
253 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
254
255 //Create a read input stream
256 final ConcurrentReadInputStream cris=makeCris();
257
258 //Optionally create a read output stream
259 final ConcurrentReadOutputStream ros=makeCros(cris.paired());
260
261 //Reset counters
262 readsProcessed=readsOut=0;
263 basesProcessed=basesOut=0;
264
265 //Process the reads in separate threads
266 spawnThreads(cris, ros);
267
268 if(verbose){outstream.println("Finished; closing streams.");}
269
270 //Write anything that was accumulated by ReadStats
271 errorState|=ReadStats.writeAll();
272 //Close the read streams
273 errorState|=ReadWrite.closeStreams(cris, ros);
274
275 //Reset read validation
276 Read.VALIDATE_IN_CONSTRUCTOR=vic;
277
278 //Report timing and results
279 t.stop();
280 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
281 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
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 private ConcurrentReadInputStream makeCris(){
290 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
291 cris.start(); //Start the stream
292 if(verbose){outstream.println("Started cris");}
293 boolean paired=cris.paired();
294 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
295 return cris;
296 }
297
298 private ConcurrentReadOutputStream makeCros(boolean pairedInput){
299 if(ffout1==null){return null;}
300
301 //Select output buffer size based on whether it needs to be ordered
302 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
303
304 //Notify user of output mode
305 if(pairedInput && out2==null && (in1!=null && !ffin1.samOrBam() && !ffout1.samOrBam())){
306 outstream.println("Writing interleaved.");
307 }
308
309 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout1, ffout2, qfout1, qfout2, buff, null, false);
310 ros.start(); //Start the stream
311 return ros;
312 }
313
314 /*--------------------------------------------------------------*/
315 /*---------------- Thread Management ----------------*/
316 /*--------------------------------------------------------------*/
317
318 /** Spawn process threads */
319 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
320
321 //Do anything necessary prior to processing
322
323 //Determine how many threads may be used
324 final int threads=Shared.threads();
325
326 //Fill a list with ProcessThreads
327 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
328 for(int i=0; i<threads; i++){
329 alpt.add(new ProcessThread(cris, ros, i));
330 }
331
332 //Start the threads and wait for them to finish
333 boolean success=ThreadWaiter.startAndWait(alpt, this);
334 errorState&=!success;
335
336 //Do anything necessary after processing
337
338 }
339
340 @Override
341 public final void accumulate(ProcessThread pt){
342 synchronized(pt) {
343 readsProcessed+=pt.readsProcessedT;
344 basesProcessed+=pt.basesProcessedT;
345 readsOut+=pt.readsOutT;
346 basesOut+=pt.basesOutT;
347 errorState|=(!pt.success);
348 }
349 }
350
351 @Override
352 public final boolean success(){return !errorState;}
353
354 /*--------------------------------------------------------------*/
355 /*---------------- Inner Methods ----------------*/
356 /*--------------------------------------------------------------*/
357
358 /*--------------------------------------------------------------*/
359 /*---------------- Inner Classes ----------------*/
360 /*--------------------------------------------------------------*/
361
362 /** This class is static to prevent accidental writing to shared variables.
363 * It is safe to remove the static modifier. */
364 static class ProcessThread extends Thread {
365
366 //Constructor
367 ProcessThread(final ConcurrentReadInputStream cris_, final ConcurrentReadOutputStream ros_, final int tid_){
368 cris=cris_;
369 ros=ros_;
370 tid=tid_;
371 }
372
373 //Called by start()
374 @Override
375 public void run(){
376 //Do anything necessary prior to processing
377
378 //Process the reads
379 processInner();
380
381 //Do anything necessary after processing
382
383 //Indicate successful exit status
384 success=true;
385 }
386
387 /** Iterate through the reads */
388 void processInner(){
389
390 //Grab the first ListNum of reads
391 ListNum<Read> ln=cris.nextList();
392
393 //Check to ensure pairing is as expected
394 if(ln!=null && !ln.isEmpty()){
395 Read r=ln.get(0);
396 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
397 }
398
399 //As long as there is a nonempty read list...
400 while(ln!=null && ln.size()>0){
401 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
402
403 processList(ln);
404
405 //Notify the input stream that the list was used
406 cris.returnList(ln);
407 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
408
409 //Fetch a new list
410 ln=cris.nextList();
411 }
412
413 //Notify the input stream that the final list was used
414 if(ln!=null){
415 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
416 }
417 }
418
419 void processList(ListNum<Read> ln){
420
421 //Grab the actual read list from the ListNum
422 final ArrayList<Read> reads=ln.list;
423
424 //Loop through each read in the list
425 for(int idx=0; idx<reads.size(); idx++){
426 final Read r1=reads.get(idx);
427 final Read r2=r1.mate;
428
429 //Validate reads in worker threads
430 if(!r1.validated()){r1.validate(true);}
431 if(r2!=null && !r2.validated()){r2.validate(true);}
432
433 //Track the initial length for statistics
434 final int initialLength1=r1.length();
435 final int initialLength2=r1.mateLength();
436
437 //Increment counters
438 readsProcessedT+=r1.pairCount();
439 basesProcessedT+=initialLength1+initialLength2;
440
441 {
442 //Reads are processed in this block.
443 boolean keep=processReadPair(r1, r2);
444
445 if(!keep){reads.set(idx, null);}
446 else{
447 readsOutT+=r1.pairCount();
448 basesOutT+=r1.pairLength();
449 }
450 }
451 }
452
453 //Output reads to the output stream
454 if(ros!=null){ros.add(reads, ln.id);}
455 }
456
457 /**
458 * Process a read or a read pair.
459 * @param r1 Read 1
460 * @param r2 Read 2 (may be null)
461 * @return True if the reads should be kept, false if they should be discarded.
462 */
463 boolean processReadPair(final Read r1, final Read r2){
464 throw new RuntimeException("TODO: Implement this method."); //TODO
465 // return true;
466 }
467
468 /** Number of reads processed by this thread */
469 protected long readsProcessedT=0;
470 /** Number of bases processed by this thread */
471 protected long basesProcessedT=0;
472
473 /** Number of reads retained by this thread */
474 protected long readsOutT=0;
475 /** Number of bases retained by this thread */
476 protected long basesOutT=0;
477
478 /** True only if this thread has completed successfully */
479 boolean success=false;
480
481 /** Shared input stream */
482 private final ConcurrentReadInputStream cris;
483 /** Shared output stream */
484 private final ConcurrentReadOutputStream ros;
485 /** Thread ID */
486 final int tid;
487 }
488
489 /*--------------------------------------------------------------*/
490 /*---------------- Fields ----------------*/
491 /*--------------------------------------------------------------*/
492
493 /** Primary input file path */
494 private String in1=null;
495 /** Secondary input file path */
496 private String in2=null;
497
498 private String qfin1=null;
499 private String qfin2=null;
500
501 /** Primary output file path */
502 private String out1=null;
503 /** Secondary output file path */
504 private String out2=null;
505
506 private String qfout1=null;
507 private String qfout2=null;
508
509 /** Override input file extension */
510 private String extin=null;
511 /** Override output file extension */
512 private String extout=null;
513
514 /** Whether interleaved was explicitly set. */
515 private boolean setInterleaved=false;
516
517 /*--------------------------------------------------------------*/
518
519 /** Number of reads processed */
520 protected long readsProcessed=0;
521 /** Number of bases processed */
522 protected long basesProcessed=0;
523
524 /** Number of reads retained */
525 protected long readsOut=0;
526 /** Number of bases retained */
527 protected long basesOut=0;
528
529 /** Quit after processing this many input reads; -1 means no limit */
530 private long maxReads=-1;
531
532 /*--------------------------------------------------------------*/
533 /*---------------- Final Fields ----------------*/
534 /*--------------------------------------------------------------*/
535
536 /** Primary input file */
537 private final FileFormat ffin1;
538 /** Secondary input file */
539 private final FileFormat ffin2;
540
541 /** Primary output file */
542 private final FileFormat ffout1;
543 /** Secondary output file */
544 private final FileFormat ffout2;
545
546 @Override
547 public final ReadWriteLock rwlock() {return rwlock;}
548 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
549
550 /*--------------------------------------------------------------*/
551 /*---------------- Common Fields ----------------*/
552 /*--------------------------------------------------------------*/
553
554 /** Print status messages to this output stream */
555 private PrintStream outstream=System.err;
556 /** Print verbose messages */
557 public static boolean verbose=false;
558 /** True if an error was encountered */
559 public boolean errorState=false;
560 /** Overwrite existing output files */
561 private boolean overwrite=true;
562 /** Append to existing output files */
563 private boolean append=false;
564 /** Reads are output in input order */
565 private boolean ordered=false;
566
567 }