Debian Codegraph @

current/prok/RiboMaker.java

raw symbols SCIP
1 package prok;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.PriorityQueue;
7 import java.util.concurrent.locks.ReadWriteLock;
8 import java.util.concurrent.locks.ReentrantReadWriteLock;
9
10 import aligner.Alignment;
11 import dna.AminoAcid;
12 import fileIO.ByteFile;
13 import fileIO.FileFormat;
14 import fileIO.ReadWrite;
15 import shared.Parse;
16 import shared.Parser;
17 import shared.PreParser;
18 import shared.Shared;
19 import shared.Timer;
20 import shared.Tools;
21 import stream.ConcurrentReadInputStream;
22 import stream.ConcurrentReadOutputStream;
23 import stream.FASTQ;
24 import stream.FastaReadInputStream;
25 import stream.Read;
26 import stream.ReadInputStream;
27 import structures.ListNum;
28 import structures.LongHashSet;
29 import template.Accumulator;
30 import template.ThreadWaiter;
31 import tracker.ReadStats;
32
33 /**
34 * Makes a consensus ribosomal sequence using raw reads as input.
35 *
36 * @author Brian Bushnell
37 * @date October 10, 2019
38 *
39 */
40 public class RiboMaker implements Accumulator<RiboMaker.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 assert(false) : "TODO";
52
53 //Start a timer immediately upon code entrance.
54 Timer t=new Timer();
55
56 //Create an instance of this class
57 RiboMaker x=new RiboMaker(args);
58
59 //Run the object
60 x.process(t);
61
62 //Close the print stream if it was redirected
63 Shared.closeStream(x.outstream);
64 }
65
66 /**
67 * Constructor.
68 * @param args Command line arguments
69 */
70 public RiboMaker(String[] args){
71
72 {//Preparse block for help, config files, and outstream
73 PreParser pp=new PreParser(args, getClass(), false);
74 args=pp.args;
75 outstream=pp.outstream;
76 }
77
78 //Set shared static variables prior to parsing
79 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
80 ReadWrite.setZipThreads(Shared.threads());
81
82 {//Parse the arguments
83 final Parser parser=parse(args);
84 Parser.processQuality();
85
86 maxReads=parser.maxReads;
87 overwrite=ReadStats.overwrite=parser.overwrite;
88 append=ReadStats.append=parser.append;
89 setInterleaved=parser.setInterleaved;
90
91 in1=parser.in1;
92 in2=parser.in2;
93 qfin1=parser.qfin1;
94 qfin2=parser.qfin2;
95 extin=parser.extin;
96
97 out1=parser.out1;
98 qfout1=parser.qfout1;
99 extout=parser.extout;
100 }
101
102 validateParams();
103 doPoundReplacement(); //Replace # with 1 and 2
104 adjustInterleaving(); //Make sure interleaving agrees with number of input and output files
105 fixExtensions(); //Add or remove .gz or .bz2 as needed
106 checkFileExistence(); //Ensure files can be read and written
107 checkStatics(); //Adjust file-related static fields as needed for this program
108
109 //Create output FileFormat objects
110 ffout1=FileFormat.testOutput(out1, FileFormat.FASTQ, extout, true, overwrite, append, ordered);
111
112 fffilter=FileFormat.testInput(filterFile, FileFormat.FASTA, null, true, true);
113 ffref=FileFormat.testInput(refFile, FileFormat.FASTA, null, true, true);
114
115 //Create input FileFormat objects
116 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
117 ffin2=FileFormat.testInput(in2, FileFormat.FASTQ, extin, true, true);
118
119 if(fffilter==null){
120 filter=null;
121 }else{
122 filter=loadFilter(fffilter, k);
123 }
124 loadRef();
125 }
126
127 /*--------------------------------------------------------------*/
128 /*---------------- Initialization Helpers ----------------*/
129 /*--------------------------------------------------------------*/
130
131 /** Parse arguments from the command line */
132 private Parser parse(String[] args){
133
134 //Create a parser object
135 Parser parser=new Parser();
136
137 //Set any necessary Parser defaults here
138 //parser.foo=bar;
139
140 //Parse each argument
141 for(int i=0; i<args.length; i++){
142 String arg=args[i];
143
144 //Break arguments into their constituent parts, in the form of "a=b"
145 String[] split=arg.split("=");
146 String a=split[0].toLowerCase();
147 String b=split.length>1 ? split[1] : null;
148 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
149
150 if(a.equals("verbose")){
151 verbose=Parse.parseBoolean(b);
152 }else if(a.equals("ordered")){
153 ordered=Parse.parseBoolean(b);
154 }else if(a.equals("filter")){
155 filterFile=b;
156 }else if(a.equals("ref")){
157 refFile=b;
158 }else if(a.equals("parse_flag_goes_here")){
159 long fake_variable=Parse.parseKMG(b);
160 //Set a variable here
161 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
162 //do nothing
163 }else{
164 outstream.println("Unknown parameter "+args[i]);
165 assert(false) : "Unknown parameter "+args[i];
166 }
167 }
168
169 return parser;
170 }
171
172 /** Replace # with 1 and 2 in headers */
173 private void doPoundReplacement(){
174 //Do input file # replacement
175 if(in1!=null && in2==null && in1.indexOf('#')>-1 && !new File(in1).exists()){
176 in2=in1.replace("#", "2");
177 in1=in1.replace("#", "1");
178 }
179
180 //Ensure there is an input file
181 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
182 }
183
184 /** Add or remove .gz or .bz2 as needed */
185 private void fixExtensions(){
186 in1=Tools.fixExtension(in1);
187 in2=Tools.fixExtension(in2);
188 qfin1=Tools.fixExtension(qfin1);
189 qfin2=Tools.fixExtension(qfin2);
190 }
191
192 /** Ensure files can be read and written */
193 private void checkFileExistence(){
194 //Ensure output files can be written
195 if(!Tools.testOutputFiles(overwrite, append, false, out1)){
196 outstream.println((out1==null)+", "+out1);
197 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output files "+out1+"\n");
198 }
199
200 //Ensure input files can be read
201 if(!Tools.testInputFiles(false, true, in1, in2, filterFile, refFile)){
202 throw new RuntimeException("\nCan't read some input files.\n");
203 }
204
205 //Ensure that no file was specified multiple times
206 if(!Tools.testForDuplicateFiles(true, in1, in2, out1, filterFile, refFile)){
207 throw new RuntimeException("\nSome file names were specified multiple times.\n");
208 }
209
210 assert(refFile!=null);
211 }
212
213 /** Make sure interleaving agrees with number of input and output files */
214 private void adjustInterleaving(){
215 //Adjust interleaved detection based on the number of input files
216 if(in2!=null){
217 if(FASTQ.FORCE_INTERLEAVED){outstream.println("Reset INTERLEAVED to false because paired input files were specified.");}
218 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
219 }
220
221 //Adjust interleaved settings based on number of output files
222 if(!setInterleaved){
223 assert(in1!=null) : "\nin1="+in1+"\nin2="+in2+"\nout1="+out1+"\n";
224 if(in2!=null){ //If there are 2 input streams.
225 FASTQ.FORCE_INTERLEAVED=FASTQ.TEST_INTERLEAVED=false;
226 outstream.println("Set INTERLEAVED to "+FASTQ.FORCE_INTERLEAVED);
227 }
228 }
229 }
230
231 /** Adjust file-related static fields as needed for this program */
232 private static void checkStatics(){
233 //Adjust the number of threads for input file reading
234 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
235 ByteFile.FORCE_MODE_BF2=true;
236 }
237
238 assert(FastaReadInputStream.settingsOK());
239 }
240
241 /** Ensure parameter ranges are within bounds and required parameters are set */
242 private boolean validateParams(){
243 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
244 assert(false) : "TODO";
245 return true;
246 }
247
248 /*--------------------------------------------------------------*/
249 /*---------------- Outer Methods ----------------*/
250 /*--------------------------------------------------------------*/
251
252 /** Create read streams and process all data */
253 void process(Timer t){
254
255 //Turn off read validation in the input threads to increase speed
256 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
257 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
258
259 //Create a read input stream
260 final ConcurrentReadInputStream cris=makeCris();
261
262 //Optionally create a read output stream
263 final ConcurrentReadOutputStream ros=makeCros(cris.paired());
264
265 //Reset counters
266 readsProcessed=readsOut=0;
267 basesProcessed=basesOut=0;
268
269 //Process the reads in separate threads
270 spawnThreads(cris, ros);
271
272 if(verbose){outstream.println("Finished; closing streams.");}
273
274 //Write anything that was accumulated by ReadStats
275 errorState|=ReadStats.writeAll();
276 //Close the read streams
277 errorState|=ReadWrite.closeStreams(cris, ros);
278
279 //Reset read validation
280 Read.VALIDATE_IN_CONSTRUCTOR=vic;
281
282 //Report timing and results
283 t.stop();
284 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
285 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
286
287 //Throw an exception of there was an error in a thread
288 if(errorState){
289 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
290 }
291 }
292
293 private void loadRef(){
294 ArrayList<Read> reads=ReadInputStream.toReads(ffref, -1);
295 ref0=reads.get(0).bases;
296 ref=new byte[ref0.length+2*padding];
297 for(int i=0, j=-padding; i<ref.length; i++, j++){
298 byte b=(j>=0 && j<ref0.length ? ref0[j] : (byte)'N');
299 ref[i]=b;
300 }
301
302 queues=new PriorityQueue[1+ref.length/queueWidth];
303 for(int i=0; i<queues.length; i++){
304 queues[i]=new PriorityQueue<Alignment>(queueLen);
305 }
306 }
307
308 public static LongHashSet loadFilter(FileFormat ff, int k){
309 if(ff==null){return null;}
310 ArrayList<Read> reads=ReadInputStream.toReads(ff, -1);
311 if(reads==null || reads.size()==0){return null;}
312 LongHashSet set=new LongHashSet(4096);
313
314 final int shift=2*k;
315 final int shift2=shift-2;
316 final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
317 int len=0;
318
319 long kmer=0, rkmer=0;
320 for(Read r : reads){
321 final byte[] bases=r.bases;
322 for(byte b : bases) {
323 long x=AminoAcid.baseToNumber[b];
324 long x2=AminoAcid.baseToComplementNumber[b];
325 kmer=((kmer<<2)|x)&mask;
326 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
327
328 if(x>=0){
329 len++;
330 if(len>=k){
331 set.add(Tools.max(kmer, rkmer));
332 }
333 }else{
334 len=0;
335 kmer=rkmer=0;
336 }
337 }
338 }
339 return set;
340 }
341
342 public static boolean passesFilter(Read r, int k, LongHashSet set){
343 if(r==null) {return false;}
344 if(set==null){return true;}
345
346 final int shift=2*k;
347 final int shift2=shift-2;
348 final long mask=(shift>63 ? -1L : ~((-1L)<<shift));
349 int len=0;
350 long kmer=0, rkmer=0;
351
352 final byte[] bases=r.bases;
353 for(byte b : bases) {
354 long x=AminoAcid.baseToNumber[b];
355 long x2=AminoAcid.baseToComplementNumber[b];
356 kmer=((kmer<<2)|x)&mask;
357 rkmer=((rkmer>>>2)|(x2<<shift2))&mask;
358
359 if(x>=0){
360 len++;
361 if(len>=k){
362 long key=Tools.max(kmer, rkmer);
363 if(set.contains(key)){return true;}
364 }
365 }else{
366 len=0;
367 kmer=rkmer=0;
368 }
369 }
370 return false;
371 }
372
373 private ConcurrentReadInputStream makeCris(){
374 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, ffin2, qfin1, qfin2);
375 cris.start(); //Start the stream
376 if(verbose){outstream.println("Started cris");}
377 boolean paired=cris.paired();
378 if(!ffin1.samOrBam()){outstream.println("Input is being processed as "+(paired ? "paired" : "unpaired"));}
379 return cris;
380 }
381
382 private ConcurrentReadOutputStream makeCros(boolean pairedInput){
383 if(ffout1==null){return null;}
384
385 //Select output buffer size based on whether it needs to be ordered
386 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
387
388 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout1, null, qfout1, null, buff, null, false);
389 ros.start(); //Start the stream
390 return ros;
391 }
392
393 /*--------------------------------------------------------------*/
394 /*---------------- Thread Management ----------------*/
395 /*--------------------------------------------------------------*/
396
397 /** Spawn process threads */
398 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream ros){
399
400 //Do anything necessary prior to processing
401
402 //Determine how many threads may be used
403 final int threads=Shared.threads();
404
405 //Fill a list with ProcessThreads
406 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
407 for(int i=0; i<threads; i++){
408 alpt.add(new ProcessThread(cris, i));
409 }
410
411 //Start the threads and wait for them to finish
412 boolean success=ThreadWaiter.startAndWait(alpt, this);
413 errorState&=!success;
414
415 //Do anything necessary after processing
416 assert(false) : "TODO: Make consensus and write it?";
417 }
418
419 @Override
420 public final void accumulate(ProcessThread pt){
421 readsProcessed+=pt.readsProcessedT;
422 basesProcessed+=pt.basesProcessedT;
423 readsOut+=pt.readsOutT;
424 basesOut+=pt.basesOutT;
425 errorState|=(!pt.success);
426
427 for(int i=0; i<queues.length; i++){
428 PriorityQueue<Alignment> q=queues[i];
429 PriorityQueue<Alignment> qt=pt.queuesT[i];
430 for(Alignment a : qt){
431 addToQueue(a, q);
432 }
433 }
434 }
435
436 @Override
437 public final boolean success(){return !errorState;}
438
439 /*--------------------------------------------------------------*/
440 /*---------------- Inner Methods ----------------*/
441 /*--------------------------------------------------------------*/
442
443 boolean addToQueue(Alignment best, PriorityQueue<Alignment>[] queues){
444 int start=best.start;
445 int qnum=start/queueWidth;
446 PriorityQueue<Alignment> queue=queues[qnum];
447 return addToQueue(best, queue);
448 }
449
450 boolean addToQueue(Alignment best, PriorityQueue<Alignment> queue){
451 if(queue.size()<queueLen){queue.add(best);}
452 else{
453 Alignment bottom=queue.peek();
454 if(bottom.compareTo(best)>=0){return false;}
455 queue.poll();
456 queue.add(best);
457 }
458 return true;
459 }
460
461 /*--------------------------------------------------------------*/
462 /*---------------- Inner Classes ----------------*/
463 /*--------------------------------------------------------------*/
464
465 /** This class is static to prevent accidental writing to shared variables.
466 * It is safe to remove the static modifier. */
467 class ProcessThread extends Thread {
468
469 //Constructor
470 ProcessThread(final ConcurrentReadInputStream cris_, final int tid_){
471 cris=cris_;
472 tid=tid_;
473
474 queuesT=new PriorityQueue[1+ref.length/queueWidth];
475 for(int i=0; i<queuesT.length; i++){
476 queuesT[i]=new PriorityQueue<Alignment>(queueLen);
477 }
478 }
479
480 //Called by start()
481 @Override
482 public void run(){
483 //Do anything necessary prior to processing
484
485 //Process the reads
486 processInner();
487
488 //Do anything necessary after processing
489
490 //Indicate successful exit status
491 success=true;
492 }
493
494 /** Iterate through the reads */
495 void processInner(){
496
497 //Grab the first ListNum of reads
498 ListNum<Read> ln=cris.nextList();
499
500 //Check to ensure pairing is as expected
501 if(ln!=null && !ln.isEmpty()){
502 Read r=ln.get(0);
503 // assert(ffin1.samOrBam() || (r.mate!=null)==cris.paired()); //Disabled due to non-static access
504 }
505
506 //As long as there is a nonempty read list...
507 while(ln!=null && ln.size()>0){
508 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
509
510 processList(ln);
511
512 //Notify the input stream that the list was used
513 cris.returnList(ln);
514 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
515
516 //Fetch a new list
517 ln=cris.nextList();
518 }
519
520 //Notify the input stream that the final list was used
521 if(ln!=null){
522 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
523 }
524 }
525
526 void processList(ListNum<Read> ln){
527
528 //Grab the actual read list from the ListNum
529 final ArrayList<Read> reads=ln.list;
530
531 //Loop through each read in the list
532 for(int idx=0; idx<reads.size(); idx++){
533 final Read r1=reads.get(idx);
534 final Read r2=r1.mate;
535
536 //Validate reads in worker threads
537 if(!r1.validated()){r1.validate(true);}
538 if(r2!=null && !r2.validated()){r2.validate(true);}
539
540 //Track the initial length for statistics
541 final int initialLength1=r1.length();
542 final int initialLength2=r1.mateLength();
543
544 //Increment counters
545 readsProcessedT+=r1.pairCount();
546 basesProcessedT+=initialLength1+initialLength2;
547
548 {
549 //Reads are processed in this block.
550 processReadPair(r1, r2);
551
552 // if(!keep){reads.set(idx, null);}
553 // else{
554 // readsOutT+=r1.pairCount();
555 // basesOutT+=r1.pairLength();
556 // }
557 }
558 }
559
560 //Output reads to the output stream
561 // if(ros!=null){ros.add(reads, ln.id);}
562 }
563
564 /**
565 * Process a read or a read pair.
566 * @param r1 Read 1
567 * @param r2 Read 2 (may be null)
568 * @return True if the reads should be kept, false if they should be discarded.
569 */
570 void processReadPair(final Read r1, final Read r2){
571 boolean pass=passesFilter(r1, k, filter) || passesFilter(r2, k, filter);
572 if(!pass){return;}
573 processRead(r1);
574 processRead(r2);
575 }
576
577 void processRead(final Read r){
578 Alignment plus=new Alignment(r);
579 plus.align(ref);
580
581 r.reverseComplement();
582 Alignment minus=new Alignment(r);
583 minus.align(ref);
584
585 Alignment best=null;
586 if(plus.id>=minus.id){
587 r.reverseComplement();
588 best=plus;
589 }else{
590 best=minus;
591 }
592 if(best.id<minID) {return;}
593
594 addToQueue(best, queuesT);
595 }
596
597 /** Number of reads processed by this thread */
598 protected long readsProcessedT=0;
599 /** Number of bases processed by this thread */
600 protected long basesProcessedT=0;
601
602 /** Number of reads retained by this thread */
603 protected long readsOutT=0;
604 /** Number of bases retained by this thread */
605 protected long basesOutT=0;
606
607 /** True only if this thread has completed successfully */
608 boolean success=false;
609
610
611 private PriorityQueue<Alignment>[] queuesT;
612
613 /** Shared input stream */
614 private final ConcurrentReadInputStream cris;
615 /** Thread ID */
616 final int tid;
617 }
618
619 /*--------------------------------------------------------------*/
620 /*---------------- Fields ----------------*/
621 /*--------------------------------------------------------------*/
622
623 /** Primary input file path */
624 private String in1=null;
625 /** Secondary input file path */
626 private String in2=null;
627
628 private String qfin1=null;
629 private String qfin2=null;
630
631 /** Primary output file path */
632 private String out1=null;
633
634 private String qfout1=null;
635
636 private String filterFile;
637 private String refFile;
638
639 /** Override input file extension */
640 private String extin=null;
641 /** Override output file extension */
642 private String extout=null;
643
644 /** Whether interleaved was explicitly set. */
645 private boolean setInterleaved=false;
646
647 /** Original ref */
648 private byte[] ref0;
649 /** Padded ref */
650 private byte[] ref;
651
652 private int padding=100;
653 private int queueLen=20;
654 private int queueWidth=20;
655 private float minID=0.4f;
656
657 private PriorityQueue<Alignment>[] queues;
658
659 /*--------------------------------------------------------------*/
660
661 /** Number of reads processed */
662 protected long readsProcessed=0;
663 /** Number of bases processed */
664 protected long basesProcessed=0;
665
666 /** Number of reads retained */
667 protected long readsOut=0;
668 /** Number of bases retained */
669 protected long basesOut=0;
670
671 /** Quit after processing this many input reads; -1 means no limit */
672 private long maxReads=-1;
673
674 /*--------------------------------------------------------------*/
675 /*---------------- Final Fields ----------------*/
676 /*--------------------------------------------------------------*/
677
678 /** Primary input file */
679 private final FileFormat ffin1;
680 /** Secondary input file */
681 private final FileFormat ffin2;
682 /** Filter input file */
683 private final FileFormat fffilter;
684 /** Ref input file */
685 private final FileFormat ffref;
686
687 /** Primary output file */
688 private final FileFormat ffout1;
689
690 private final LongHashSet filter;
691 private final int k=31;
692
693 @Override
694 public final ReadWriteLock rwlock() {return rwlock;}
695 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
696
697
698 /*--------------------------------------------------------------*/
699 /*---------------- Common Fields ----------------*/
700 /*--------------------------------------------------------------*/
701
702 /** Print status messages to this output stream */
703 private PrintStream outstream=System.err;
704 /** Print verbose messages */
705 public static boolean verbose=false;
706 /** True if an error was encountered */
707 public boolean errorState=false;
708 /** Overwrite existing output files */
709 private boolean overwrite=true;
710 /** Append to existing output files */
711 private boolean append=false;
712 /** Reads are output in input order */
713 private boolean ordered=false;
714
715 }