1 // ***************************************************************************
2 // BamMultiReader.cpp (c) 2010 Erik Garrison, Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // All rights reserved.
5 // ---------------------------------------------------------------------------
6 // Last modified: 18 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 // ***************************************************************************
27 #include "BamMultiReader.h"
28 using namespace BamTools;
31 // -----------------------------------------------------
32 // BamMultiReader implementation
33 // -----------------------------------------------------
36 BamMultiReader::BamMultiReader(void)
42 BamMultiReader::~BamMultiReader(void) {
46 // close the BAM files
47 void BamMultiReader::Close(void) {
49 // close all BAM readers and clean up pointers
50 vector<pair<BamReader*, BamAlignment*> >::iterator readerIter = readers.begin();
51 vector<pair<BamReader*, BamAlignment*> >::iterator readerEnd = readers.end();
52 for ( ; readerIter != readerEnd; ++readerIter) {
54 BamReader* reader = (*readerIter).first;
55 BamAlignment* alignment = (*readerIter).second;
58 if ( reader) reader->Close();
60 // delete reader pointer
64 // delete alignment pointer
69 // clear out the container
73 // saves index data to BAM index files (".bai"/".bti") where necessary, returns success/fail
74 bool BamMultiReader::CreateIndexes(bool useStandardIndex) {
76 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
77 BamReader* reader = it->first;
78 result &= reader->CreateIndex(useStandardIndex);
83 // sets the index caching mode on the readers
84 void BamMultiReader::SetIndexCacheMode(const BamIndex::BamIndexCacheMode mode) {
85 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
86 BamReader* reader = it->first;
87 reader->SetIndexCacheMode(mode);
92 void BamMultiReader::DumpAlignmentIndex(void) {
93 for (AlignmentIndex::const_iterator it = alignments.begin(); it != alignments.end(); ++it) {
94 cerr << it->first.first << ":" << it->first.second << " " << it->second.first->GetFilename() << endl;
98 // makes a virtual, unified header for all the bam files in the multireader
99 const string BamMultiReader::GetHeaderText(void) const {
101 string mergedHeader = "";
102 map<string, bool> readGroups;
104 // foreach extraction entry (each BAM file)
105 for (vector<pair<BamReader*, BamAlignment*> >::const_iterator rs = readers.begin(); rs != readers.end(); ++rs) {
107 BamReader* reader = rs->first;
108 string headerText = reader->GetHeaderText();
109 if ( headerText.empty() ) continue;
111 map<string, bool> currentFileReadGroups;
112 stringstream header(headerText);
113 vector<string> lines;
115 while (getline(header, item))
116 lines.push_back(item);
118 for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
120 // get next line from header, skip if empty
121 string headerLine = *it;
122 if ( headerLine.empty() ) { continue; }
124 // if first file, save HD & SQ entries
125 if ( rs == readers.begin() ) {
126 if ( headerLine.find("@HD") == 0 || headerLine.find("@SQ") == 0) {
127 mergedHeader.append(headerLine.c_str());
128 mergedHeader.append(1, '\n');
132 // (for all files) append RG entries if they are unique
133 if ( headerLine.find("@RG") == 0 ) {
134 stringstream headerLineSs(headerLine);
135 string part, readGroupPart, readGroup;
136 while(std::getline(headerLineSs, part, '\t')) {
137 stringstream partSs(part);
139 std::getline(partSs, subtag, ':');
140 if (subtag == "ID") {
141 std::getline(partSs, readGroup, ':');
145 if (readGroups.find(readGroup) == readGroups.end()) { // prevents duplicate @RG entries
146 mergedHeader.append(headerLine.c_str() );
147 mergedHeader.append(1, '\n');
148 readGroups[readGroup] = true;
149 currentFileReadGroups[readGroup] = true;
151 // warn iff we are reading one file and discover duplicated @RG tags in the header
152 // otherwise, we emit no warning, as we might be merging multiple BAM files with identical @RG tags
153 if (currentFileReadGroups.find(readGroup) != currentFileReadGroups.end()) {
154 cerr << "WARNING: duplicate @RG tag " << readGroup
155 << " entry in header of " << reader->GetFilename() << endl;
162 // return merged header text
166 // get next alignment among all files
167 bool BamMultiReader::GetNextAlignment(BamAlignment& nextAlignment) {
169 // bail out if we are at EOF in all files, means no more alignments to process
170 if (!HasOpenReaders())
173 // when all alignments have stepped into a new target sequence, update our
174 // current reference sequence id
177 // our lowest alignment and reader will be at the front of our alignment index
178 BamAlignment* alignment = alignments.begin()->second.second;
179 BamReader* reader = alignments.begin()->second.first;
181 // now that we have the lowest alignment in the set, save it by copy to our argument
182 nextAlignment = BamAlignment(*alignment);
184 // remove this alignment index entry from our alignment index
185 alignments.erase(alignments.begin());
187 // and add another entry if we can get another alignment from the reader
188 if (reader->GetNextAlignment(*alignment)) {
189 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
190 make_pair(reader, alignment)));
191 } else { // do nothing
192 //cerr << "reached end of file " << lowestReader->GetFilename() << endl;
199 // get next alignment among all files without parsing character data from alignments
200 bool BamMultiReader::GetNextAlignmentCore(BamAlignment& nextAlignment) {
202 // bail out if we are at EOF in all files, means no more alignments to process
203 if (!HasOpenReaders())
206 // when all alignments have stepped into a new target sequence, update our
207 // current reference sequence id
210 // our lowest alignment and reader will be at the front of our alignment index
211 BamAlignment* alignment = alignments.begin()->second.second;
212 BamReader* reader = alignments.begin()->second.first;
214 // now that we have the lowest alignment in the set, save it by copy to our argument
215 nextAlignment = BamAlignment(*alignment);
216 //memcpy(&nextAlignment, alignment, sizeof(BamAlignment));
218 // remove this alignment index entry from our alignment index
219 alignments.erase(alignments.begin());
221 // and add another entry if we can get another alignment from the reader
222 if (reader->GetNextAlignmentCore(*alignment)) {
223 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
224 make_pair(reader, alignment)));
225 } else { // do nothing
226 //cerr << "reached end of file " << lowestReader->GetFilename() << endl;
233 // ---------------------------------------------------------------------------------------
235 // NB: The following GetReferenceX() functions assume that we have identical
236 // references for all BAM files. We enforce this by invoking the above
237 // validation function (ValidateReaders) to verify that our reference data
238 // is the same across all files on Open, so we will not encounter a situation
239 // in which there is a mismatch and we are still live.
241 // ---------------------------------------------------------------------------------------
243 // returns the number of reference sequences
244 const int BamMultiReader::GetReferenceCount(void) const {
245 return readers.front().first->GetReferenceCount();
248 // returns vector of reference objects
249 const BamTools::RefVector BamMultiReader::GetReferenceData(void) const {
250 return readers.front().first->GetReferenceData();
253 // returns refID from reference name
254 const int BamMultiReader::GetReferenceID(const string& refName) const {
255 return readers.front().first->GetReferenceID(refName);
258 // ---------------------------------------------------------------------------------------
260 // checks if any readers still have alignments
261 bool BamMultiReader::HasOpenReaders() {
262 return alignments.size() > 0;
265 // returns whether underlying BAM readers ALL have an index loaded
266 // this is useful to indicate whether Jump() or SetRegion() are possible
267 bool BamMultiReader::IsIndexLoaded(void) const {
269 vector<pair<BamReader*, BamAlignment*> >::const_iterator readerIter = readers.begin();
270 vector<pair<BamReader*, BamAlignment*> >::const_iterator readerEnd = readers.end();
271 for ( ; readerIter != readerEnd; ++readerIter ) {
272 const BamReader* reader = (*readerIter).first;
273 if ( reader ) ok &= reader->IsIndexLoaded();
278 // jumps to specified region(refID, leftBound) in BAM files, returns success/fail
279 bool BamMultiReader::Jump(int refID, int position) {
281 //if ( References.at(refID).RefHasAlignments && (position <= References.at(refID).RefLength) ) {
282 CurrentRefID = refID;
283 CurrentLeft = position;
286 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
287 BamReader* reader = it->first;
288 result &= reader->Jump(refID, position);
290 cerr << "ERROR: could not jump " << reader->GetFilename() << " to " << refID << ":" << position << endl;
294 if (result) UpdateAlignments();
299 bool BamMultiReader::Open(const vector<string>& filenames, bool openIndexes, bool coreMode, bool preferStandardIndex) {
301 // for filename in filenames
302 fileNames = filenames; // save filenames in our multireader
303 for (vector<string>::const_iterator it = filenames.begin(); it != filenames.end(); ++it) {
305 const string filename = *it;
306 BamReader* reader = new BamReader;
308 bool openedOK = true;
311 // leave index filename empty
312 // this allows BamReader & BamIndex to search for any available
313 // useStandardIndex gives hint to prefer BAI over BTI
314 openedOK = reader->Open(filename, "", true, preferStandardIndex);
317 // ignoring index file(s)
318 else openedOK = reader->Open(filename);
320 // if file opened ok, check that it can be read
324 BamAlignment* alignment = new BamAlignment;
325 fileOK &= ( coreMode ? reader->GetNextAlignmentCore(*alignment) : reader->GetNextAlignment(*alignment) );
328 readers.push_back(make_pair(reader, alignment)); // store pointers to our readers for cleanup
329 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
330 make_pair(reader, alignment)));
332 cerr << "WARNING: could not read first alignment in " << filename << ", ignoring file" << endl;
333 // if only file available & could not be read, return failure
334 if ( filenames.size() == 1 ) return false;
338 // TODO; any further error handling when openedOK is false ??
343 // files opened ok, at least one alignment could be read,
344 // now need to check that all files use same reference data
349 void BamMultiReader::PrintFilenames(void) {
350 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
351 BamReader* reader = it->first;
352 cout << reader->GetFilename() << endl;
356 // returns BAM file pointers to beginning of alignment data
357 bool BamMultiReader::Rewind(void) {
359 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
360 BamReader* reader = it->first;
361 result &= reader->Rewind();
366 bool BamMultiReader::SetRegion(const int& leftRefID, const int& leftPosition, const int& rightRefID, const int& rightPosition) {
367 BamRegion region(leftRefID, leftPosition, rightRefID, rightPosition);
368 return SetRegion(region);
371 bool BamMultiReader::SetRegion(const BamRegion& region) {
375 // NB: While it may make sense to track readers in which we can
376 // successfully SetRegion, In practice a failure of SetRegion means "no
377 // alignments here." It makes sense to simply accept the failure,
378 // UpdateAlignments(), and continue.
380 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
381 if (!it->first->SetRegion(region)) {
382 cerr << "ERROR: could not jump " << it->first->GetFilename() << " to "
383 << region.LeftRefID << ":" << region.LeftPosition
384 << ".." << region.RightRefID << ":" << region.RightPosition << endl;
392 void BamMultiReader::UpdateAlignments(void) {
395 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
396 BamReader* br = it->first;
397 BamAlignment* ba = it->second;
398 if (br->GetNextAlignment(*ba)) {
399 alignments.insert(make_pair(make_pair(ba->RefID, ba->Position),
402 // assume BamReader end of region / EOF
407 // updates the reference id stored in the BamMultiReader
408 // to reflect the current state of the readers
409 void BamMultiReader::UpdateReferenceID(void) {
410 // the alignments are sorted by position, so the first alignment will always have the lowest reference ID
411 if (alignments.begin()->second.second->RefID != CurrentRefID) {
412 // get the next reference id
413 // while there aren't any readers at the next ref id
414 // increment the ref id
415 int nextRefID = CurrentRefID;
416 while (alignments.begin()->second.second->RefID != nextRefID) {
419 //cerr << "updating reference id from " << CurrentRefID << " to " << nextRefID << endl;
420 CurrentRefID = nextRefID;
424 // ValidateReaders checks that all the readers point to BAM files representing
425 // alignments against the same set of reference sequences, and that the
426 // sequences are identically ordered. If these checks fail the operation of
427 // the multireader is undefined, so we force program exit.
428 void BamMultiReader::ValidateReaders(void) const {
429 int firstRefCount = readers.front().first->GetReferenceCount();
430 BamTools::RefVector firstRefData = readers.front().first->GetReferenceData();
431 for (vector<pair<BamReader*, BamAlignment*> >::const_iterator it = readers.begin(); it != readers.end(); ++it) {
432 BamReader* reader = it->first;
433 BamTools::RefVector currentRefData = reader->GetReferenceData();
434 BamTools::RefVector::const_iterator f = firstRefData.begin();
435 BamTools::RefVector::const_iterator c = currentRefData.begin();
436 if (reader->GetReferenceCount() != firstRefCount || firstRefData.size() != currentRefData.size()) {
437 cerr << "ERROR: mismatched number of references in " << reader->GetFilename()
438 << " expected " << firstRefCount
439 << " reference sequences but only found " << reader->GetReferenceCount() << endl;
442 // this will be ok; we just checked above that we have identically-sized sets of references
443 // here we simply check if they are all, in fact, equal in content
444 while (f != firstRefData.end()) {
445 if (f->RefName != c->RefName || f->RefLength != c->RefLength) {
446 cerr << "ERROR: mismatched references found in " << reader->GetFilename()
447 << " expected: " << endl;
448 for (BamTools::RefVector::const_iterator a = firstRefData.begin(); a != firstRefData.end(); ++a)
449 cerr << a->RefName << " " << a->RefLength << endl;
450 cerr << "but found: " << endl;
451 for (BamTools::RefVector::const_iterator a = currentRefData.begin(); a != currentRefData.end(); ++a)
452 cerr << a->RefName << " " << a->RefLength << endl;