]> git.donarmstrong.com Git - bamtools.git/blobdiff - src/api/BamMultiReader.cpp
Cleaned up index file handling throughout toolkit. Did this by adding a FileExists...
[bamtools.git] / src / api / BamMultiReader.cpp
index 005b0b0adc7c6c22c12f4317791785803a974bd6..6de97dc9e7f15411e887ea1c97a62d41fe1ed9d5 100644 (file)
@@ -3,7 +3,7 @@
 // Marth Lab, Department of Biology, Boston College
 // All rights reserved.
 // ---------------------------------------------------------------------------
-// Last modified: 20 July 2010 (DB)
+// Last modified: 3 September 2010 (DB)
 // ---------------------------------------------------------------------------
 // Uses BGZF routines were adapted from the bgzf.c code developed at the Broad
 // Institute.
 
 // C++ includes
 #include <algorithm>
+#include <fstream>
+#include <iostream>
 #include <iterator>
+#include <sstream>
 #include <string>
 #include <vector>
-#include <iostream>
-#include <sstream>
 
 // BamTools includes
 #include "BGZF.h"
 using namespace BamTools;
 using namespace std;
 
+namespace BamTools {
+
+bool FileExists(const string& filename) {
+    ifstream f(filename.c_str(), ifstream::in);
+    return !f.fail();
+}
+  
+} // namespace BamTools
+
 // -----------------------------------------------------
 // BamMultiReader implementation
 // -----------------------------------------------------
@@ -42,42 +52,118 @@ BamMultiReader::BamMultiReader(void)
 
 // destructor
 BamMultiReader::~BamMultiReader(void) {
-    Close(); // close the bam files
-    // clean up reader objects
-    for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
-        delete it->first;
-        delete it->second;
-    }
+    Close(); 
 }
 
 // close the BAM files
 void BamMultiReader::Close(void) {
+  
+    // close all BAM readers and clean up pointers
+    vector<pair<BamReader*, BamAlignment*> >::iterator readerIter = readers.begin();
+    vector<pair<BamReader*, BamAlignment*> >::iterator readerEnd  = readers.end();
+    for ( ; readerIter != readerEnd; ++readerIter) {
+      
+        BamReader* reader = (*readerIter).first;
+        BamAlignment* alignment = (*readerIter).second;
+        
+        // close the reader
+        if ( reader) reader->Close();  
+        
+        // delete reader pointer
+        delete reader;
+        reader = 0;
+
+        // delete alignment pointer
+        delete alignment;
+        alignment = 0;
+    }
+
+    // clear out the container
+    readers.clear();
+}
+
+// saves index data to BAM index files (".bai"/".bti") where necessary, returns success/fail
+bool BamMultiReader::CreateIndexes(bool useDefaultIndex) {
+    bool result = true;
     for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
         BamReader* reader = it->first;
-        reader->Close();  // close the reader
+        result &= reader->CreateIndex(useDefaultIndex);
     }
+    return result;
 }
 
-// updates the reference id stored in the BamMultiReader
-// to reflect the current state of the readers
-void BamMultiReader::UpdateReferenceID(void) {
-    // the alignments are sorted by position, so the first alignment will always have the lowest reference ID
-    if (alignments.begin()->second.second->RefID != CurrentRefID) {
-        // get the next reference id
-        // while there aren't any readers at the next ref id
-        // increment the ref id
-        int nextRefID = CurrentRefID;
-        while (alignments.begin()->second.second->RefID != nextRefID) {
-            ++nextRefID;
-        }
-        //cerr << "updating reference id from " << CurrentRefID << " to " << nextRefID << endl;
-        CurrentRefID = nextRefID;
+// for debugging
+void BamMultiReader::DumpAlignmentIndex(void) {
+    for (AlignmentIndex::const_iterator it = alignments.begin(); it != alignments.end(); ++it) {
+        cerr << it->first.first << ":" << it->first.second << " " << it->second.first->GetFilename() << endl;
     }
 }
 
-// checks if any readers still have alignments
-bool BamMultiReader::HasOpenReaders() {
-    return alignments.size() > 0;
+// makes a virtual, unified header for all the bam files in the multireader
+const string BamMultiReader::GetHeaderText(void) const {
+
+    string mergedHeader = "";
+    map<string, bool> readGroups;
+
+    // foreach extraction entry (each BAM file)
+    for (vector<pair<BamReader*, BamAlignment*> >::const_iterator rs = readers.begin(); rs != readers.end(); ++rs) {
+
+        map<string, bool> currentFileReadGroups;
+
+        BamReader* reader = rs->first;
+
+        stringstream header(reader->GetHeaderText());
+        vector<string> lines;
+        string item;
+        while (getline(header, item))
+            lines.push_back(item);
+
+        for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
+
+            // get next line from header, skip if empty
+            string headerLine = *it;
+            if ( headerLine.empty() ) { continue; }
+
+            // if first file, save HD & SQ entries
+            if ( rs == readers.begin() ) {
+                if ( headerLine.find("@HD") == 0 || headerLine.find("@SQ") == 0) {
+                    mergedHeader.append(headerLine.c_str());
+                    mergedHeader.append(1, '\n');
+                }
+            }
+
+            // (for all files) append RG entries if they are unique
+            if ( headerLine.find("@RG") == 0 ) {
+                stringstream headerLineSs(headerLine);
+                string part, readGroupPart, readGroup;
+                while(std::getline(headerLineSs, part, '\t')) {
+                    stringstream partSs(part);
+                    string subtag;
+                    std::getline(partSs, subtag, ':');
+                    if (subtag == "ID") {
+                        std::getline(partSs, readGroup, ':');
+                        break;
+                    }
+                }
+                if (readGroups.find(readGroup) == readGroups.end()) { // prevents duplicate @RG entries
+                    mergedHeader.append(headerLine.c_str() );
+                    mergedHeader.append(1, '\n');
+                    readGroups[readGroup] = true;
+                    currentFileReadGroups[readGroup] = true;
+                } else {
+                    // warn iff we are reading one file and discover duplicated @RG tags in the header
+                    // otherwise, we emit no warning, as we might be merging multiple BAM files with identical @RG tags
+                    if (currentFileReadGroups.find(readGroup) != currentFileReadGroups.end()) {
+                        cerr << "WARNING: duplicate @RG tag " << readGroup 
+                            << " entry in header of " << reader->GetFilename() << endl;
+                    }
+                }
+            }
+        }
+    }
+
+    // return merged header text
+    return mergedHeader;
 }
 
 // get next alignment among all files
@@ -147,6 +233,51 @@ bool BamMultiReader::GetNextAlignmentCore(BamAlignment& nextAlignment) {
 
 }
 
+// ---------------------------------------------------------------------------------------
+//
+// NB: The following GetReferenceX() functions assume that we have identical 
+// references for all BAM files.  We enforce this by invoking the above 
+// validation function (ValidateReaders) to verify that our reference data 
+// is the same across all files on Open, so we will not encounter a situation 
+// in which there is a mismatch and we are still live.
+//
+// ---------------------------------------------------------------------------------------
+
+// returns the number of reference sequences
+const int BamMultiReader::GetReferenceCount(void) const {
+    return readers.front().first->GetReferenceCount();
+}
+
+// returns vector of reference objects
+const BamTools::RefVector BamMultiReader::GetReferenceData(void) const {
+    return readers.front().first->GetReferenceData();
+}
+
+// returns refID from reference name
+const int BamMultiReader::GetReferenceID(const string& refName) const { 
+    return readers.front().first->GetReferenceID(refName);
+}
+
+// ---------------------------------------------------------------------------------------
+
+// checks if any readers still have alignments
+bool BamMultiReader::HasOpenReaders() {
+    return alignments.size() > 0;
+}
+
+// returns whether underlying BAM readers ALL have an index loaded
+// this is useful to indicate whether Jump() or SetRegion() are possible
+bool BamMultiReader::IsIndexLoaded(void) const {
+    bool ok = true;
+    vector<pair<BamReader*, BamAlignment*> >::const_iterator readerIter = readers.begin();
+    vector<pair<BamReader*, BamAlignment*> >::const_iterator readerEnd  = readers.end();
+    for ( ; readerIter != readerEnd; ++readerIter ) {
+        const BamReader* reader = (*readerIter).first;
+        if ( reader ) ok &= reader->IsIndexLoaded();
+    }
+    return ok;
+}
+
 // jumps to specified region(refID, leftBound) in BAM files, returns success/fail
 bool BamMultiReader::Jump(int refID, int position) {
 
@@ -167,77 +298,44 @@ bool BamMultiReader::Jump(int refID, int position) {
     return result;
 }
 
-bool BamMultiReader::SetRegion(const int& leftRefID, const int& leftPosition, const int& rightRefID, const int& rightPosition) {
-
-    BamRegion region(leftRefID, leftPosition, rightRefID, rightPosition);
-
-    return SetRegion(region);
-
-}
-
-bool BamMultiReader::SetRegion(const BamRegion& region) {
-
-    Region = region;
-
-    // NB: While it may make sense to track readers in which we can
-    // successfully SetRegion, In practice a failure of SetRegion means "no
-    // alignments here."  It makes sense to simply accept the failure,
-    // UpdateAlignments(), and continue.
-
-    for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
-        it->first->SetRegion(region);
-    }
-
-    UpdateAlignments();
-
-    return true;
-
-}
-
-void BamMultiReader::UpdateAlignments(void) {
-    // Update Alignments
-    alignments.clear();
-    for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
-        BamReader* br = it->first;
-        BamAlignment* ba = it->second;
-        if (br->GetNextAlignment(*ba)) {
-            alignments.insert(make_pair(make_pair(ba->RefID, ba->Position), 
-                                        make_pair(br, ba)));
-        } else {
-            // assume BamReader end of region / EOF
-        }
-    }
-}
-
 // opens BAM files
 bool BamMultiReader::Open(const vector<string> filenames, bool openIndexes, bool coreMode, bool useDefaultIndex) {
     
     // for filename in filenames
     fileNames = filenames; // save filenames in our multireader
     for (vector<string>::const_iterator it = filenames.begin(); it != filenames.end(); ++it) {
-        string filename = *it;
+        
+        const string filename = *it;
         BamReader* reader = new BamReader;
 
         bool openedOK = true;
         if (openIndexes) {
-            if (useDefaultIndex)
-                openedOK = reader->Open(filename, filename + ".bai");
-            else 
-                openedOK = reader->Open(filename, filename + ".bti");
-        } else {
-            openedOK = reader->Open(filename); // for merging, jumping is disallowed
-        }
+          
+            const string defaultIndexFilename  = filename + ".bai";
+            const string bamToolsIndexFilename = filename + ".bti";
+            
+            // if default BAM index requested and one exists
+            if ( useDefaultIndex && FileExists(defaultIndexFilename) )
+                openedOK = reader->Open(filename, defaultIndexFilename);
+            
+            // else see if BamTools index exists
+            else if ( FileExists(bamToolsIndexFilename) )
+                openedOK = reader->Open(filename, bamToolsIndexFilename);
+            
+            // else none exist... just open without
+            else
+                openedOK = reader->Open(filename);
+        } 
+        
+        // ignoring index file(s)
+        else openedOK = reader->Open(filename); 
         
         // if file opened ok, check that it can be read
         if ( openedOK ) {
            
             bool fileOK = true;
             BamAlignment* alignment = new BamAlignment;
-            if (coreMode) {
-                fileOK &= reader->GetNextAlignmentCore(*alignment);
-            } else {
-                fileOK &= reader->GetNextAlignment(*alignment);
-            }
+            fileOK &= ( coreMode ? reader->GetNextAlignmentCore(*alignment) : reader->GetNextAlignment(*alignment) );
             
             if (fileOK) {
                 readers.push_back(make_pair(reader, alignment)); // store pointers to our readers for cleanup
@@ -248,10 +346,9 @@ bool BamMultiReader::Open(const vector<string> filenames, bool openIndexes, bool
                 // if only file available & could not be read, return failure
                 if ( filenames.size() == 1 ) return false;
             }
-        
         } 
        
-        // TODO; any more error handling on openedOK ??
+        // TODO; any more error handling when openedOKvis false ??
         else 
             return false;
     }
@@ -269,13 +366,6 @@ void BamMultiReader::PrintFilenames(void) {
     }
 }
 
-// for debugging
-void BamMultiReader::DumpAlignmentIndex(void) {
-    for (AlignmentIndex::const_iterator it = alignments.begin(); it != alignments.end(); ++it) {
-        cerr << it->first.first << ":" << it->first.second << " " << it->second.first->GetFilename() << endl;
-    }
-}
-
 // returns BAM file pointers to beginning of alignment data
 bool BamMultiReader::Rewind(void) { 
     bool result = true;
@@ -286,81 +376,58 @@ bool BamMultiReader::Rewind(void) {
     return result;
 }
 
-// saves index data to BAM index files (".bai"/".bti") where necessary, returns success/fail
-bool BamMultiReader::CreateIndexes(bool useDefaultIndex) {
-    bool result = true;
-    for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
-        BamReader* reader = it->first;
-        result &= reader->CreateIndex(useDefaultIndex);
-    }
-    return result;
+bool BamMultiReader::SetRegion(const int& leftRefID, const int& leftPosition, const int& rightRefID, const int& rightPosition) {
+    BamRegion region(leftRefID, leftPosition, rightRefID, rightPosition);
+    return SetRegion(region);
 }
 
-// makes a virtual, unified header for all the bam files in the multireader
-const string BamMultiReader::GetHeaderText(void) const {
-
-    string mergedHeader = "";
-    map<string, bool> readGroups;
-
-    // foreach extraction entry (each BAM file)
-    for (vector<pair<BamReader*, BamAlignment*> >::const_iterator rs = readers.begin(); rs != readers.end(); ++rs) {
-
-        map<string, bool> currentFileReadGroups;
-
-        BamReader* reader = rs->first;
+bool BamMultiReader::SetRegion(const BamRegion& region) {
 
-        stringstream header(reader->GetHeaderText());
-        vector<string> lines;
-        string item;
-        while (getline(header, item))
-            lines.push_back(item);
+    Region = region;
 
-        for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
+    // NB: While it may make sense to track readers in which we can
+    // successfully SetRegion, In practice a failure of SetRegion means "no
+    // alignments here."  It makes sense to simply accept the failure,
+    // UpdateAlignments(), and continue.
 
-            // get next line from header, skip if empty
-            string headerLine = *it;
-            if ( headerLine.empty() ) { continue; }
+    for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
+        it->first->SetRegion(region);
+    }
 
-            // if first file, save HD & SQ entries
-            if ( rs == readers.begin() ) {
-                if ( headerLine.find("@HD") == 0 || headerLine.find("@SQ") == 0) {
-                    mergedHeader.append(headerLine.c_str());
-                    mergedHeader.append(1, '\n');
-                }
-            }
+    UpdateAlignments();
+    return true;
+}
 
-            // (for all files) append RG entries if they are unique
-            if ( headerLine.find("@RG") == 0 ) {
-                stringstream headerLineSs(headerLine);
-                string part, readGroupPart, readGroup;
-                while(std::getline(headerLineSs, part, '\t')) {
-                    stringstream partSs(part);
-                    string subtag;
-                    std::getline(partSs, subtag, ':');
-                    if (subtag == "ID") {
-                        std::getline(partSs, readGroup, ':');
-                        break;
-                    }
-                }
-                if (readGroups.find(readGroup) == readGroups.end()) { // prevents duplicate @RG entries
-                    mergedHeader.append(headerLine.c_str() );
-                    mergedHeader.append(1, '\n');
-                    readGroups[readGroup] = true;
-                    currentFileReadGroups[readGroup] = true;
-                } else {
-                    // warn iff we are reading one file and discover duplicated @RG tags in the header
-                    // otherwise, we emit no warning, as we might be merging multiple BAM files with identical @RG tags
-                    if (currentFileReadGroups.find(readGroup) != currentFileReadGroups.end()) {
-                        cerr << "WARNING: duplicate @RG tag " << readGroup 
-                            << " entry in header of " << reader->GetFilename() << endl;
-                    }
-                }
-            }
+void BamMultiReader::UpdateAlignments(void) {
+    // Update Alignments
+    alignments.clear();
+    for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
+        BamReader* br = it->first;
+        BamAlignment* ba = it->second;
+        if (br->GetNextAlignment(*ba)) {
+            alignments.insert(make_pair(make_pair(ba->RefID, ba->Position), 
+                                        make_pair(br, ba)));
+        } else {
+            // assume BamReader end of region / EOF
         }
     }
+}
 
-    // return merged header text
-    return mergedHeader;
+// updates the reference id stored in the BamMultiReader
+// to reflect the current state of the readers
+void BamMultiReader::UpdateReferenceID(void) {
+    // the alignments are sorted by position, so the first alignment will always have the lowest reference ID
+    if (alignments.begin()->second.second->RefID != CurrentRefID) {
+        // get the next reference id
+        // while there aren't any readers at the next ref id
+        // increment the ref id
+        int nextRefID = CurrentRefID;
+        while (alignments.begin()->second.second->RefID != nextRefID) {
+            ++nextRefID;
+        }
+        //cerr << "updating reference id from " << CurrentRefID << " to " << nextRefID << endl;
+        CurrentRefID = nextRefID;
+    }
 }
 
 // ValidateReaders checks that all the readers point to BAM files representing
@@ -398,23 +465,3 @@ void BamMultiReader::ValidateReaders(void) const {
         }
     }
 }
-
-// NB: The following functions assume that we have identical references for all
-// BAM files.  We enforce this by invoking the above validation function
-// (ValidateReaders) to verify that our reference data is the same across all
-// files on Open, so we will not encounter a situation in which there is a
-// mismatch and we are still live.
-
-// returns the number of reference sequences
-const int BamMultiReader::GetReferenceCount(void) const {
-    return readers.front().first->GetReferenceCount();
-}
-
-// returns vector of reference objects
-const BamTools::RefVector BamMultiReader::GetReferenceData(void) const {
-    return readers.front().first->GetReferenceData();
-}
-
-const int BamMultiReader::GetReferenceID(const string& refName) const { 
-    return readers.front().first->GetReferenceID(refName);
-}