Debian Codegraph @

current/template/A_SampleSamStreamer.java

raw symbols SCIP
1 package template;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.concurrent.locks.ReadWriteLock;
6 import java.util.concurrent.locks.ReentrantReadWriteLock;
7
8 import fileIO.ByteFile;
9 import fileIO.FileFormat;
10 import fileIO.ReadWrite;
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.FastaReadInputStream;
20 import stream.Read;
21 import stream.SamLine;
22 import stream.SamReadStreamer;
23 import stream.SamStreamer;
24 import structures.ListNum;
25 import tracker.ReadStats;
26 import var2.Realigner;
27 import var2.SamFilter;
28 import var2.ScafMap;
29
30 /**
31 * This class does nothing.
32 * It is designed to be easily modified into a program
33 * that processes reads in multiple threads, by
34 * filling in the processRead method.
35 *
36 * @author Brian Bushnell
37 * @date September 6, 2019
38 *
39 */
40 public class A_SampleSamStreamer implements Accumulator<A_SampleSamStreamer.ProcessThread> {
41
42 /*--------------------------------------------------------------*/
43 /*---------------- Initialization ----------------*/
44 /*--------------------------------------------------------------*/
45
46 /**
47 * Code entrance from the command line.
48 * @param args Command line arguments
49 */
50 public static void main(String[] args){
51 //Start a timer immediately upon code entrance.
52 Timer t=new Timer();
53
54 //Create an instance of this class
55 A_SampleSamStreamer x=new A_SampleSamStreamer(args);
56
57 //Run the object
58 x.process(t);
59
60 //Close the print stream if it was redirected
61 Shared.closeStream(x.outstream);
62 }
63
64 /**
65 * Constructor.
66 * @param args Command line arguments
67 */
68 public A_SampleSamStreamer(String[] args){
69
70 {//Preparse block for help, config files, and outstream
71 PreParser pp=new PreParser(args, getClass(), false);
72 args=pp.args;
73 outstream=pp.outstream;
74 }
75
76 //Set shared static variables prior to parsing
77 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
78 ReadWrite.setZipThreads(Shared.threads());
79
80 // samFilter.includeUnmapped=false;
81 // samFilter.includeSupplimentary=false;
82 // samFilter.includeDuplicate=false;
83 // samFilter.includeNonPrimary=false;
84 // samFilter.includeQfail=false;
85 // samFilter.minMapq=4;
86
87 {//Parse the arguments
88 final Parser parser=parse(args);
89
90 Parser.processQuality();
91
92 maxReads=parser.maxReads;
93 overwrite=ReadStats.overwrite=parser.overwrite;
94 append=ReadStats.append=parser.append;
95
96 in=parser.in1;
97 extin=parser.extin;
98
99 out=parser.out1;
100 extout=parser.extout;
101 }
102
103 {
104 // if("auto".equalsIgnoreCase(atomic)){Scaffold.setCA3A(Shared.threads()>8);}
105 // else{Scaffold.setCA3A(Parse.parseBoolean(atomic));}
106
107 if(ploidy<1){System.err.println("WARNING: ploidy not set; assuming ploidy=1."); ploidy=1;}
108 samFilter.setSamtoolsFilter();
109
110 streamerThreads=Tools.max(1, Tools.min(streamerThreads, Shared.threads()));
111 assert(streamerThreads>0) : streamerThreads;
112 }
113
114 validateParams();
115 fixExtensions(); //Add or remove .gz or .bz2 as needed
116 checkFileExistence(); //Ensure files can be read and written
117 checkStatics(); //Adjust file-related static fields as needed for this program
118
119 //Create output FileFormat objects
120 ffout=FileFormat.testOutput(out, FileFormat.SAM, extout, true, overwrite, append, ordered);
121 assert(false) : "TODO: Default output format might be fasta.";
122
123 //Create input FileFormat objects
124 ffin=FileFormat.testInput(in, FileFormat.SAM, extin, true, true);
125 ffref=FileFormat.testInput(ref, FileFormat.FASTA, null, true, true);
126 }
127
128 /*--------------------------------------------------------------*/
129 /*---------------- Initialization Helpers ----------------*/
130 /*--------------------------------------------------------------*/
131
132 /** Parse arguments from the command line */
133 private Parser parse(String[] args){
134
135 //Create a parser object
136 Parser parser=new Parser();
137
138 //Set any necessary Parser defaults here
139 //parser.foo=bar;
140
141 //Parse each argument
142 for(int i=0; i<args.length; i++){
143 String arg=args[i];
144
145 //Break arguments into their constituent parts, in the form of "a=b"
146 String[] split=arg.split("=");
147 String a=split[0].toLowerCase();
148 String b=split.length>1 ? split[1] : null;
149 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
150
151 if(a.equals("verbose")){
152 verbose=Parse.parseBoolean(b);
153 }else if(a.equals("ref")){
154 ref=b;
155 }else if(a.equals("ordered")){
156 ordered=Parse.parseBoolean(b);
157 }else if(a.equals("realign")){
158 realign=Parse.parseBoolean(b);
159 }else if(a.equals("ploidy")){
160 ploidy=Integer.parseInt(b);
161 }else if(a.equals("clearfilters")){
162 if(Parse.parseBoolean(b)){
163 samFilter.clear();
164 }
165 }else if(a.equals("parse_flag_goes_here")){
166 long fake_variable=Parse.parseKMG(b);
167 //Set a variable here
168 }else if(samFilter.parse(arg, a, b)){
169 //do nothing
170 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
171 //do nothing
172 }else{
173 outstream.println("Unknown parameter "+args[i]);
174 assert(false) : "Unknown parameter "+args[i];
175 }
176 }
177
178 return parser;
179 }
180
181 /** Add or remove .gz or .bz2 as needed */
182 private void fixExtensions(){
183 in=Tools.fixExtension(in);
184 ref=Tools.fixExtension(ref);
185 }
186
187 /** Ensure files can be read and written */
188 private void checkFileExistence(){
189
190 //Ensure there is an input file
191 if(in==null){throw new RuntimeException("Error - an input file is required.");}
192
193 //Ensure there is an input file
194 assert(false) : "TODO: Check.";
195 if(ref==null){throw new RuntimeException("Error - a reference file is required.");}
196
197 //Ensure output files can be written
198 if(!Tools.testOutputFiles(overwrite, append, false, out)){
199 outstream.println((out==null)+", "+out);
200 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out+"\n");
201 }
202
203 //Ensure input files can be read
204 if(!Tools.testInputFiles(false, true, in, ref)){
205 throw new RuntimeException("\nCan't read some input files.\n");
206 }
207
208 //Ensure that no file was specified multiple times
209 if(!Tools.testForDuplicateFiles(true, in, ref, out)){
210 throw new RuntimeException("\nSome file names were specified multiple times.\n");
211 }
212 }
213
214 /** Adjust file-related static fields as needed for this program */
215 private static void checkStatics(){
216 //Adjust the number of threads for input file reading
217 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
218 ByteFile.FORCE_MODE_BF2=true;
219 }
220
221 assert(FastaReadInputStream.settingsOK());
222 }
223
224 /** Ensure parameter ranges are within bounds and required parameters are set */
225 private boolean validateParams(){
226 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
227 assert(false) : "TODO";
228 return true;
229 }
230
231 /*--------------------------------------------------------------*/
232 /*---------------- Outer Methods ----------------*/
233 /*--------------------------------------------------------------*/
234
235 /** Create read streams and process all data */
236 void process(Timer t){
237
238 //Turn off read validation in the input threads to increase speed
239 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
240 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
241
242 //Create a read input stream
243 final SamStreamer ss=makeStreamer(ffin);
244
245 //Load reference, if desired (and if present);
246 loadScafMapFromReference();
247 // loadReferenceCustom();
248
249 //Optionally create a read output stream
250 final ConcurrentReadOutputStream ros=makeCros();
251
252 //Reset counters
253 readsProcessed=readsOut=0;
254 basesProcessed=basesOut=0;
255
256 //Process the reads in separate threads
257 spawnThreads(ss, 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.closeStream(ros);
265
266 //Reset read validation
267 Read.VALIDATE_IN_CONSTRUCTOR=vic;
268
269 //Report timing and results
270 t.stop();
271 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
272 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
273
274 //Throw an exception of there was an error in a thread
275 if(errorState){
276 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
277 }
278 }
279
280 private void loadScafMapFromReference(){
281 if(loadedRef){return;}
282 assert(ref!=null);
283 scafMap=ScafMap.loadReference(ref, scafMap, samFilter, true);
284 if(realign){Realigner.map=scafMap;}
285 loadedRef=true;
286 }
287
288 private void loadReferenceCustom(){
289 ConcurrentReadInputStream cris=makeRefCris();
290 for(ListNum<Read> ln=cris.nextList(); ln!=null && ln.size()>0; ln=cris.nextList()) {
291 //Do something
292 assert(false) : "TODO";
293 }
294 }
295
296 private ConcurrentReadInputStream makeRefCris(){
297 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffref, null);
298 cris.start(); //Start the stream
299 if(verbose){outstream.println("Started cris");}
300 boolean paired=cris.paired();
301 assert(!paired) : "References should not be paired.";
302 return cris;
303 }
304
305 private SamStreamer makeStreamer(FileFormat ff){
306 if(ff==null){return null;}
307 SamStreamer ss=new SamReadStreamer(ff, streamerThreads, true, maxReads);
308 ss.start(); //Start the stream
309 if(verbose){outstream.println("Started Streamer");}
310 return ss;
311 }
312
313 private ConcurrentReadOutputStream makeCros(){
314 if(ffout==null){return null;}
315
316 //Select output buffer size based on whether it needs to be ordered
317 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
318
319 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout, null, buff, null, false);
320 ros.start(); //Start the stream
321 return ros;
322 }
323
324 /*--------------------------------------------------------------*/
325 /*---------------- Thread Management ----------------*/
326 /*--------------------------------------------------------------*/
327
328 /** Spawn process threads */
329 private void spawnThreads(final SamStreamer ss, final ConcurrentReadOutputStream ros){
330
331 //Do anything necessary prior to processing
332
333 //Determine how many threads may be used
334 final int threads=Shared.threads();
335
336 //Fill a list with ProcessThreads
337 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
338 for(int i=0; i<threads; i++){
339 alpt.add(new ProcessThread(ss, ros, i));
340 }
341
342 //Start the threads
343 for(ProcessThread pt : alpt){
344 pt.start();
345 }
346
347 //Wait for threads to finish
348 boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
349 errorState&=!success;
350
351 //Do anything necessary after processing
352
353 }
354
355 @Override
356 public final void accumulate(ProcessThread pt){
357 readsProcessed+=pt.readsProcessedT;
358 basesProcessed+=pt.basesProcessedT;
359 readsOut+=pt.readsOutT;
360 basesOut+=pt.basesOutT;
361 errorState|=(!pt.success);
362 }
363
364 @Override
365 public final boolean success(){return !errorState;}
366
367 /*--------------------------------------------------------------*/
368 /*---------------- Inner Methods ----------------*/
369 /*--------------------------------------------------------------*/
370
371 /*--------------------------------------------------------------*/
372 /*---------------- Inner Classes ----------------*/
373 /*--------------------------------------------------------------*/
374
375 /** This class is static to prevent accidental writing to shared variables.
376 * It is safe to remove the static modifier. */
377 class ProcessThread extends Thread {
378
379 //Constructor
380 ProcessThread(final SamStreamer ss_, final ConcurrentReadOutputStream ros_, final int tid_){
381 ss=ss_;
382 ros=ros_;
383 tid=tid_;
384 realigner=(realign ? new Realigner() : null);
385 }
386
387 //Called by start()
388 @Override
389 public void run(){
390 //Do anything necessary prior to processing
391
392 //Process the reads
393 processInner();
394
395 //Do anything necessary after processing
396
397 //Indicate successful exit status
398 success=true;
399 }
400
401 /** Iterate through the reads */
402 void processInner(){
403
404 //Grab and process all lists
405 for(ListNum<Read> ln=ss.nextReads(); ln!=null; ln=ss.nextReads()){
406 // if(verbose){outstream.println("Got list of size "+list.size());} //Disabled due to non-static access
407
408 processList(ln);
409 }
410
411 }
412
413 void processList(ListNum<Read> ln){
414
415 //Grab the actual read list from the ListNum
416 final ArrayList<Read> reads=ln.list;
417
418 //Loop through each read in the list
419 for(int idx=0; idx<reads.size(); idx++){
420 final Read r=reads.get(idx);
421
422 //Validate reads in worker threads
423 if(!r.validated()){r.validate(true);}
424
425 //Track the initial length for statistics
426 final int initialLength=r.length();
427
428 //Increment counters
429 readsProcessedT+=r.pairCount();
430 basesProcessedT+=initialLength;
431
432 {
433 //Reads are processed in this block.
434 boolean keep=processRead(r);
435
436 if(!keep){reads.set(idx, null);}
437 else{
438 readsOutT++;
439 basesOutT+=r.length();
440 }
441 }
442 }
443
444 //Output reads to the output stream
445 if(ros!=null){ros.add(reads, ln.id);}
446 }
447
448 /**
449 * Process a read or a read pair.
450 * @param r Read 1
451 * @param r2 Read 2 (may be null)
452 * @return True if the reads should be kept, false if they should be discarded.
453 */
454 boolean processRead(final Read r){
455 if(r.bases==null || r.length()<=1){return false;}
456 final SamLine sl=r.samline;
457 if(samFilter!=null && !samFilter.passesFilter(sl)){return false;}
458
459 // System.err.println("A: "+sl);
460
461 // final SamLine oldSL=new SamLine(sl);
462 // final Read oldRead=r.clone();
463
464 assert(false) : "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 SamStreamer ss;
483 /** Shared output stream */
484 private final ConcurrentReadOutputStream ros;
485 /** Thread ID */
486 final int tid;
487 /** For realigning reads */
488 final Realigner realigner;
489 }
490
491 /*--------------------------------------------------------------*/
492 /*---------------- Fields ----------------*/
493 /*--------------------------------------------------------------*/
494
495 /** Primary input file path */
496 private String in=null;
497 /** Secondary input file path */
498 private String ref=null;
499
500 /** Primary output file path */
501 private String out=null;
502
503 /** Override input file extension */
504 private String extin=null;
505 /** Override output file extension */
506 private String extout=null;
507
508 /*--------------------------------------------------------------*/
509
510 /** Number of reads processed */
511 protected long readsProcessed=0;
512 /** Number of bases processed */
513 protected long basesProcessed=0;
514
515 /** Number of reads retained */
516 protected long readsOut=0;
517 /** Number of bases retained */
518 protected long basesOut=0;
519
520 /** Quit after processing this many input reads; -1 means no limit */
521 private long maxReads=-1;
522
523 /*--------------------------------------------------------------*/
524
525 /** Threads dedicated to reading the sam file */
526 private int streamerThreads=SamStreamer.DEFAULT_THREADS;
527
528 private boolean loadedRef=false;
529
530 private boolean realign=false;
531
532 private int ploidy=1;
533
534 public ScafMap scafMap;
535 public final SamFilter samFilter=new SamFilter();
536
537 @Override
538 public final ReadWriteLock rwlock() {return rwlock;}
539 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
540
541 /*--------------------------------------------------------------*/
542 /*---------------- Final Fields ----------------*/
543 /*--------------------------------------------------------------*/
544
545 /** Primary input file */
546 private final FileFormat ffin;
547 /** Secondary input file */
548 private final FileFormat ffref;
549
550 /** Primary output file */
551 private final FileFormat ffout;
552
553 /*--------------------------------------------------------------*/
554 /*---------------- Common Fields ----------------*/
555 /*--------------------------------------------------------------*/
556
557 /** Print status messages to this output stream */
558 private PrintStream outstream=System.err;
559 /** Print verbose messages */
560 public static boolean verbose=false;
561 /** True if an error was encountered */
562 public boolean errorState=false;
563 /** Overwrite existing output files */
564 private boolean overwrite=true;
565 /** Append to existing output files */
566 private boolean append=false;
567 /** Reads are output in input order */
568 private boolean ordered=false;
569
570 }