Debian Codegraph @

current/bin/ContigRenamer.java

raw symbols SCIP
1 package bin;
2
3 import java.io.File;
4 import java.io.PrintStream;
5 import java.util.ArrayList;
6 import java.util.HashMap;
7 import java.util.concurrent.locks.ReadWriteLock;
8 import java.util.concurrent.locks.ReentrantReadWriteLock;
9
10 import fileIO.ByteFile;
11 import fileIO.FileFormat;
12 import fileIO.ReadWrite;
13 import shared.LineParser1;
14 import shared.LineParser4;
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.FastaReadInputStream;
24 import stream.Read;
25 import stream.SamLine;
26 import stream.SamLineStreamer;
27 import stream.SamReadInputStream;
28 import stream.SamStreamer;
29 import structures.ByteBuilder;
30 import structures.FloatList;
31 import structures.IntList;
32 import structures.IntLongHashMap;
33 import structures.ListNum;
34 import tax.TaxTree;
35 import template.Accumulator;
36 import template.ThreadWaiter;
37 import tracker.ReadStats;
38 import var2.SamFilter;
39
40 /**
41 * Renames contigs based on a sam file.
42 * Appends coverage (cov_#).
43 * Also appends taxid (taxid_#) if reads have taxids,
44 * and the contig does not already have a taxid.
45 *
46 * @author Brian Bushnell
47 * @date September 6, 2019
48 *
49 */
50 public class ContigRenamer implements Accumulator<ContigRenamer.ProcessThread> {
51
52 /*--------------------------------------------------------------*/
53 /*---------------- Initialization ----------------*/
54 /*--------------------------------------------------------------*/
55
56 /**
57 * Code entrance from the command line.
58 * @param args Command line arguments
59 */
60 public static void main(String[] args){
61 //Start a timer immediately upon code entrance.
62 Timer t=new Timer();
63
64 //Create an instance of this class
65 ContigRenamer x=new ContigRenamer(args);
66
67 //Run the object
68 x.process(t);
69
70 //Close the print stream if it was redirected
71 Shared.closeStream(x.outstream);
72 }
73
74 /**
75 * Constructor.
76 * @param args Command line arguments
77 */
78 public ContigRenamer(String[] args){
79
80 {//Preparse block for help, config files, and outstream
81 PreParser pp=new PreParser(args, getClass(), false);
82 args=pp.args;
83 outstream=pp.outstream;
84 }
85
86 //Set shared static variables prior to parsing
87 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
88 ReadWrite.setZipThreads(Shared.threads());
89
90 samFilter.includeUnmapped=false;
91 samFilter.includeSupplimentary=false;
92 samFilter.includeDuplicate=false;
93 samFilter.includeNonPrimary=false;
94 samFilter.includeQfail=false;
95 // samFilter.minMapq=4;
96
97 {//Parse the arguments
98 final Parser parser=parse(args);
99
100 Parser.processQuality();
101
102 maxReads=parser.maxReads;
103 overwrite=ReadStats.overwrite=parser.overwrite;
104 append=ReadStats.append=parser.append;
105
106 extin=parser.extin;
107
108 out=parser.out1;
109 extout=parser.extout;
110 }
111
112 {
113 samFilter.setSamtoolsFilter();
114
115 streamerThreads=Tools.max(1, Tools.min(streamerThreads, Shared.threads()));
116 assert(streamerThreads>0) : streamerThreads;
117 }
118
119 validateParams();
120 fixExtensions(); //Add or remove .gz or .bz2 as needed
121 checkFileExistence(); //Ensure files can be read and written
122 checkStatics(); //Adjust file-related static fields as needed for this program
123
124 //Create output FileFormat objects
125 ffout=FileFormat.testOutput(out, FileFormat.FASTA, extout, true, overwrite, append, ordered);
126
127 //Create input FileFormat objects
128 ffref=FileFormat.testInput(ref, FileFormat.FASTA, null, true, true);
129 }
130
131 /*--------------------------------------------------------------*/
132 /*---------------- Initialization Helpers ----------------*/
133 /*--------------------------------------------------------------*/
134
135 /** Parse arguments from the command line */
136 private Parser parse(String[] args){
137
138 //Create a parser object
139 Parser parser=new Parser();
140
141 //Set any necessary Parser defaults here
142 //parser.foo=bar;
143
144 //Parse each argument
145 for(int i=0; i<args.length; i++){
146 String arg=args[i];
147
148 //Break arguments into their constituent parts, in the form of "a=b"
149 String[] split=arg.split("=");
150 String a=split[0].toLowerCase();
151 String b=split.length>1 ? split[1] : null;
152 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
153
154 if(a.equals("verbose")){
155 verbose=Parse.parseBoolean(b);
156 }else if(a.equals("ref") || a.equals("contigs") || a.equals("in")){
157 ref=b;
158 }else if(a.equals("ordered")){
159 ordered=Parse.parseBoolean(b);
160 }else if(a.equals("delimiter")){
161 delimiter=Parse.parseSymbol(b);
162 }else if(a.equals("wipe")){
163 wipe=Parse.parseBoolean(b);
164 }else if(a.equals("depth") || a.equals("cov") || a.equals("adddepth")){
165 addDepth=Parse.parseBoolean(b);
166 }else if(a.equals("tid") || a.equalsIgnoreCase("taxid")){
167 addTid=Parse.parseBoolean(b);
168 }else if(a.equals("cami")){
169 cami=b;
170 }else if(a.equals("clearfilters")){
171 if(Parse.parseBoolean(b)){
172 samFilter.clear();
173 }
174 }else if(a.equals("parse_flag_goes_here")){
175 long fake_variable=Parse.parseKMG(b);
176 //Set a variable here
177 }else if(a.equals("sam") || a.equals("insam") || a.equals("samin")){
178 Tools.getFileOrFiles(b, in, false, false, true, false);
179 }else if(samFilter.parse(arg, a, b)){
180 //do nothing
181 }else if(new File(arg).isFile()){
182 in.add(arg);
183 }else if(parser.parse(arg, a, b)){//Parse standard flags in the parser
184 //do nothing
185 }else{
186 outstream.println("Unknown parameter "+args[i]);
187 assert(false) : "Unknown parameter "+args[i];
188 }
189 }
190
191 return parser;
192 }
193
194 /** Add or remove .gz or .bz2 as needed */
195 private void fixExtensions(){
196 in=Tools.fixExtension(in);
197 ref=Tools.fixExtension(ref);
198 }
199
200 /** Ensure files can be read and written */
201 private void checkFileExistence(){
202
203 //Ensure there is an input file
204 if(in==null){throw new RuntimeException("Error - an input file is required.");}
205
206 //Ensure there is an input file
207 if(ref==null){throw new RuntimeException("Error - a reference file is required.");}
208
209 //Ensure output files can be written
210 if(!Tools.testOutputFiles(overwrite, append, false, out)){
211 outstream.println((out==null)+", "+out);
212 throw new RuntimeException("\n\noverwrite="+overwrite+"; Can't write to output file "+out+"\n");
213 }
214
215 ArrayList<String> x=new ArrayList<String>();
216 x.addAll(in);
217 x.add(ref);
218
219 //Ensure input files can be read
220 if(!Tools.testInputFiles(false, true, x)){
221 throw new RuntimeException("\nCan't read some input files.\n");
222 }
223
224 x.add(out);
225
226 //Ensure that no file was specified multiple times
227 if(!Tools.testForDuplicateFiles(true, x.toArray(new String[0]))){
228 throw new RuntimeException("\nSome file names were specified multiple times.\n");
229 }
230 }
231
232 /** Adjust file-related static fields as needed for this program */
233 private static void checkStatics(){
234 //Adjust the number of threads for input file reading
235 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
236 ByteFile.FORCE_MODE_BF2=true;
237 }
238
239 assert(FastaReadInputStream.settingsOK());
240 }
241
242 /** Ensure parameter ranges are within bounds and required parameters are set */
243 private boolean validateParams(){
244 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
245 // assert(false) : "TODO";
246 return true;
247 }
248
249 /*--------------------------------------------------------------*/
250 /*---------------- Outer Methods ----------------*/
251 /*--------------------------------------------------------------*/
252
253 /** Create read streams and process all data */
254 void process(Timer t){
255
256 //Turn off read validation in the input threads to increase speed
257 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
258 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
259
260 //Reset counters
261 readsProcessed=readsOut=0;
262 basesProcessed=basesOut=0;
263
264 if(in.size()>0) {
265 processSam();
266 }else if(cami!=null) {
267 processCami();
268 }else {
269 assert(false) : "No input.";
270 }
271 processReference();
272
273 if(verbose){outstream.println("Finished; closing streams.");}
274
275 //Write anything that was accumulated by ReadStats
276 errorState|=ReadStats.writeAll();
277
278 //Reset read validation
279 Read.VALIDATE_IN_CONSTRUCTOR=vic;
280
281 //Report timing and results
282 t.stop();
283 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
284 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, readsOut, basesOut, 8, false));
285
286 //Throw an exception of there was an error in a thread
287 if(errorState){
288 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
289 }
290 }
291
292 private void processSam() {
293
294 for(int i=0; i<in.size(); i++) {
295 FileFormat ffin=FileFormat.testInput(in.get(i), FileFormat.SAM, extin, true, true);
296
297 //Create a read input stream
298 SamStreamer ss=makeStreamer(ffin);
299
300 if(scafMap.isEmpty()) {scafMap=makeScafMap();}
301
302 //Process the reads in separate threads
303 spawnThreads(ss);
304
305 for(Scaf scaf : scafMap.values()) {
306 scaf.process();
307 scaf.map.clear();
308 }
309 }
310 }
311
312 private void processCami() {
313 LineParser1 lp=new LineParser1('\t');
314 ArrayList<byte[]> lines=ByteFile.toLines(cami);
315 scafMap=new HashMap<String, Scaf>();
316 addDepth=false;
317 addTid=true;
318 for(byte[] line : lines) {
319 if(!Tools.startsWith(line, '@')){
320 lp.set(line);
321 String name=lp.parseString(0);
322 int taxID=lp.parseInt(2);
323 Scaf scaf=new Scaf(name, 1);
324 Scaf old=scafMap.putIfAbsent(name, scaf);
325 assert(old==null) : "Name conflict for scaffold "+name;
326 scaf.tidList.add(taxID);
327 scaf.covList.add(1);
328 }
329 }
330 }
331
332 private ConcurrentReadInputStream makeRefCris(){
333 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffref, null);
334 cris.start(); //Start the stream
335 if(verbose){outstream.println("Started cris");}
336 boolean paired=cris.paired();
337 assert(!paired) : "References should not be paired.";
338 return cris;
339 }
340
341 private SamStreamer makeStreamer(FileFormat ff){
342 if(ff==null){return null;}
343 SamStreamer ss=new SamLineStreamer(ff, streamerThreads, true, maxReads);
344 ss.start(); //Start the stream
345 if(verbose){outstream.println("Started Streamer");}
346 return ss;
347 }
348
349 private static HashMap<String, Scaf> makeScafMap() {
350 //@SQ SN:foo LN:999
351 LineParser4 lp=new LineParser4("\t:\t:");
352 ArrayList<byte[]> header=SamReadInputStream.getSharedHeader(true);
353 HashMap<String, Scaf> map=new HashMap<String, Scaf>(header.size()+1);
354 for(byte[] line : header) {
355 if(Tools.startsWith(line, "@SQ\t")){
356 lp.set(line);
357 assert(lp.termEquals("SN", 1)) : "\n"+lp.parseString(1)+"\n"+lp+"\n"+new String(line);
358 String name=lp.parseString(2);
359 assert(lp.termEquals("LN", 3));
360 int len=lp.parseInt(4);
361 Scaf scaf=new Scaf(name, len);
362 Scaf old=map.putIfAbsent(name, scaf);
363 assert(old==null) : "Name conflict for scaffold "+name;
364 }
365 }
366 return map;
367 }
368
369 private ConcurrentReadOutputStream makeCros(){
370 if(ffout==null){return null;}
371
372 //Select output buffer size based on whether it needs to be ordered
373 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
374
375 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout, null, buff, null, false);
376 ros.start(); //Start the stream
377 return ros;
378 }
379
380 /*--------------------------------------------------------------*/
381 /*---------------- Thread Management ----------------*/
382 /*--------------------------------------------------------------*/
383
384 /** Spawn process threads */
385 private void spawnThreads(final SamStreamer ss){
386
387 //Do anything necessary prior to processing
388
389 //Determine how many threads may be used
390 final int threads=Shared.threads();
391
392 //Fill a list with ProcessThreads
393 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
394 for(int i=0; i<threads; i++){
395 alpt.add(new ProcessThread(ss, i));
396 }
397
398 //Start the threads
399 for(ProcessThread pt : alpt){
400 pt.start();
401 }
402
403 //Wait for threads to finish
404 boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
405 errorState&=!success;
406
407 //Do anything necessary after processing
408
409 }
410
411 @Override
412 public final void accumulate(ProcessThread pt){
413 readsProcessed+=pt.readsProcessedT;
414 basesProcessed+=pt.basesProcessedT;
415 errorState|=(!pt.success);
416 }
417
418 @Override
419 public final boolean success(){return !errorState;}
420
421 /*--------------------------------------------------------------*/
422 /*---------------- Inner Methods ----------------*/
423 /*--------------------------------------------------------------*/
424
425 private void processReference(){
426 ConcurrentReadInputStream cris=makeRefCris();
427 ConcurrentReadOutputStream ros=makeCros();
428 ListNum<Read> ln=null;
429 for(ln=cris.nextList(); ln!=null && ln.size()>0; ln=cris.nextList()) {
430 for(Read r : ln) {
431 r.id=(rename(r.id, r.length(), r.numericID));
432 readsOut++;
433 basesOut+=r.length();
434 readsProcessed++;
435 basesProcessed+=r.length();
436 }
437 if(ros!=null) {ros.add(ln.list, ln.id);}
438 cris.returnList(ln);
439 }
440
441 //Notify the input stream that the list was used
442 cris.returnList(ln);
443
444 //Notify the input stream that the final list was used
445 if(ln!=null){
446 cris.returnList(ln.id, ln.list==null || ln.list.isEmpty());
447 }
448 errorState|=ReadWrite.closeStreams(cris, ros);
449 }
450
451 static String toShortName(String s) {
452 int idx=Tools.indexOfWhitespace(s);
453 return idx<0 ? s : s.substring(0, idx);
454 }
455
456 static String toShortName(byte[] s) {
457 int idx=Tools.indexOfWhitespace(s);
458 return idx<0 ? new String(s) : new String(s, 0, idx);
459 }
460
461 private String rename(final String old, final int scaflen, long numericID) {
462 final String name=old;
463 final String shortName=toShortName(name);
464 final int oldTaxid=TaxTree.parseHeaderStatic2(old, null);
465 Scaf scaf=scafMap.get(shortName);
466 if(scaf==null) {scaf=scafMap.get(name);}
467 assert(scaf!=null) : "Can't find "+shortName+" in map of size "+scafMap.size();
468 if(scaf==null) {return old+delimiter+"cov_0";}
469
470 IntList tids=scaf.tidList;
471 FloatList covs=scaf.covList;
472 float maxCov=0;
473 int maxTid=-1;
474 for(int i=0; i<covs.size(); i++) {
475 int tid=tids.get(i);
476 float cov=covs.get(i);
477 if(maxTid<=0 || cov>maxCov) {
478 maxCov=cov;
479 maxTid=tid;
480 }
481 }
482
483 ByteBuilder bb=new ByteBuilder(old.length()+(covs.size*9)+20);
484 if(wipe) {
485 bb.append("contig_").append(numericID);
486 }else {
487 bb.append(old);
488 }
489
490 if(oldTaxid<0 && maxTid>0 && addTid) {bb.append(delimiter).append("tid_").append(maxTid);}
491 for(int i=0; i<covs.size && addDepth; i++) {
492 bb.append(delimiter).append("cov_").append(covs.get(i), 2);
493 }
494 // assert(false) : oldTaxid+", "+maxTid+", "+bb;
495 return bb.toString();
496 }
497
498 /*--------------------------------------------------------------*/
499 /*---------------- Inner Classes ----------------*/
500 /*--------------------------------------------------------------*/
501
502 /** This class is static to prevent accidental writing to shared variables.
503 * It is safe to remove the static modifier. */
504 class ProcessThread extends Thread {
505
506 //Constructor
507 ProcessThread(final SamStreamer ss_, final int tid_){
508 ss=ss_;
509 tid=tid_;
510 }
511
512 //Called by start()
513 @Override
514 public void run(){
515 //Do anything necessary prior to processing
516
517 //Process the reads
518 processInner();
519
520 //Do anything necessary after processing
521
522 //Indicate successful exit status
523 success=true;
524 }
525
526 /** Iterate through the reads */
527 void processInner(){
528
529 //Grab and process all lists
530 for(ListNum<SamLine> ln=ss.nextLines(); ln!=null; ln=ss.nextLines()){
531 // if(verbose){outstream.println("Got list of size "+list.size());} //Disabled due to non-static access
532
533 processList(ln);
534 }
535
536 }
537
538 void processList(ListNum<SamLine> ln){
539
540 //Grab the actual read list from the ListNum
541 final ArrayList<SamLine> reads=ln.list;
542
543 //Loop through each read in the list
544 for(int idx=0; idx<reads.size(); idx++){
545 final SamLine r=reads.get(idx);
546
547 //Track the initial length for statistics
548 final int initialLength=r.length();
549
550 //Increment counters
551 readsProcessedT+=r.length();
552 basesProcessedT+=initialLength;
553
554 addLine(r);
555 }
556 }
557
558 private void addLine(SamLine sl) {
559 if(samFilter!=null && !samFilter.passesFilter(sl)){return;}
560 String key=sl.rnameS();
561 Scaf scaf=scafMap.get(key);
562 assert(scaf!=null) : "Can't find scaffold "+key+" in map of size "+scafMap.size();
563 scaf.add(sl);
564 }
565
566 /** Number of reads processed by this thread */
567 protected long readsProcessedT=0;
568 /** Number of bases processed by this thread */
569 protected long basesProcessedT=0;
570
571 /** True only if this thread has completed successfully */
572 boolean success=false;
573
574 /** Shared input stream */
575 private final SamStreamer ss;
576 /** Thread ID */
577 final int tid;
578 }
579
580 private static class Scaf {
581
582 Scaf(String shortName_, int length_) {
583 name=shortName_;
584 length=length_;
585 }
586
587 void add(SamLine sl) {
588 int taxid=TaxTree.parseHeaderStatic2(sl.qname, null);
589 int length=sl.length();
590 synchronized(this) {map.increment(taxid, length);}
591 }
592
593 void process() {
594
595 final int[] keys=map.keys();
596 final long[] values=map.values();
597 final int invalid=map.invalid();
598 int taxid=-1;
599 long totalMappedBases=0;
600 long maxMappedBases=0;
601 for(int i=0; i<keys.length; i++) {
602 int key=keys[i];
603 long value=values[i];
604 if(key!=invalid) {
605 totalMappedBases+=value;
606 if(value>maxMappedBases) {
607 maxMappedBases=value;
608 taxid=key;
609 }
610 }
611 }
612 assert(length>0);
613 final float cov=totalMappedBases/(float)length;
614 tidList.add(taxid);
615 covList.add(cov);
616 }
617
618 final String name;
619 final int length;
620
621 IntLongHashMap map=new IntLongHashMap(7);
622 IntList tidList=new IntList(2);
623 FloatList covList=new FloatList(2);
624
625 }
626
627 /*--------------------------------------------------------------*/
628 /*---------------- Fields ----------------*/
629 /*--------------------------------------------------------------*/
630
631 /** Sam input file path */
632 private ArrayList<String> in=new ArrayList<String>();
633 /** Contig input file path */
634 private String ref=null;
635
636 private String cami=null;
637
638 /** Primary output file path */
639 private String out=null;
640
641 /** Override input file extension */
642 private String extin=null;
643 /** Override output file extension */
644 private String extout=null;
645
646 /*--------------------------------------------------------------*/
647
648 /** Number of reads processed */
649 protected long readsProcessed=0;
650 /** Number of bases processed */
651 protected long basesProcessed=0;
652
653 /** Number of reads retained */
654 protected long readsOut=0;
655 /** Number of bases retained */
656 protected long basesOut=0;
657
658 /** Quit after processing this many input reads; -1 means no limit */
659 private long maxReads=-1;
660
661 private String delimiter=" ";
662 private boolean wipe=false;
663 private boolean addDepth=true;
664 private boolean addTid=true;
665
666 /*--------------------------------------------------------------*/
667
668 /** Threads dedicated to reading the sam file */
669 private int streamerThreads=SamStreamer.DEFAULT_THREADS;
670
671 public final SamFilter samFilter=new SamFilter();
672
673 public HashMap<String, Scaf> scafMap=new HashMap<String, Scaf>();
674
675 @Override
676 public final ReadWriteLock rwlock() {return rwlock;}
677 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
678
679 /*--------------------------------------------------------------*/
680 /*---------------- Final Fields ----------------*/
681 /*--------------------------------------------------------------*/
682
683 /** Secondary input file */
684 private final FileFormat ffref;
685
686 /** Primary output file */
687 private final FileFormat ffout;
688
689 /*--------------------------------------------------------------*/
690 /*---------------- Common Fields ----------------*/
691 /*--------------------------------------------------------------*/
692
693 /** Print status messages to this output stream */
694 private PrintStream outstream=System.err;
695 /** Print verbose messages */
696 public static boolean verbose=false;
697 /** True if an error was encountered */
698 public boolean errorState=false;
699 /** Overwrite existing output files */
700 private boolean overwrite=true;
701 /** Append to existing output files */
702 private boolean append=false;
703 /** Reads are output in input order */
704 private boolean ordered=false;
705
706 }