1 // ***************************************************************************
2 // BamMultiReader.cpp (c) 2010 Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // All rights reserved.
5 // ---------------------------------------------------------------------------
6 // Last modified: 3 September 2010 (DB)
7 // ---------------------------------------------------------------------------
8 // Uses BGZF routines were adapted from the bgzf.c code developed at the Broad
10 // ---------------------------------------------------------------------------
11 // Functionality for simultaneously reading multiple BAM files.
13 // This functionality allows applications to work on very large sets of files
14 // without requiring intermediate merge, sort, and index steps for each file
15 // subset. It also improves the performance of our merge system as it
16 // precludes the need to sort merged files.
17 // ***************************************************************************
30 #include "BamMultiReader.h"
31 using namespace BamTools;
34 // -----------------------------------------------------
35 // BamMultiReader implementation
36 // -----------------------------------------------------
39 BamMultiReader::BamMultiReader(void)
45 BamMultiReader::~BamMultiReader(void) {
49 // close the BAM files
50 void BamMultiReader::Close(void) {
52 // close all BAM readers and clean up pointers
53 vector<pair<BamReader*, BamAlignment*> >::iterator readerIter = readers.begin();
54 vector<pair<BamReader*, BamAlignment*> >::iterator readerEnd = readers.end();
55 for ( ; readerIter != readerEnd; ++readerIter) {
57 BamReader* reader = (*readerIter).first;
58 BamAlignment* alignment = (*readerIter).second;
61 if ( reader) reader->Close();
63 // delete reader pointer
67 // delete alignment pointer
72 // clear out the container
76 // saves index data to BAM index files (".bai"/".bti") where necessary, returns success/fail
77 bool BamMultiReader::CreateIndexes(bool useDefaultIndex) {
79 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
80 BamReader* reader = it->first;
81 result &= reader->CreateIndex(useDefaultIndex);
87 void BamMultiReader::DumpAlignmentIndex(void) {
88 for (AlignmentIndex::const_iterator it = alignments.begin(); it != alignments.end(); ++it) {
89 cerr << it->first.first << ":" << it->first.second << " " << it->second.first->GetFilename() << endl;
93 // makes a virtual, unified header for all the bam files in the multireader
94 const string BamMultiReader::GetHeaderText(void) const {
96 string mergedHeader = "";
97 map<string, bool> readGroups;
99 // foreach extraction entry (each BAM file)
100 for (vector<pair<BamReader*, BamAlignment*> >::const_iterator rs = readers.begin(); rs != readers.end(); ++rs) {
102 map<string, bool> currentFileReadGroups;
104 BamReader* reader = rs->first;
106 stringstream header(reader->GetHeaderText());
107 vector<string> lines;
109 while (getline(header, item))
110 lines.push_back(item);
112 for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
114 // get next line from header, skip if empty
115 string headerLine = *it;
116 if ( headerLine.empty() ) { continue; }
118 // if first file, save HD & SQ entries
119 if ( rs == readers.begin() ) {
120 if ( headerLine.find("@HD") == 0 || headerLine.find("@SQ") == 0) {
121 mergedHeader.append(headerLine.c_str());
122 mergedHeader.append(1, '\n');
126 // (for all files) append RG entries if they are unique
127 if ( headerLine.find("@RG") == 0 ) {
128 stringstream headerLineSs(headerLine);
129 string part, readGroupPart, readGroup;
130 while(std::getline(headerLineSs, part, '\t')) {
131 stringstream partSs(part);
133 std::getline(partSs, subtag, ':');
134 if (subtag == "ID") {
135 std::getline(partSs, readGroup, ':');
139 if (readGroups.find(readGroup) == readGroups.end()) { // prevents duplicate @RG entries
140 mergedHeader.append(headerLine.c_str() );
141 mergedHeader.append(1, '\n');
142 readGroups[readGroup] = true;
143 currentFileReadGroups[readGroup] = true;
145 // warn iff we are reading one file and discover duplicated @RG tags in the header
146 // otherwise, we emit no warning, as we might be merging multiple BAM files with identical @RG tags
147 if (currentFileReadGroups.find(readGroup) != currentFileReadGroups.end()) {
148 cerr << "WARNING: duplicate @RG tag " << readGroup
149 << " entry in header of " << reader->GetFilename() << endl;
156 // return merged header text
160 // get next alignment among all files
161 bool BamMultiReader::GetNextAlignment(BamAlignment& nextAlignment) {
163 // bail out if we are at EOF in all files, means no more alignments to process
164 if (!HasOpenReaders())
167 // when all alignments have stepped into a new target sequence, update our
168 // current reference sequence id
171 // our lowest alignment and reader will be at the front of our alignment index
172 BamAlignment* alignment = alignments.begin()->second.second;
173 BamReader* reader = alignments.begin()->second.first;
175 // now that we have the lowest alignment in the set, save it by copy to our argument
176 nextAlignment = BamAlignment(*alignment);
178 // remove this alignment index entry from our alignment index
179 alignments.erase(alignments.begin());
181 // and add another entry if we can get another alignment from the reader
182 if (reader->GetNextAlignment(*alignment)) {
183 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
184 make_pair(reader, alignment)));
185 } else { // do nothing
186 //cerr << "reached end of file " << lowestReader->GetFilename() << endl;
193 // get next alignment among all files without parsing character data from alignments
194 bool BamMultiReader::GetNextAlignmentCore(BamAlignment& nextAlignment) {
196 // bail out if we are at EOF in all files, means no more alignments to process
197 if (!HasOpenReaders())
200 // when all alignments have stepped into a new target sequence, update our
201 // current reference sequence id
204 // our lowest alignment and reader will be at the front of our alignment index
205 BamAlignment* alignment = alignments.begin()->second.second;
206 BamReader* reader = alignments.begin()->second.first;
208 // now that we have the lowest alignment in the set, save it by copy to our argument
209 nextAlignment = BamAlignment(*alignment);
210 //memcpy(&nextAlignment, alignment, sizeof(BamAlignment));
212 // remove this alignment index entry from our alignment index
213 alignments.erase(alignments.begin());
215 // and add another entry if we can get another alignment from the reader
216 if (reader->GetNextAlignmentCore(*alignment)) {
217 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
218 make_pair(reader, alignment)));
219 } else { // do nothing
220 //cerr << "reached end of file " << lowestReader->GetFilename() << endl;
227 // ---------------------------------------------------------------------------------------
229 // NB: The following GetReferenceX() functions assume that we have identical
230 // references for all BAM files. We enforce this by invoking the above
231 // validation function (ValidateReaders) to verify that our reference data
232 // is the same across all files on Open, so we will not encounter a situation
233 // in which there is a mismatch and we are still live.
235 // ---------------------------------------------------------------------------------------
237 // returns the number of reference sequences
238 const int BamMultiReader::GetReferenceCount(void) const {
239 return readers.front().first->GetReferenceCount();
242 // returns vector of reference objects
243 const BamTools::RefVector BamMultiReader::GetReferenceData(void) const {
244 return readers.front().first->GetReferenceData();
247 // returns refID from reference name
248 const int BamMultiReader::GetReferenceID(const string& refName) const {
249 return readers.front().first->GetReferenceID(refName);
252 // ---------------------------------------------------------------------------------------
254 // checks if any readers still have alignments
255 bool BamMultiReader::HasOpenReaders() {
256 return alignments.size() > 0;
259 // returns whether underlying BAM readers ALL have an index loaded
260 // this is useful to indicate whether Jump() or SetRegion() are possible
261 bool BamMultiReader::IsIndexLoaded(void) const {
263 vector<pair<BamReader*, BamAlignment*> >::const_iterator readerIter = readers.begin();
264 vector<pair<BamReader*, BamAlignment*> >::const_iterator readerEnd = readers.end();
265 for ( ; readerIter != readerEnd; ++readerIter ) {
266 const BamReader* reader = (*readerIter).first;
267 if ( reader ) ok &= reader->IsIndexLoaded();
272 // jumps to specified region(refID, leftBound) in BAM files, returns success/fail
273 bool BamMultiReader::Jump(int refID, int position) {
275 //if ( References.at(refID).RefHasAlignments && (position <= References.at(refID).RefLength) ) {
276 CurrentRefID = refID;
277 CurrentLeft = position;
280 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
281 BamReader* reader = it->first;
282 result &= reader->Jump(refID, position);
284 cerr << "ERROR: could not jump " << reader->GetFilename() << " to " << refID << ":" << position << endl;
288 if (result) UpdateAlignments();
293 bool BamMultiReader::Open(const vector<string> filenames, bool openIndexes, bool coreMode, bool useDefaultIndex) {
295 // for filename in filenames
296 fileNames = filenames; // save filenames in our multireader
297 for (vector<string>::const_iterator it = filenames.begin(); it != filenames.end(); ++it) {
299 const string filename = *it;
300 BamReader* reader = new BamReader;
302 bool openedOK = true;
305 // leave index filename empty
306 // this allows BamReader & BamIndex to search for any available
307 // useDefaultIndex gives hint to prefer BAI over BTI
308 openedOK = reader->Open(filename, "", true, useDefaultIndex);
311 // ignoring index file(s)
312 else openedOK = reader->Open(filename);
314 // if file opened ok, check that it can be read
318 BamAlignment* alignment = new BamAlignment;
319 fileOK &= ( coreMode ? reader->GetNextAlignmentCore(*alignment) : reader->GetNextAlignment(*alignment) );
322 readers.push_back(make_pair(reader, alignment)); // store pointers to our readers for cleanup
323 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
324 make_pair(reader, alignment)));
326 cerr << "WARNING: could not read first alignment in " << filename << ", ignoring file" << endl;
327 // if only file available & could not be read, return failure
328 if ( filenames.size() == 1 ) return false;
332 // TODO; any further error handling when openedOK is false ??
337 // files opened ok, at least one alignment could be read,
338 // now need to check that all files use same reference data
343 void BamMultiReader::PrintFilenames(void) {
344 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
345 BamReader* reader = it->first;
346 cout << reader->GetFilename() << endl;
350 // returns BAM file pointers to beginning of alignment data
351 bool BamMultiReader::Rewind(void) {
353 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
354 BamReader* reader = it->first;
355 result &= reader->Rewind();
360 bool BamMultiReader::SetRegion(const int& leftRefID, const int& leftPosition, const int& rightRefID, const int& rightPosition) {
361 BamRegion region(leftRefID, leftPosition, rightRefID, rightPosition);
362 return SetRegion(region);
365 bool BamMultiReader::SetRegion(const BamRegion& region) {
369 // NB: While it may make sense to track readers in which we can
370 // successfully SetRegion, In practice a failure of SetRegion means "no
371 // alignments here." It makes sense to simply accept the failure,
372 // UpdateAlignments(), and continue.
374 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
375 it->first->SetRegion(region);
382 void BamMultiReader::UpdateAlignments(void) {
385 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
386 BamReader* br = it->first;
387 BamAlignment* ba = it->second;
388 if (br->GetNextAlignment(*ba)) {
389 alignments.insert(make_pair(make_pair(ba->RefID, ba->Position),
392 // assume BamReader end of region / EOF
397 // updates the reference id stored in the BamMultiReader
398 // to reflect the current state of the readers
399 void BamMultiReader::UpdateReferenceID(void) {
400 // the alignments are sorted by position, so the first alignment will always have the lowest reference ID
401 if (alignments.begin()->second.second->RefID != CurrentRefID) {
402 // get the next reference id
403 // while there aren't any readers at the next ref id
404 // increment the ref id
405 int nextRefID = CurrentRefID;
406 while (alignments.begin()->second.second->RefID != nextRefID) {
409 //cerr << "updating reference id from " << CurrentRefID << " to " << nextRefID << endl;
410 CurrentRefID = nextRefID;
414 // ValidateReaders checks that all the readers point to BAM files representing
415 // alignments against the same set of reference sequences, and that the
416 // sequences are identically ordered. If these checks fail the operation of
417 // the multireader is undefined, so we force program exit.
418 void BamMultiReader::ValidateReaders(void) const {
419 int firstRefCount = readers.front().first->GetReferenceCount();
420 BamTools::RefVector firstRefData = readers.front().first->GetReferenceData();
421 for (vector<pair<BamReader*, BamAlignment*> >::const_iterator it = readers.begin(); it != readers.end(); ++it) {
422 BamReader* reader = it->first;
423 BamTools::RefVector currentRefData = reader->GetReferenceData();
424 BamTools::RefVector::const_iterator f = firstRefData.begin();
425 BamTools::RefVector::const_iterator c = currentRefData.begin();
426 if (reader->GetReferenceCount() != firstRefCount || firstRefData.size() != currentRefData.size()) {
427 cerr << "ERROR: mismatched number of references in " << reader->GetFilename()
428 << " expected " << firstRefCount
429 << " reference sequences but only found " << reader->GetReferenceCount() << endl;
432 // this will be ok; we just checked above that we have identically-sized sets of references
433 // here we simply check if they are all, in fact, equal in content
434 while (f != firstRefData.end()) {
435 if (f->RefName != c->RefName || f->RefLength != c->RefLength) {
436 cerr << "ERROR: mismatched references found in " << reader->GetFilename()
437 << " expected: " << endl;
438 for (BamTools::RefVector::const_iterator a = firstRefData.begin(); a != firstRefData.end(); ++a)
439 cerr << a->RefName << " " << a->RefLength << endl;
440 cerr << "but found: " << endl;
441 for (BamTools::RefVector::const_iterator a = currentRefData.begin(); a != currentRefData.end(); ++a)
442 cerr << a->RefName << " " << a->RefLength << endl;