Debian Codegraph @

current/consensus/Lilypad.java

raw symbols SCIP
1 package consensus;
2
3 import java.io.PrintStream;
4 import java.util.ArrayList;
5 import java.util.LinkedHashMap;
6 import java.util.Map.Entry;
7 import java.util.concurrent.atomic.AtomicIntegerArray;
8 import java.util.concurrent.atomic.AtomicLongArray;
9 import java.util.concurrent.locks.ReadWriteLock;
10 import java.util.concurrent.locks.ReentrantReadWriteLock;
11
12 import dna.AminoAcid;
13 import fileIO.ByteFile;
14 import fileIO.FileFormat;
15 import fileIO.ReadWrite;
16 import shared.Parse;
17 import shared.Parser;
18 import shared.PreParser;
19 import shared.Shared;
20 import shared.Timer;
21 import shared.Tools;
22 import stream.ConcurrentReadInputStream;
23 import stream.ConcurrentReadOutputStream;
24 import stream.FastaReadInputStream;
25 import stream.Read;
26 import stream.SamLine;
27 import stream.SamReadStreamer;
28 import stream.SamStreamer;
29 import structures.ByteBuilder;
30 import structures.ListNum;
31 import template.Accumulator;
32 import template.ThreadWaiter;
33 import tracker.ReadStats;
34 import var2.SamFilter;
35
36 /**
37 * Scaffolds contigs based on paired read mapping.
38 *
39 * @author Brian Bushnell
40 * @date September 11, 2019
41 *
42 */
43 public class Lilypad implements Accumulator<Lilypad.ProcessThread> {
44
45 /*--------------------------------------------------------------*/
46 /*---------------- Initialization ----------------*/
47 /*--------------------------------------------------------------*/
48
49 /**
50 * Code entrance from the command line.
51 * @param args Command line arguments
52 */
53 public static void main(String[] args){
54 //Start a timer immediately upon code entrance.
55 Timer t=new Timer();
56
57 //Create an instance of this class
58 Lilypad x=new Lilypad(args);
59
60 //Run the object
61 x.process(t);
62
63 //Close the print stream if it was redirected
64 Shared.closeStream(x.outstream);
65 }
66
67 /**
68 * Constructor.
69 * @param args Command line arguments
70 */
71 public Lilypad(String[] args){
72
73 {//Preparse block for help, config files, and outstream
74 PreParser pp=new PreParser(args, getClass(), false);
75 args=pp.args;
76 outstream=pp.outstream;
77 }
78
79 //Set shared static variables prior to parsing
80 ReadWrite.USE_PIGZ=ReadWrite.USE_UNPIGZ=true;
81 ReadWrite.setZipThreads(Shared.threads());
82 SamLine.RNAME_AS_BYTES=false;
83
84 samFilter.includeUnmapped=false;
85 samFilter.includeSupplimentary=false;
86 // samFilter.includeDuplicate=false;
87 samFilter.includeNonPrimary=false;
88 samFilter.includeQfail=false;
89 samFilter.minMapq=4;
90
91 {//Parse the arguments
92 final Parser parser=parse(args);
93
94 Parser.processQuality();
95
96 maxReads=parser.maxReads;
97 overwrite=ReadStats.overwrite=parser.overwrite;
98 append=ReadStats.append=parser.append;
99
100 in=parser.in1;
101 extin=parser.extin;
102
103 out=parser.out1;
104 extout=parser.extout;
105 }
106
107 {
108 // if("auto".equalsIgnoreCase(atomic)){Scaffold.setCA3A(Shared.threads()>8);}
109 // else{Scaffold.setCA3A(Parse.parseBoolean(atomic));}
110 samFilter.setSamtoolsFilter();
111
112 streamerThreads=Tools.max(1, Tools.min(streamerThreads, Shared.threads()));
113 assert(streamerThreads>0) : streamerThreads;
114 }
115
116 validateParams();
117 fixExtensions(); //Add or remove .gz or .bz2 as needed
118 checkFileExistence(); //Ensure files can be read and written
119 checkStatics(); //Adjust file-related static fields as needed for this program
120
121 //Create output FileFormat objects
122 ffout=FileFormat.testOutput(out, FileFormat.FASTA, extout, true, overwrite, append, ordered);
123
124 //Create input FileFormat objects
125 ffin=FileFormat.testInput(in, FileFormat.SAM, extin, true, true);
126 ffref=FileFormat.testInput(ref, FileFormat.FASTA, null, true, true);
127 }
128
129 /*--------------------------------------------------------------*/
130 /*---------------- Initialization Helpers ----------------*/
131 /*--------------------------------------------------------------*/
132
133 /** Parse arguments from the command line */
134 private Parser parse(String[] args){
135
136 //Create a parser object
137 Parser parser=new Parser();
138
139 //Set any necessary Parser defaults here
140 //parser.foo=bar;
141
142 //Parse each argument
143 for(int i=0; i<args.length; i++){
144 String arg=args[i];
145
146 //Break arguments into their constituent parts, in the form of "a=b"
147 String[] split=arg.split("=");
148 String a=split[0].toLowerCase();
149 String b=split.length>1 ? split[1] : null;
150 if(b!=null && b.equalsIgnoreCase("null")){b=null;}
151
152 if(a.equals("verbose")){
153 verbose=Parse.parseBoolean(b);
154 }else if(a.equals("ref") || a.equals("scaffolds")){
155 ref=b;
156 }else if(a.equals("insertlist")){
157 insertList=b;
158 }else if(a.equals("ordered")){
159 ordered=Parse.parseBoolean(b);
160 }else if(a.equalsIgnoreCase("sameStrandPairs")){
161 sameStrandPairs=Parse.parseBoolean(b);
162 }else if(a.equalsIgnoreCase("ns") || a.equalsIgnoreCase("n") || a.equalsIgnoreCase("scaffoldbreak") || a.equalsIgnoreCase("gap") || a.equalsIgnoreCase("mingap")){
163 scaffoldBreakNs=Integer.parseInt(b);
164 assert(scaffoldBreakNs>0);
165 }else if(a.equalsIgnoreCase("mindepth")){
166 minDepth=Integer.parseInt(b);
167 assert(minDepth>0);
168 }else if(a.equalsIgnoreCase("maxinsert")){
169 maxPairDist=Parse.parseIntKMG(b);
170 }else if(a.equalsIgnoreCase("minWeightRatio") || a.equalsIgnoreCase("minwr")){
171 minWeightRatio=Float.parseFloat(b);
172 }else if(a.equalsIgnoreCase("minStrandRatio") || a.equalsIgnoreCase("minsr")){
173 minStrandRatio=Float.parseFloat(b);
174 }else if(a.equals("clearfilters") || a.equals("clearfilter")){
175 if(Parse.parseBoolean(b)){
176 samFilter.clear();
177 }
178 }else if(a.equals("parse_flag_goes_here")){
179 long fake_variable=Parse.parseKMG(b);
180 //Set a variable here
181 }else if(samFilter.parse(arg, a, b)){
182 //do nothing
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 //Ensure input files can be read
216 if(!Tools.testInputFiles(false, true, in, ref)){
217 throw new RuntimeException("\nCan't read some input files.\n");
218 }
219
220 //Ensure that no file was specified multiple times
221 if(!Tools.testForDuplicateFiles(true, in, ref, out)){
222 throw new RuntimeException("\nSome file names were specified multiple times.\n");
223 }
224 }
225
226 /** Adjust file-related static fields as needed for this program */
227 private static void checkStatics(){
228 //Adjust the number of threads for input file reading
229 if(!ByteFile.FORCE_MODE_BF1 && !ByteFile.FORCE_MODE_BF2 && Shared.threads()>2){
230 ByteFile.FORCE_MODE_BF2=true;
231 }
232
233 assert(FastaReadInputStream.settingsOK());
234 }
235
236 /** Ensure parameter ranges are within bounds and required parameters are set */
237 private boolean validateParams(){
238 // assert(minfoo>0 && minfoo<=maxfoo) : minfoo+", "+maxfoo;
239 return true;
240 }
241
242 /*--------------------------------------------------------------*/
243 /*---------------- Outer Methods ----------------*/
244 /*--------------------------------------------------------------*/
245
246 /** Create read streams and process all data */
247 void process(Timer t){
248
249 //Turn off read validation in the input threads to increase speed
250 final boolean vic=Read.VALIDATE_IN_CONSTRUCTOR;
251 Read.VALIDATE_IN_CONSTRUCTOR=Shared.threads()<4;
252
253 //Create a read input stream
254 final SamStreamer ss=makeStreamer(ffin);
255
256 //Load reference
257 loadReferenceCustom();
258
259 //Reset counters
260 readsProcessed=readsOut=0;
261 basesProcessed=basesOut=0;
262
263 //Process the reads in separate threads
264 spawnThreads(ss);
265
266 //Optionally create a read output stream
267 final ConcurrentReadOutputStream ros=makeCros();
268
269 if(verbose){outstream.println("Fixing reference.");}
270
271 makeScaffolds(ros);
272
273 if(verbose){outstream.println("Finished; closing streams.");}
274
275 //Write anything that was accumulated by ReadStats
276 errorState|=ReadStats.writeAll();
277 //Close the read streams
278 errorState|=ReadWrite.closeStream(ros);
279
280 //Reset read validation
281 Read.VALIDATE_IN_CONSTRUCTOR=vic;
282
283 //Report timing and results
284 t.stop();
285 outstream.println(Tools.timeReadsBasesProcessed(t, readsProcessed, basesProcessed, 8));
286 outstream.println(Tools.readsBasesOut(readsProcessed, basesProcessed, scaffoldsOut, scaffoldLengthOut, 8, false));
287
288 outstream.println();
289 outstream.println(Tools.number("Average Insert", totalAverageInsert, 2, 8));
290 outstream.println(Tools.number("Joins Made ", gapsAdded, 8));
291 outstream.println(Tools.number("Ns Added ", nsAdded, 8));
292 outstream.println(Tools.number("Contigs In ", refMap.size(), 8));
293 outstream.println(Tools.number("Scaffolds Out ", scaffoldsOut, 8));
294
295
296 //Throw an exception of there was an error in a thread
297 if(errorState){
298 throw new RuntimeException(getClass().getName()+" terminated in an error state; the output may be corrupt.");
299 }
300 }
301
302 private synchronized void loadReferenceCustom(){
303 assert(!loadedRef);
304 ConcurrentReadInputStream cris=makeRefCris();
305 for(ListNum<Read> ln=cris.nextList(); ln!=null && ln.size()>0; ln=cris.nextList()) {
306 for(Read r : ln){
307 String name=r.id;
308 String name2=Tools.trimToWhitespace(r.id);
309 Contig cont=new Contig(name, r.bases, r.numericID);
310 refMap.put(name, cont);
311 refMap2.put(name2, cont);
312 }
313 cris.returnList(ln);
314 }
315 ReadWrite.closeStream(cris);
316 loadedRef=true;
317 }
318
319 private ConcurrentReadInputStream makeRefCris(){
320 ConcurrentReadInputStream cris=ConcurrentReadInputStream.getReadInputStream(maxReads, true, ffref, null);
321 cris.start(); //Start the stream
322 if(verbose){outstream.println("Started cris");}
323 boolean paired=cris.paired();
324 assert(!paired) : "References should not be paired.";
325 return cris;
326 }
327
328 private SamStreamer makeStreamer(FileFormat ff){
329 if(ff==null){return null;}
330 SamStreamer ss=new SamReadStreamer(ff, streamerThreads, true, maxReads);
331 ss.start(); //Start the stream
332 if(verbose){outstream.println("Started Streamer");}
333 return ss;
334 }
335
336 private ConcurrentReadOutputStream makeCros(){
337 if(ffout==null){return null;}
338
339 //Select output buffer size based on whether it needs to be ordered
340 final int buff=(ordered ? Tools.mid(16, 128, (Shared.threads()*2)/3) : 8);
341
342 final ConcurrentReadOutputStream ros=ConcurrentReadOutputStream.getStream(ffout, null, buff, null, false);
343 ros.start(); //Start the stream
344 return ros;
345 }
346
347 /*--------------------------------------------------------------*/
348 /*---------------- Thread Management ----------------*/
349 /*--------------------------------------------------------------*/
350
351 /** Spawn process threads */
352 private void spawnThreads(final SamStreamer ss){
353
354 //Do anything necessary prior to processing
355
356 //Determine how many threads may be used
357 final int threads=Shared.threads();
358
359 //Fill a list with ProcessThreads
360 ArrayList<ProcessThread> alpt=new ArrayList<ProcessThread>(threads);
361 for(int i=0; i<threads; i++){
362 alpt.add(new ProcessThread(ss, i));
363 }
364
365 //Start the threads
366 for(ProcessThread pt : alpt){
367 pt.start();
368 }
369
370 //Wait for threads to finish
371 boolean success=ThreadWaiter.waitForThreadsToFinish(alpt, this);
372 errorState&=!success;
373
374 //Do anything necessary after processing
375 totalAverageInsert=totalInsertSum/(double)totalInsertCount;
376 insertByPercentile=Tools.makeHistogram(insertCounts, buckets);
377 }
378
379 @Override
380 public final void accumulate(ProcessThread pt){
381 readsProcessed+=pt.readsProcessedT;
382 basesProcessed+=pt.basesProcessedT;
383 readsOut+=pt.readsOutT;
384 basesOut+=pt.basesOutT;
385
386 totalInsertSum+=pt.totalInsertSumT;
387 totalInsertCount+=pt.totalInsertCountT;
388
389 errorState|=(!pt.success);
390 }
391
392 @Override
393 public final boolean success(){return !errorState;}
394
395 /*--------------------------------------------------------------*/
396 /*---------------- Inner Methods ----------------*/
397 /*--------------------------------------------------------------*/
398
399 private void makeScaffolds(ConcurrentReadOutputStream ros){
400 ByteBuilder bb=new ByteBuilder(1000000);
401
402 ArrayList<Read> list=new ArrayList<Read>(200);
403 long num=0;
404 long lengthSum=0;
405 for(Entry<String, Contig> e : refMap.entrySet()){
406 Contig cont=e.getValue();
407 if(!cont.processed()){
408 Read r=cont.makeScaffold(bb);
409 assert(r!=null);
410
411 lengthSum+=r.length();
412 list.add(r);
413 scaffoldsOut++;
414 scaffoldLengthOut+=r.length();
415
416 if(list.size()>=200 || lengthSum>=100000){
417 if(ros!=null){ros.add(list, num);}
418 list=new ArrayList<Read>(200);
419 num++;
420 lengthSum=0;
421 }
422 assert(cont.processed());
423 }
424 }
425 if(list.size()>0){
426 if(ros!=null){ros.add(list, num);}
427 }
428 }
429
430 private static int calcInsertSize(SamLine sl) {
431 assert(sl.mapped() && sl.pairedOnSameChrom());
432 assert(sl.primary());
433 assert(!sl.supplementary());
434 assert(sl.leftmost());
435
436 assert(sl.tlen>0) : sl.tlen+"\n\n"+sl;
437 return sl.tlen>0 ? sl.tlen : -sl.tlen;
438
439 // final int insertSize;
440 // String insertTag=null;
441 // if(sl.optional!=null){
442 // for(String s : sl.optional){
443 // if(s.startsWith("X8:Z:")){
444 // insertTag=s;
445 // break;
446 // }
447 // }
448 // }
449 // if(insertTag!=null){
450 // insertSize=Integer.parseInt(insertTag.substring(5));
451 // }else{
452 // insertSize=sl.tlen;//This is unsafe due to indels.
453 // assert(false) : "Reads need insert size tags.";
454 // }
455 // assert(insertSize>0) : sl;
456 //
457 // return insertSize;
458 }
459
460 private Contig getScaffold(String rname){
461 Contig scaf=refMap.get(rname);
462 if(scaf==null){scaf=refMap2.get(Tools.trimToWhitespace(rname));}
463 assert(scaf!=null) : "Can't find graph for "+rname;
464 return scaf;
465 }
466
467 /*--------------------------------------------------------------*/
468 /*---------------- Inner Classes ----------------*/
469 /*--------------------------------------------------------------*/
470
471 /** This class is static to prevent accidental writing to shared variables.
472 * It is safe to remove the static modifier. */
473 class ProcessThread extends Thread {
474
475 //Constructor
476 ProcessThread(final SamStreamer ss_, final int tid_){
477 ss=ss_;
478 tid=tid_;
479 }
480
481 //Called by start()
482 @Override
483 public void run(){
484 //Do anything necessary prior to processing
485
486 //Process the reads
487 processInner();
488
489 //Do anything necessary after processing
490
491 //Indicate successful exit status
492 success=true;
493 }
494
495 /** Iterate through the reads */
496 void processInner(){
497
498 //Grab and process all lists
499 for(ListNum<Read> ln=ss.nextReads(); ln!=null; ln=ss.nextReads()){
500 // if(verbose){outstream.println("Got list of size "+list.size());} //Disabled due to non-static access
501
502 processList(ln);
503 }
504
505 }
506
507 void processList(ListNum<Read> ln){
508
509 //Grab the actual read list from the ListNum
510 final ArrayList<Read> reads=ln.list;
511
512 //Loop through each read in the list
513 for(int idx=0; idx<reads.size(); idx++){
514 final Read r=reads.get(idx);
515
516 //Validate reads in worker threads
517 if(!r.validated()){r.validate(true);}
518
519 //Track the initial length for statistics
520 final int initialLength=r.length();
521
522 //Increment counters
523 readsProcessedT+=r.pairCount();
524 basesProcessedT+=initialLength;
525
526 processRead(r);
527 }
528 }
529
530 /**
531 * Process a read or a read pair.
532 * @param r Read 1
533 * @param r2 Read 2 (may be null)
534 * @return True if the reads should be kept, false if they should be discarded.
535 */
536 void processRead(final Read r){
537 final SamLine sl=r.samline;
538 assert(sl!=null) : sl;
539 if(samFilter!=null && !samFilter.passesFilter(sl)){return;}
540
541 //sl.nextMapped();
542 if(sl.mapped() && sl.primary() && !sl.supplementary()){
543 final String rname=sl.rnameS();
544 Contig scaf=getScaffold(rname);
545 if(scaf!=null){
546 if(sl.pairedOnSameChrom() && sl.properPair() && sl.leftmost()){
547 final int insertSize=calcInsertSize(sl);
548 insertCounts.incrementAndGet(Tools.mid(0, insertSize, insertCounts.length()-1));
549 totalInsertSumT+=insertSize;
550 totalInsertCountT++;
551 }
552 scaf.add(sl);
553
554 readsOutT++;
555 basesOutT+=r.length();
556 }
557 }
558 if(sl.mapped() && sl.pairedOnSameChrom() && sl.properPair() && sl.primary() && !sl.supplementary() && sl.leftmost()){
559 final String rname=sl.rnameS();
560
561 Contig scaf=getScaffold(rname);
562 if(scaf!=null){
563 final int insertSize=calcInsertSize(sl);
564 insertCounts.incrementAndGet(Tools.mid(0, insertSize, insertCounts.length()-1));
565 scaf.add(sl);
566
567 readsOutT++;
568 basesOutT+=r.length();
569
570 totalInsertSumT+=insertSize;
571 totalInsertCountT++;
572 }
573 }
574 }
575
576 /** Number of reads processed by this thread */
577 protected long readsProcessedT=0;
578 /** Number of bases processed by this thread */
579 protected long basesProcessedT=0;
580
581 /** Number of reads retained by this thread */
582 protected long readsOutT=0;
583 /** Number of bases retained by this thread */
584 protected long basesOutT=0;
585
586 protected long totalInsertSumT=0;
587 protected long totalInsertCountT=0;
588
589 long insertSum=0;
590
591 /** True only if this thread has completed successfully */
592 boolean success=false;
593
594 /** Shared input stream */
595 private final SamStreamer ss;
596 /** Thread ID */
597 final int tid;
598 }
599
600 Contig findLeftmost(Contig source){
601 if(verbose){System.err.println("findLeftmost("+source.name+")");}
602 while(true) {
603 assert(!source.processed());
604 if(source.processed()){return null;}
605 source.processedLeft=true;
606 Edge se=source.bestEdge(true);
607 if(verbose){System.err.println("Found source edge "+se);}
608 if(se==null){return source;}
609 Contig dest=se.dest;
610 if(dest.processed()){
611 if(verbose){System.err.println("Dest was processed; returning.");}
612 return source;
613 }
614 if(se.sameStrand()){
615 if(source.strand==dest.strand){
616
617 }else{
618 if(verbose){System.err.println("Flipping "+dest.name);}
619 dest.flip();
620 }
621 }else{
622 if(source.strand==dest.strand){
623 if(verbose){System.err.println("Flipping "+dest.name);}
624 dest.flip();
625 }else{
626
627 }
628 }
629 Edge de=dest.bestEdge(false);
630 if(verbose){System.err.println("Found dest edge "+de);}
631 if(de==null || de.dest!=source){
632 if(dest.strand==1){dest.flip();}
633 if(verbose){System.err.println("Dest edge did not match; returning.");}
634 return source;
635 }
636 source=dest;
637 if(verbose){System.err.println("Migrated to next node.");}
638 }
639 }
640
641 Read expandRight(final Contig source0, ByteBuilder bb){
642 if(verbose){System.err.println("expandRight("+source0.name+")");}
643 bb.clear();
644 Contig source=source0;
645 while(true) {
646 assert(!source.processedRight);
647 if(source.processedRight){return null;}
648 if(source.strand==1){
649 Tools.reverseInPlace(source.depthArray);
650 }
651 source.processedRight=true;
652 bb.append(source.bases);
653 Edge se=source.bestEdge(false);
654 if(verbose){System.err.println("Found source edge "+se);}
655 if(se==null){break;}
656 Contig dest=se.dest;
657 if(dest.processedRight){
658 if(verbose){System.err.println("Dest was processed; returning.");}
659 break;
660 }
661 if(se.sameStrand()){
662 if(source.strand==dest.strand){
663
664 }else{
665 if(verbose){System.err.println("Flipping "+dest.name);}
666 dest.flip();
667 }
668 }else{
669 if(source.strand==dest.strand){
670 if(verbose){System.err.println("Flipping "+dest.name);}
671 dest.flip();
672 }else{
673
674 }
675 }
676 Edge de=dest.bestEdge(true);
677 if(verbose){System.err.println("Found dest edge "+de);}
678 if(de==null || de.dest!=source){
679 if(verbose){System.err.println("Dest edge did not match; returning.");}
680 if(dest.strand==1){dest.flip();}
681 break;
682 }
683
684 //Now append Ns
685 int observedLength=(int)(se.distanceSum/se.count());
686 long depth=se.count();
687 int depthProxyIndex=(source.length()-Tools.min(source.length()/2, 300));
688 long depthProxy=source.depthArray.get(depthProxyIndex);
689 int percentile=(int)(buckets*depth/(float)(depth+depthProxy));
690 int inferredLength=insertByPercentile[percentile];
691
692 int Ns=(Tools.max(scaffoldBreakNs, inferredLength-observedLength));
693 for(int i=0; i<Ns; i++){bb.append('N');}
694 source=dest;
695
696 gapsAdded++;
697 nsAdded+=Ns;
698 }
699 Read r=new Read(bb.toBytes(), null, source0.name, source0.numericID);
700 return r;
701 }
702
703 /*--------------------------------------------------------------*/
704
705 private class Contig {
706
707 Contig(String name_, byte[] bases_, long numericID_){
708 name=name_;
709 bases=bases_;
710 numericID=(int)numericID_;
711 depthArray=new AtomicIntegerArray(bases.length);
712 }
713
714 public Read makeScaffold(ByteBuilder bb) {
715 assert(!processed());
716 Contig leftmost=findLeftmost(this);
717 return expandRight(leftmost, bb);
718 }
719
720 Edge bestEdge(boolean left) {
721 final LinkedHashMap<String, Edge> map=(left ? leftEdgeMap : rightEdgeMap);
722 if(map.isEmpty()){return null;}
723 long weightSum=0;
724 long countSum=0;
725 Edge best=null;
726 for(Entry<String, Edge> entry : map.entrySet()){
727 Edge e=entry.getValue();
728 weightSum+=e.weight;
729 countSum+=e.count();
730 if(best==null || e.weight>best.weight){best=e;}
731 }
732 if(best.count()<minDepth){return null;}
733 if(weightSum*minWeightRatio>best.weight){return null;}
734 if(best.strandRatio()<minStrandRatio){return null;}
735 if(best.badCount>0.5*best.count()){return null;}
736 return best;
737 }
738
739 void add(SamLine sl){
740 assert(sl.mapped() && sl.primary() && !sl.supplementary());
741 if(sl.nextMapped()){
742 if(sl.pairedOnSameChrom()){
743 if(!sl.properPair()){
744 addCoverageSingleton(sl);
745 }else if(sl.leftmost()){
746 addCoveragePaired(sl);
747 }
748 }else{
749 addCoverageSingleton(sl);
750 handleMixedPair(sl);
751 }
752 }else{
753 addCoverageSingleton(sl);
754 }
755 }
756
757 private void addCoverageSingleton(SamLine sl){
758 assert(sl.cigar!=null);
759 int start=sl.pos-1;
760 int stop=start+SamLine.calcCigarLength(sl.cigar, false, false);
761
762 for(int i=start; i<stop; i++){
763 if(i>=0 && i<bases.length){
764 depthArray.incrementAndGet(i);
765 }
766 }
767 }
768
769 private void addCoveragePaired(SamLine sl){
770 assert(sl.cigar!=null);
771 assert(sl.leftmost() && sl.pairedOnSameChrom() && sl.nextMapped());
772 int start=sl.pos-1;
773 int stop=start+sl.tlen;
774
775 for(int i=start; i<stop; i++){
776 if(i>=0 && i<bases.length){
777 depthArray.incrementAndGet(i);
778 }
779 }
780 }
781
782 /** Reads mapping to different contigs */
783 private void handleMixedPair(SamLine sl){
784 assert(sl.mapped() && sl.nextMapped() && !sl.pairedOnSameChrom());
785 String rname=sl.rnameS();
786 String rnext=sl.rnextS();
787 if(rname.equals(rnext)){return;}
788
789 final boolean left=(sl.strand()==1);
790 LinkedHashMap<String, Edge> map=(left ? leftEdgeMap : rightEdgeMap);
791 Edge e=map.get(rnext);
792 Contig dest=null;
793 if(e==null){
794 dest=getScaffold(rnext);
795 if(dest==null){return;}
796 e=new Edge(this, dest, left);
797 map.put(rnext, e);
798 }
799 e.add(sl);
800 }
801
802 void flip(){//Be careful with this
803 AminoAcid.reverseComplementBasesInPlace(bases);
804 strand^=1;
805 LinkedHashMap<String, Edge> temp=leftEdgeMap;
806 leftEdgeMap=rightEdgeMap;
807 rightEdgeMap=temp;
808 }
809
810 int length(){return bases.length;}
811
812 final int numericID;
813 final String name;
814 final byte[] bases;
815 final AtomicIntegerArray depthArray;
816 int strand=0;
817
818 boolean processedLeft=false;
819 boolean processedRight=false;
820 boolean processed(){return processedLeft || processedRight;}
821
822 LinkedHashMap<String, Edge> leftEdgeMap=new LinkedHashMap<String, Edge>();
823 LinkedHashMap<String, Edge> rightEdgeMap=new LinkedHashMap<String, Edge>();
824 }
825
826 private class Edge{
827
828 Edge(Contig source_, Contig dest_, boolean left_){
829 source=source_;
830 dest=dest_;
831 leftEdge=left_;
832 }
833
834 void add(SamLine sl){
835 final boolean sameStrandReads=(sl.strand()==sl.mateStrand());
836 final boolean sameStrandContigs=(sameStrandPairs==sameStrandReads);
837 final int spos, dpos;
838 if(leftEdge){
839 spos=sl.pos+sl.calcCigarLength(true, false)-1;
840 dpos=(sameStrandContigs ? dest.length()-sl.pnext : sl.pnext+sl.length())-1;
841 }else{
842 spos=source.length()-sl.pos-1;
843 dpos=(sameStrandContigs ? sl.pnext+sl.length() : dest.length()-sl.pnext)-1;
844 }
845 final int distance=spos+dpos;
846
847 if(distance>maxPairDist){
848
849 // assert(false) : "distance="+distance+", spos="+spos+", dpos="+dpos+", sameStrandContigs="+sameStrandContigs+
850 // "\nsl.pos="+sl.pos+", sl.pnext="+sl.pnext+", strand="+sl.strand()+", nextStrand="+sl.mateStrand()+", left="+leftEdge
851 // +"\n"+sl;
852 // badCount++;
853 return;
854 }
855
856 distanceSum+=distance;
857
858 weight+=sl.mapq;
859 if(sameStrandContigs){
860 sameStrandCount++;
861 }else{
862 difStrandCount++;
863 }
864 // assert(false) : weight;
865 }
866
867 public float strandRatio() {
868 return Tools.max(sameStrandCount, difStrandCount)/(float)(sameStrandCount+difStrandCount);
869 }
870
871 public boolean sameStrand(){
872 return sameStrandCount>=difStrandCount;
873 }
874
875 @Override
876 public String toString(){
877 return "("+source.name+"->"+dest.name+", "+(leftEdge ? "left" : "right")+", weight="+weight+
878 ", same="+sameStrandCount+", dif="+difStrandCount+", bad="+badCount+")";
879 }
880
881 long count(){return sameStrandCount+difStrandCount;}
882
883 final Contig source;
884 final Contig dest;
885 long sameStrandCount;
886 long difStrandCount;
887 long distanceSum;
888 long weight;
889 long badCount;
890 final boolean leftEdge;
891 }
892
893 /*--------------------------------------------------------------*/
894 /*---------------- Fields ----------------*/
895 /*--------------------------------------------------------------*/
896
897 /** Primary input file path */
898 private String in=null;
899 /** Secondary input file path */
900 private String ref=null;
901
902 /** Primary output file path */
903 private String out=null;
904
905 /** Override input file extension */
906 private String extin=null;
907 /** Override output file extension */
908 private String extout=null;
909
910 private String insertList=null;
911
912 /*--------------------------------------------------------------*/
913
914 /** Number of reads processed */
915 protected long readsProcessed=0;
916 /** Number of bases processed */
917 protected long basesProcessed=0;
918
919 /** Number of reads retained */
920 protected long readsOut=0;
921 /** Number of bases retained */
922 protected long basesOut=0;
923
924 protected long scaffoldsOut=0;
925 protected long scaffoldLengthOut=0;
926
927 protected long totalInsertSum=0;
928 protected long totalInsertCount=0;
929 protected double totalAverageInsert;
930
931 /** Quit after processing this many input reads; -1 means no limit */
932 private long maxReads=-1;
933
934 boolean sameStrandPairs=false;
935
936 int gapsAdded=0;
937 long nsAdded=0;
938
939 /*--------------------------------------------------------------*/
940
941 /** Threads dedicated to reading the sam file */
942 private int streamerThreads=SamStreamer.DEFAULT_THREADS;
943
944 private boolean loadedRef=false;
945
946 private int minDepth=4;
947
948 private float minWeightRatio=0.8f;
949 private float minStrandRatio=0.8f;
950
951 private int scaffoldBreakNs=10;
952
953 private int maxPairDist=3000;
954
955 private int buckets=1000;
956 protected AtomicLongArray insertCounts=new AtomicLongArray(20000);
957 protected int[] insertByPercentile;
958
959 public final SamFilter samFilter=new SamFilter();
960
961 /** Uses full ref names */
962 public LinkedHashMap<String, Contig> refMap=new LinkedHashMap<String, Contig>();
963 /** Uses truncated ref names */
964 public LinkedHashMap<String, Contig> refMap2=new LinkedHashMap<String, Contig>();
965
966 /*--------------------------------------------------------------*/
967 /*---------------- Final Fields ----------------*/
968 /*--------------------------------------------------------------*/
969
970 /** Primary input file */
971 private final FileFormat ffin;
972 /** Secondary input file */
973 private final FileFormat ffref;
974
975 /** Primary output file */
976 private final FileFormat ffout;
977
978 @Override
979 public final ReadWriteLock rwlock() {return rwlock;}
980 private final ReadWriteLock rwlock=new ReentrantReadWriteLock();
981
982 /*--------------------------------------------------------------*/
983 /*---------------- Common Fields ----------------*/
984 /*--------------------------------------------------------------*/
985
986 /** Print status messages to this output stream */
987 private PrintStream outstream=System.err;
988 /** Print verbose messages */
989 public static boolean verbose=false;
990 /** True if an error was encountered */
991 public boolean errorState=false;
992 /** Overwrite existing output files */
993 private boolean overwrite=true;
994 /** Append to existing output files */
995 private boolean append=false;
996 /** Reads are output in input order */
997 private boolean ordered=false;
998
999 }