Debian Codegraph @

current/prok/SplitRibo.java

raw symbols SCIP
1 package prok;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.Arrays;
6 import java.util.concurrent.locks.ReadWriteLock;
7 import java.util.concurrent.locks.ReentrantReadWriteLock;
8
9 import aligner.SingleStateAlignerFlat2;
10 import fileIO.ByteFile;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import shared.Parse;
14 import shared.Parser;
15 import shared.PreParser;
16 import shared.Shared;
17 import shared.Timer;
18 import shared.Tools;
19 import stream.ConcurrentReadInputStream;
20 import stream.ConcurrentReadOutputStream;
21 import stream.FastaReadInputStream;
22 import stream.Read;
23 import structures.ListNum;
24 import template.Accumulator;
25 import template.ThreadWaiter;
26 import tracker.ReadStats;
27
28 /**
29 * Splits a mix of ribosomal sequences (such as Silva) into different files per type (16S, 18S, etc).
30 *
31 * @author Brian Bushnell
32 * @date November 19, 2015
33 *
34 */
35 public class SplitRibo implements Accumulator<SplitRibo.ProcessThread> {
36
37 /*--------------------------------------------------------------*/
38 /*---------------- Initialization ----------------*/
39 /*--------------------------------------------------------------*/
40
41 /**
42 * Code entrance from the command line.
43 * @param args Command line arguments
44 */
45 public static void main(String[] args){
46 //Start a timer immediately upon code entrance.
47 Timer t=new Timer();
48
49 //Create an instance of this class
50 SplitRibo x=new SplitRibo(args);
51
52 //Run the object
53 x.process(t);
54
55 //Close the print stream if it was redirected
56 Shared.closeStream(x.outstream);
57 }
58
59 /**
60 * Constructor.
61 * @param args Command line arguments
62 */
63 public SplitRibo(String[] args){
64
65 {//Preparse block for help, config files, and outstream
66 PreParser pp=new PreParser(args, getClass(), false);
67 args=pp.args;
68 outstream=pp.outstream;
69 }
70
71 //Set shared static variables prior to parsing
72 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
73 ReadWrite.setZipThreads(Shared.threads());
74 Shared.capBufferLen(50);
75 ReadWrite.ZIPLEVEL=9;
76
77 {//Parse the arguments
78 final Parser parser=parse(args);
79 Parser.processQuality();
80
81 maxReads=parser.maxReads;
82 overwrite=ReadStats.overwrite=parser.overwrite;
83 append=ReadStats.append=parser.append;
84
85 in1=parser.in1;
86 qfin1=parser.qfin1;
87 extin=parser.extin;
88
89 outPattern=parser.out1;
90 extout=parser.extout;
91 }
92
93 validateParams();
94 fixExtensions(); //Add or remove .gz or .bz2 as needed
95 checkFileExistence(); //Ensure files can be read and written
96 checkStatics(); //Adjust file-related static fields as needed for this program
97
98 //Create input FileFormat objects
99 ffin1=FileFormat.testInput(in1, FileFormat.FASTQ, extin, true, true);
100
101 numTypes=sequenceTypes.length;
102 readsOut=new long[numTypes];
103 basesOut=new long[numTypes];
104 consensusSequences=loadConsensusSequenceFromFile();
105 }
106
107 /*--------------------------------------------------------------*/
108 /*---------------- Initialization Helpers ----------------*/
109 /*--------------------------------------------------------------*/
110
111 /** Parse arguments from the command line */
112 private Parser parse(String[] args){
113
114 //Create a parser object
115 Parser parser=new Parser();
116
117 //Set any necessary Parser defaults here
118 //parser.foo=bar;
119
120 //Parse each argument
121 for(int i=0; i<args.length; i++){
122 String arg=args[i];
123
124 //Break arguments into their constituent parts, in the form of "a=b"
125 String[] split=arg.split("=");
126 String a=split[0].toLowerCase();
127 String b=split.length>1 ? split[1] : null;
128 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
129
130 if(a.equals("verbose")){
131 verbose=Parse.parseBoolean(b);
132 }else if(a.equals("ordered")){
133 ordered=Parse.parseBoolean(b);
134 }else if(a.equalsIgnoreCase("minid")){
135 minID=Float.parseFloat(b);
136 }else if(a.equalsIgnoreCase("minid2") || a.equalsIgnoreCase("refineid")){
137 refineID=Float.parseFloat(b);
138 }else if(a.equals("out") || a.equals("pattern") || a.equals("outpattern")){
139 parser.out1=b;
140 }else if(a.equals("type") || a.equals("types")){
141 parseTypes(b);
142 }else if(a.equals("parse_flag_goes_here")){
143 long fake_variable=Parse.parseKMG(b);
144 //Set a variable here
145 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
146 //do nothing
147 }else{
148 outstream.println("Unknown parameter "+args[i]);
149 assert(false) : "Unknown parameter "+args[i];
150 }
151 }
152
153 return parser;
154 }
155
156 private void parseTypes(String b){
157 sequenceTypes=null;
158 if(b==null){
159 assert(false) : "'types' flag requires a list of types, such as 'types=16S,18S'";
160 sequenceTypes=new String[] {"Other"};
161 }else{
162 String[] split=b.split(",");
163 sequenceTypes=new String[split.length+1];
164 sequenceTypes[0]="Other";
165 for(int i=0; i<split.length; i++){
166 String s=split[i].replace('s', 'S');
167 if(s.startsWith("its")){s=s.replaceFirst("its", "ITS");}
168 sequenceTypes[i+1]=s;
169 }
170 }
171 }
172
173 /** Add or remove .gz or .bz2 as needed */
174 private void fixExtensions(){
175 in1=Tools.fixExtension(in1);
176 qfin1=Tools.fixExtension(qfin1);
177 }
178
179 /** Ensure files can be read and written */
180 private void checkFileExistence(){
181
182 //Ensure input files can be read
183 if(!Tools.testInputFiles(false, true, in1)){
184 throw new RuntimeException("\nCan't read some input files.\n");
185 }
186
187 if(outPattern==null){return;}
188
189 if(!outPattern.contains("#")){
190 throw new RuntimeException("OutPattern must contain '#' symbol: "+outPattern);
191 }
192
193 for(String type : sequenceTypes) {
194 String out=outPattern.replaceFirst("#", type);
195
196 //Ensure output files can be written
197 if(!Tools.testOutputFiles(overwrite, append, false, out)){
198 outstream.println((outPattern==null)+", "+(out==null)+", "+outPattern+", "+out);
199 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out+"\n");
200 }
201
202 //Ensure that no file was specified multiple times
203 if(!Tools.testForDuplicateFiles(true, in1, out)){
204 throw new RuntimeException("\nSome file names were specified multiple times.\n");
205 }
206 }
207 }
208
209 /** Adjust file-related static fields as needed for this program */
210 private static void checkStatics(){
211 //Adjust the number of threads for input file reading
212 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
213 ByteFile.FORCE_MODE_BF2=true;
214 }
215
216 assert(FastaReadInputStream.settingsOK());
217 }
218
219 /** Ensure parameter ranges are within bounds and required parameters are set */
220 private boolean validateParams(){
221 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
222 if(in1==null){throw new RuntimeException("Error - at least one input file is required.");}
223 return true;
224 }
225
226 private final Read[][] loadConsensusSequenceFromFile(){
227 Read[][] seqs=new Read[numTypes][];
228 m16S_index=Tools.find("m16S", sequenceTypes);
229 m18S_index=Tools.find("m18S", sequenceTypes);
230 p16S_index=Tools.find("p16S", sequenceTypes);
231 boolean stripM16S=(m16S_index>=0);
232 boolean stripM18S=(m18S_index>=0);
233 boolean stripP16S=(p16S_index>=0);
234 for(int st=1; st<numTypes; st++){
235 String name=sequenceTypes[st];
236 boolean is16S=name.equalsIgnoreCase("16S");
237 boolean is18S=name.equalsIgnoreCase("18S");
238 seqs[st]=ProkObject.loadConsensusSequenceType(name, ((is16S && stripM16S) || (is18S && stripM18S)), (is16S && stripP16S));
239 }
240 return seqs;
241 }
242
243 /*--------------------------------------------------------------*/
244 /*---------------- Outer Methods ----------------*/
245 /*--------------------------------------------------------------*/
246
247 /** Create read streams and process all data */
248 void process(Timer t){
249
250 //Turn off read validation in the input threads to increase speed
251 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
252 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
253
254 //Create a read input stream
255 final ConcurrentReadInputStream cris=makeCris();
256
257 //Optionally create a read output stream
258 final ConcurrentReadOutputStream[] rosa=makeCrosArray();
259
260 //Reset counters
261 readsProcessed=0;
262 basesProcessed=0;
263 Arrays.fill(readsOut, 0);
264 Arrays.fill(basesOut, 0);
265
266 //Process the reads in separate threads
267 spawnThreads(cris, rosa);
268
269 if(verbose){outstream.println("Finished; closing streams.");}
270
271 //Write anything that was accumulated by ReadStats
272 errorState|=ReadStats.writeAll();
273 //assert(!errorState);
274 //Close the read streams
275 errorState|=ReadWrite.closeStreams(cris, rosa);
276 //assert(!errorState);
277
278 //Reset read validation
279 Read.VALIDATE_IN_CONSTRUCTOR=vic;
280
281 long readsOut2=shared.Vector.sum(readsOut)-readsOut[0];
282 long basesOut2=shared.Vector.sum(basesOut)-basesOut[0];
283
284 //Report timing and results
285 t.stop();
286 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
287 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut2, basesOut2, 8, true));
288
289 outstream.println();
290 outstream.println(Tools.string("Type", "Count", 8));
291 for(int type=0; type<numTypes; type++){
292 outstream.println(Tools.number(sequenceTypes[type], readsOut[type], 8));
293 }
294
295 //Throw an exception of there was an error in a thread
296 if(errorState){
297 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
298 }
299 }
300
301 private ConcurrentReadInputStream makeCris(){
302 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffin1, null, qfin1, null);
303 cris.start(); //Start the stream
304 if(verbose){outstream.println("Started cris");}
305 return cris;
306 }
307
308 private ConcurrentReadOutputStream[] makeCrosArray(){
309 ConcurrentReadOutputStream[] rosa=new ConcurrentReadOutputStream[numTypes];
310 for(int i=0; i<numTypes; i++){
311 String type=sequenceTypes[i];
312 final ConcurrentReadOutputStream ros=makeCros(type);
313 rosa[i]=ros;
314 }
315 return rosa;
316 }
317
318 private ConcurrentReadOutputStream makeCros(String type){
319 if(outPattern==null){return null;}
320
321 //Select output buffer size based on whether it needs to be ordered
322 final int buff=(ordered ? Tools.mid(2, 16, (Shared.threads()*2)/3) : 4);
323 final String fname=outPattern.replaceFirst("#", type);
324 FileFormat ff=FileFormat.testOutput(fname, FileFormat.FASTA, extout, true, overwrite, append, ordered);
325
326 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ff, null, buff, null, false);
327 ros.start(); //Start the stream
328 return ros;
329 }
330
331 /*--------------------------------------------------------------*/
332 /*---------------- Thread Management ----------------*/
333 /*--------------------------------------------------------------*/
334
335 /** Spawn process threads */
336 private void spawnThreads(final ConcurrentReadInputStream cris, final ConcurrentReadOutputStream[] rosa){
337
338 //Do anything necessary prior to processing
339
340 //Determine how many threads may be used
341 final int threads=Shared.threads();
342
343 //Fill a list with ProcessThreads
344 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
345 for(int i=0; i<threads; i++){
346 alpt.add(new ProcessThread(cris, rosa, i));
347 }
348
349 //Start the threads and wait for them to finish
350 boolean success=ThreadWaiter.startAndWait(alpt, this);
351 errorState&=!success;
352 //assert(!errorState);
353
354 //Do anything necessary after processing
355
356 }
357
358 @Override
359 public final void accumulate(ProcessThread pt){
360 readsProcessed+=pt.readsProcessedT;
361 basesProcessed+=pt.basesProcessedT;
362 Tools.add(readsOut, pt.readsOutT);
363 Tools.add(basesOut, pt.basesOutT);
364 errorState|=(!pt.success);
365 //assert(!errorState);
366 }
367
368 @Override
369 public final boolean success(){return !errorState;}
370
371 /*--------------------------------------------------------------*/
372 /*---------------- Inner Methods ----------------*/
373 /*--------------------------------------------------------------*/
374
375 /*--------------------------------------------------------------*/
376 /*---------------- Inner Classes ----------------*/
377 /*--------------------------------------------------------------*/
378
379 /** This class is static to prevent accidental writing to shared variables.
380 * It is safe to remove the static modifier. */
381 class ProcessThread extends Thread {
382
383 //Constructor
384 ProcessThread(final ConcurrentReadInputStream cris_, final ConcurrentReadOutputStream[] rosa_, final int tid_){
385 cris=cris_;
386 rosa=rosa_;
387 tid=tid_;
388 }
389
390 //Called by start()
391 @Override
392 public void run(){
393 //Do anything necessary prior to processing
394
395 //Process the reads
396 processInner();
397
398 //Do anything necessary after processing
399
400 //Indicate successful exit status
401 success=true;
402 }
403
404 /** Iterate through the reads */
405 void processInner(){
406
407 //Grab the first ListNum of reads
408 ListNum<Read> ln=cris.nextList();
409
410 //Check to ensure pairing is as expected
411 if(ln!=null && !ln.isEmpty()){
412 Read r=ln.get(0);
413 assert(r.mate==null);
414 }
415
416 //As long as there is a nonempty read list...
417 while(ln!=null && ln.size()>0){
418 // if(verbose){outstream.println("Fetched "+reads.size()+" reads.");} //Disabled due to non-static access
419
420 processList(ln);
421
422 //Notify the input stream that the list was used
423 cris.returnList(ln);
424 // if(verbose){outstream.println("Returned a list.");} //Disabled due to non-static access
425
426 //Fetch a new list
427 ln=cris.nextList();
428 }
429
430 //Notify the input stream that the final list was used
431 if(ln!=null){
432 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
433 }
434 }
435
436 void processList(ListNum<Read> ln){
437
438 //Grab the actual read list from the ListNum
439 final ArrayList<Read> reads=ln.list;
440
441 @SuppressWarnings("unchecked")
442 final ArrayList<Read>[] out=new ArrayList[numTypes];
443 for(int i=0; i<numTypes; i++){
444 ArrayList<Read> list=new ArrayList<Read>(50);
445 out[i]=list;
446 }
447
448 //Loop through each read in the list
449 for(int idx=0; idx<reads.size(); idx++){
450 final Read r1=reads.get(idx);
451
452 //Validate reads in worker threads
453 if(!r1.validated()){r1.validate(true);}
454
455 //Track the initial length for statistics
456 final int initialLength1=r1.length();
457 final int initialLength2=r1.mateLength();
458
459 //Increment counters
460 readsProcessedT+=r1.pairCount();
461 basesProcessedT+=initialLength1+initialLength2;
462
463 {
464 //Reads are processed in this block.
465 final int type=processRead(r1);
466 readsOutT[type]+=r1.pairCount();
467 basesOutT[type]+=r1.pairLength();
468 out[type].add(r1);
469 }
470 }
471
472 //Output reads to the output stream
473 if(rosa!=null){
474 for(int type=0; type<numTypes; type++){
475 rosa[type].add(out[type], ln.id);
476 }
477 }
478 }
479
480 /**
481 * Process a read.
482 * @param r1 Read 1
483 * @return The best-matching type, or 0 for no matches.
484 */
485 private int processRead(final Read r){
486 int bestType=0;
487 float bestID=-1;
488 for(int type=1; type<numTypes; type++){//Align to only the overall consensus
489 Read[] refs=consensusSequences[type];
490 float id=align(r, refs, 0, 1);
491 if(id>bestID && id>=minID){
492 bestType=type;
493 bestID=id;
494 }
495 }
496 if(bestType<1 || bestID<refineID || bestType==p16S_index){//If nothing met minID, or if it matched chloro, align to clade-specific consensuses
497 for(int type=1; type<numTypes; type++){
498 Read[] refs=consensusSequences[type];
499 float id=align(r, refs, 1, refs.length);
500 if(id>bestID && id>=minID){
501 bestType=type;
502 bestID=id;
503 }
504 }
505 }
506 r.obj=bestID;//If desired... in actuality, more info might be useful, like alignment length
507 return bestID<minID ? 0 : bestType;
508 }
509
510 private float align(Read r, Read[] refs, int minRef, int maxRef){
511 float bestID=-1;
512 if(refs!=null){
513 for(int i=minRef; i<maxRef; i++){
514 Read ref=refs[i];
515 float id=align(r.bases, ref.bases);
516 bestID=Tools.max(id, bestID);
517 }
518 }
519 return bestID;
520 }
521
522 private float align(byte[] query, byte[] ref){
523 int a=0, b=ref.length-1;
524 int[] max=ssa.fillUnlimited(query, ref, a, b, -9999);
525 if(max==null){return 0;}
526
527 final int rows=max[0];
528 final int maxCol=max[1];
529 final int maxState=max[2];
530 final float id=ssa.tracebackIdentity(query, ref, a, b, rows, maxCol, maxState, null);
531 return id;
532 }
533
534 SingleStateAlignerFlat2 ssa=new SingleStateAlignerFlat2();
535
536 /** Number of reads processed by this thread */
537 protected long readsProcessedT=0;
538 /** Number of bases processed by this thread */
539 protected long basesProcessedT=0;
540
541 /** Number of reads retained by this thread */
542 protected long[] readsOutT=new long[numTypes];
543 /** Number of bases retained by this thread */
544 protected long[] basesOutT=new long[numTypes];
545
546 /** True only if this thread has completed successfully */
547 boolean success=false;
548
549 /** Shared input stream */
550 private final ConcurrentReadInputStream cris;
551 /** Shared output stream */
552 private final ConcurrentReadOutputStream[] rosa;
553 /** Thread ID */
554 final int tid;
555 }
556
557 /*--------------------------------------------------------------*/
558 /*---------------- Fields ----------------*/
559 /*--------------------------------------------------------------*/
560
561 /** Primary input file path */
562 private String in1=null;
563
564 private String qfin1=null;
565
566 /** Primary output file path */
567 private String outPattern=null;
568
569 /** Override input file extension */
570 private String extin=null;
571 /** Override output file extension */
572 private String extout=null;
573
574 float minID=0.59f; //This could be a per-type value
575 float refineID=0.70f; //Refine alignment if best is less than this
576
577 private int m16S_index=-2;
578 private int m18S_index=-2;
579 private int p16S_index=-2;
580
581 /*--------------------------------------------------------------*/
582
583 /** Number of reads processed */
584 protected long readsProcessed=0;
585 /** Number of bases processed */
586 protected long basesProcessed=0;
587
588 /** Quit after processing this many input reads; -1 means no limit */
589 private long maxReads=-1;
590
591 private String[] sequenceTypes=new String[] {"Other", "16S", "18S", "23S", "5S", "m16S", "m18S", "p16S"};
592 private final int numTypes;//=sequenceTypes.length;
593 final Read[][] consensusSequences;
594
595 /** Number of reads retained */
596 final long[] readsOut;
597 /** Number of bases retained */
598 final long[] basesOut;
599
600 /*--------------------------------------------------------------*/
601 /*---------------- Final Fields ----------------*/
602 /*--------------------------------------------------------------*/
603
604 /** Primary input file */
605 private final FileFormat ffin1;
606
607 @Override
608 public final ReadWriteLock rwlock() {return rwlock;}
609 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
610
611 /*--------------------------------------------------------------*/
612 /*---------------- Static Fields ----------------*/
613 /*--------------------------------------------------------------*/
614
615 /*--------------------------------------------------------------*/
616 /*---------------- Common Fields ----------------*/
617 /*--------------------------------------------------------------*/
618
619 /** Print status messages to this output stream */
620 private PrintStream outstream=System.err;
621 /** Print verbose messages */
622 public static boolean verbose=false;
623 /** True if an error was encountered */
624 public boolean errorState=false;
625 /** Overwrite existing output files */
626 private boolean overwrite=true;
627 /** Append to existing output files */
628 private boolean append=false;
629 /** Reads are output in input order */
630 private boolean ordered=true;
631
632 }