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);
84 void BamMultiReader::DumpAlignmentIndex(void) {
85 for (AlignmentIndex::const_iterator it = alignments.begin(); it != alignments.end(); ++it) {
86 cerr << it->first.first << ":" << it->first.second << " " << it->second.first->GetFilename() << endl;
90 // makes a virtual, unified header for all the bam files in the multireader
91 const string BamMultiReader::GetHeaderText(void) const {
93 string mergedHeader = "";
94 map<string, bool> readGroups;
96 // foreach extraction entry (each BAM file)
97 for (vector<pair<BamReader*, BamAlignment*> >::const_iterator rs = readers.begin(); rs != readers.end(); ++rs) {
99 BamReader* reader = rs->first;
100 const string headerText = reader->GetHeaderText();
101 if ( headerText.empty() ) continue;
103 map<string, bool> currentFileReadGroups;
104 stringstream header(headerText);
105 vector<string> lines;
107 while (getline(header, item))
108 lines.push_back(item);
110 for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
112 // get next line from header, skip if empty
113 string headerLine = *it;
114 if ( headerLine.empty() ) { continue; }
116 // if first file, save HD & SQ entries
117 if ( rs == readers.begin() ) {
118 if ( headerLine.find("@HD") == 0 || headerLine.find("@SQ") == 0) {
119 mergedHeader.append(headerLine.c_str());
120 mergedHeader.append(1, '\n');
124 // (for all files) append RG entries if they are unique
125 if ( headerLine.find("@RG") == 0 ) {
126 stringstream headerLineSs(headerLine);
127 string part, readGroupPart, readGroup;
128 while(std::getline(headerLineSs, part, '\t')) {
129 stringstream partSs(part);
131 std::getline(partSs, subtag, ':');
132 if (subtag == "ID") {
133 std::getline(partSs, readGroup, ':');
137 if (readGroups.find(readGroup) == readGroups.end()) { // prevents duplicate @RG entries
138 mergedHeader.append(headerLine.c_str() );
139 mergedHeader.append(1, '\n');
140 readGroups[readGroup] = true;
141 currentFileReadGroups[readGroup] = true;
143 // warn iff we are reading one file and discover duplicated @RG tags in the header
144 // otherwise, we emit no warning, as we might be merging multiple BAM files with identical @RG tags
145 if (currentFileReadGroups.find(readGroup) != currentFileReadGroups.end()) {
146 cerr << "WARNING: duplicate @RG tag " << readGroup
147 << " entry in header of " << reader->GetFilename() << endl;
154 // return merged header text
158 // get next alignment among all files
159 bool BamMultiReader::GetNextAlignment(BamAlignment& nextAlignment) {
161 // bail out if we are at EOF in all files, means no more alignments to process
162 if (!HasOpenReaders())
165 // when all alignments have stepped into a new target sequence, update our
166 // current reference sequence id
169 // our lowest alignment and reader will be at the front of our alignment index
170 BamAlignment* alignment = alignments.begin()->second.second;
171 BamReader* reader = alignments.begin()->second.first;
173 // now that we have the lowest alignment in the set, save it by copy to our argument
174 nextAlignment = BamAlignment(*alignment);
176 // remove this alignment index entry from our alignment index
177 alignments.erase(alignments.begin());
179 // and add another entry if we can get another alignment from the reader
180 if (reader->GetNextAlignment(*alignment)) {
181 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
182 make_pair(reader, alignment)));
183 } else { // do nothing
184 //cerr << "reached end of file " << lowestReader->GetFilename() << endl;
191 // get next alignment among all files without parsing character data from alignments
192 bool BamMultiReader::GetNextAlignmentCore(BamAlignment& nextAlignment) {
194 // bail out if we are at EOF in all files, means no more alignments to process
195 if (!HasOpenReaders())
198 // when all alignments have stepped into a new target sequence, update our
199 // current reference sequence id
202 // our lowest alignment and reader will be at the front of our alignment index
203 BamAlignment* alignment = alignments.begin()->second.second;
204 BamReader* reader = alignments.begin()->second.first;
206 // now that we have the lowest alignment in the set, save it by copy to our argument
207 nextAlignment = BamAlignment(*alignment);
208 //memcpy(&nextAlignment, alignment, sizeof(BamAlignment));
210 // remove this alignment index entry from our alignment index
211 alignments.erase(alignments.begin());
213 // and add another entry if we can get another alignment from the reader
214 if (reader->GetNextAlignmentCore(*alignment)) {
215 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
216 make_pair(reader, alignment)));
217 } else { // do nothing
218 //cerr << "reached end of file " << lowestReader->GetFilename() << endl;
225 // ---------------------------------------------------------------------------------------
227 // NB: The following GetReferenceX() functions assume that we have identical
228 // references for all BAM files. We enforce this by invoking the above
229 // validation function (ValidateReaders) to verify that our reference data
230 // is the same across all files on Open, so we will not encounter a situation
231 // in which there is a mismatch and we are still live.
233 // ---------------------------------------------------------------------------------------
235 // returns the number of reference sequences
236 const int BamMultiReader::GetReferenceCount(void) const {
237 return readers.front().first->GetReferenceCount();
240 // returns vector of reference objects
241 const BamTools::RefVector BamMultiReader::GetReferenceData(void) const {
242 return readers.front().first->GetReferenceData();
245 // returns refID from reference name
246 const int BamMultiReader::GetReferenceID(const string& refName) const {
247 return readers.front().first->GetReferenceID(refName);
250 // ---------------------------------------------------------------------------------------
252 // checks if any readers still have alignments
253 bool BamMultiReader::HasOpenReaders() {
254 return alignments.size() > 0;
257 // returns whether underlying BAM readers ALL have an index loaded
258 // this is useful to indicate whether Jump() or SetRegion() are possible
259 bool BamMultiReader::IsIndexLoaded(void) const {
261 vector<pair<BamReader*, BamAlignment*> >::const_iterator readerIter = readers.begin();
262 vector<pair<BamReader*, BamAlignment*> >::const_iterator readerEnd = readers.end();
263 for ( ; readerIter != readerEnd; ++readerIter ) {
264 const BamReader* reader = (*readerIter).first;
265 if ( reader ) ok &= reader->IsIndexLoaded();
270 // jumps to specified region(refID, leftBound) in BAM files, returns success/fail
271 bool BamMultiReader::Jump(int refID, int position) {
273 //if ( References.at(refID).RefHasAlignments && (position <= References.at(refID).RefLength) ) {
274 CurrentRefID = refID;
275 CurrentLeft = position;
278 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
279 BamReader* reader = it->first;
280 result &= reader->Jump(refID, position);
282 cerr << "ERROR: could not jump " << reader->GetFilename() << " to " << refID << ":" << position << endl;
286 if (result) UpdateAlignments();
291 bool BamMultiReader::Open(const vector<string>& filenames, bool openIndexes, bool coreMode, bool useDefaultIndex) {
293 // for filename in filenames
294 fileNames = filenames; // save filenames in our multireader
295 for (vector<string>::const_iterator it = filenames.begin(); it != filenames.end(); ++it) {
297 const string filename = *it;
298 BamReader* reader = new BamReader;
300 bool openedOK = true;
303 // leave index filename empty
304 // this allows BamReader & BamIndex to search for any available
305 // useDefaultIndex gives hint to prefer BAI over BTI
306 openedOK = reader->Open(filename, "", true, useDefaultIndex);
309 // ignoring index file(s)
310 else openedOK = reader->Open(filename);
312 // if file opened ok, check that it can be read
316 BamAlignment* alignment = new BamAlignment;
317 fileOK &= ( coreMode ? reader->GetNextAlignmentCore(*alignment) : reader->GetNextAlignment(*alignment) );
320 readers.push_back(make_pair(reader, alignment)); // store pointers to our readers for cleanup
321 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
322 make_pair(reader, alignment)));
324 cerr << "WARNING: could not read first alignment in " << filename << ", ignoring file" << endl;
325 // if only file available & could not be read, return failure
326 if ( filenames.size() == 1 ) return false;
330 // TODO; any further error handling when openedOK is false ??
335 // files opened ok, at least one alignment could be read,
336 // now need to check that all files use same reference data
341 void BamMultiReader::PrintFilenames(void) {
342 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
343 BamReader* reader = it->first;
344 cout << reader->GetFilename() << endl;
348 // returns BAM file pointers to beginning of alignment data
349 bool BamMultiReader::Rewind(void) {
351 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
352 BamReader* reader = it->first;
353 result &= reader->Rewind();
358 bool BamMultiReader::SetRegion(const int& leftRefID, const int& leftPosition, const int& rightRefID, const int& rightPosition) {
359 BamRegion region(leftRefID, leftPosition, rightRefID, rightPosition);
360 return SetRegion(region);
363 bool BamMultiReader::SetRegion(const BamRegion& region) {
367 // NB: While it may make sense to track readers in which we can
368 // successfully SetRegion, In practice a failure of SetRegion means "no
369 // alignments here." It makes sense to simply accept the failure,
370 // UpdateAlignments(), and continue.
372 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
373 if (!it->first->SetRegion(region)) {
374 cerr << "ERROR: could not jump " << it->first->GetFilename() << " to "
375 << region.LeftRefID << ":" << region.LeftPosition
376 << ".." << region.RightRefID << ":" << region.RightPosition << endl;
384 void BamMultiReader::UpdateAlignments(void) {
387 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
388 BamReader* br = it->first;
389 BamAlignment* ba = it->second;
390 if (br->GetNextAlignment(*ba)) {
391 alignments.insert(make_pair(make_pair(ba->RefID, ba->Position),
394 // assume BamReader end of region / EOF
399 // updates the reference id stored in the BamMultiReader
400 // to reflect the current state of the readers
401 void BamMultiReader::UpdateReferenceID(void) {
402 // the alignments are sorted by position, so the first alignment will always have the lowest reference ID
403 if (alignments.begin()->second.second->RefID != CurrentRefID) {
404 // get the next reference id
405 // while there aren't any readers at the next ref id
406 // increment the ref id
407 int nextRefID = CurrentRefID;
408 while (alignments.begin()->second.second->RefID != nextRefID) {
411 //cerr << "updating reference id from " << CurrentRefID << " to " << nextRefID << endl;
412 CurrentRefID = nextRefID;
416 // ValidateReaders checks that all the readers point to BAM files representing
417 // alignments against the same set of reference sequences, and that the
418 // sequences are identically ordered. If these checks fail the operation of
419 // the multireader is undefined, so we force program exit.
420 void BamMultiReader::ValidateReaders(void) const {
421 int firstRefCount = readers.front().first->GetReferenceCount();
422 BamTools::RefVector firstRefData = readers.front().first->GetReferenceData();
423 for (vector<pair<BamReader*, BamAlignment*> >::const_iterator it = readers.begin(); it != readers.end(); ++it) {
424 BamReader* reader = it->first;
425 BamTools::RefVector currentRefData = reader->GetReferenceData();
426 BamTools::RefVector::const_iterator f = firstRefData.begin();
427 BamTools::RefVector::const_iterator c = currentRefData.begin();
428 if (reader->GetReferenceCount() != firstRefCount || firstRefData.size() != currentRefData.size()) {
429 cerr << "ERROR: mismatched number of references in " << reader->GetFilename()
430 << " expected " << firstRefCount
431 << " reference sequences but only found " << reader->GetReferenceCount() << endl;
434 // this will be ok; we just checked above that we have identically-sized sets of references
435 // here we simply check if they are all, in fact, equal in content
436 while (f != firstRefData.end()) {
437 if (f->RefName != c->RefName || f->RefLength != c->RefLength) {
438 cerr << "ERROR: mismatched references found in " << reader->GetFilename()
439 << " expected: " << endl;
440 for (BamTools::RefVector::const_iterator a = firstRefData.begin(); a != firstRefData.end(); ++a)
441 cerr << a->RefName << " " << a->RefLength << endl;
442 cerr << "but found: " << endl;
443 for (BamTools::RefVector::const_iterator a = currentRefData.begin(); a != currentRefData.end(); ++a)
444 cerr << a->RefName << " " << a->RefLength << endl;