1 // ***************************************************************************
2 // BamMultiReader.cpp (c) 2010 Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // All rights reserved.
5 // ---------------------------------------------------------------------------
6 // Last modified: 23 Februrary 2010 (EG)
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 // ***************************************************************************
29 #include "BamMultiReader.h"
30 using namespace BamTools;
33 // -----------------------------------------------------
34 // BamMultiReader implementation
35 // -----------------------------------------------------
38 BamMultiReader::BamMultiReader(void)
44 BamMultiReader::~BamMultiReader(void) {
45 Close(); // close the bam files
46 // clean up reader objects
47 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
53 // close the BAM files
54 void BamMultiReader::Close(void) {
55 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
56 BamReader* reader = it->first;
57 reader->Close(); // close the reader
61 // updates the reference id stored in the BamMultiReader
62 // to reflect the current state of the readers
63 void BamMultiReader::UpdateReferenceID(void) {
64 // the alignments are sorted by position, so the first alignment will always have the lowest reference ID
65 if (alignments.begin()->second.second->RefID != CurrentRefID) {
66 // get the next reference id
67 // while there aren't any readers at the next ref id
68 // increment the ref id
69 int nextRefID = CurrentRefID;
70 while (alignments.begin()->second.second->RefID != nextRefID) {
73 //cerr << "updating reference id from " << CurrentRefID << " to " << nextRefID << endl;
74 CurrentRefID = nextRefID;
78 // checks if any readers still have alignments
79 bool BamMultiReader::HasOpenReaders() {
80 return alignments.size() > 0;
83 // get next alignment among all files
84 bool BamMultiReader::GetNextAlignment(BamAlignment& nextAlignment) {
86 // bail out if we are at EOF in all files, means no more alignments to process
87 if (!HasOpenReaders())
90 // when all alignments have stepped into a new target sequence, update our
91 // current reference sequence id
94 // our lowest alignment and reader will be at the front of our alignment index
95 BamAlignment* alignment = alignments.begin()->second.second;
96 BamReader* reader = alignments.begin()->second.first;
98 // now that we have the lowest alignment in the set, save it by copy to our argument
99 nextAlignment = BamAlignment(*alignment);
101 // remove this alignment index entry from our alignment index
102 alignments.erase(alignments.begin());
104 // and add another entry if we can get another alignment from the reader
105 if (reader->GetNextAlignment(*alignment)) {
106 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
107 make_pair(reader, alignment)));
108 } else { // do nothing
109 //cerr << "reached end of file " << lowestReader->GetFilename() << endl;
116 // get next alignment among all files without parsing character data from alignments
117 bool BamMultiReader::GetNextAlignmentCore(BamAlignment& nextAlignment) {
119 // bail out if we are at EOF in all files, means no more alignments to process
120 if (!HasOpenReaders())
123 // when all alignments have stepped into a new target sequence, update our
124 // current reference sequence id
127 // our lowest alignment and reader will be at the front of our alignment index
128 BamAlignment* alignment = alignments.begin()->second.second;
129 BamReader* reader = alignments.begin()->second.first;
131 // now that we have the lowest alignment in the set, save it by copy to our argument
132 nextAlignment = BamAlignment(*alignment);
133 //memcpy(&nextAlignment, alignment, sizeof(BamAlignment));
135 // remove this alignment index entry from our alignment index
136 alignments.erase(alignments.begin());
138 // and add another entry if we can get another alignment from the reader
139 if (reader->GetNextAlignmentCore(*alignment)) {
140 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
141 make_pair(reader, alignment)));
142 } else { // do nothing
143 //cerr << "reached end of file " << lowestReader->GetFilename() << endl;
150 // jumps to specified region(refID, leftBound) in BAM files, returns success/fail
151 bool BamMultiReader::Jump(int refID, int position) {
153 //if ( References.at(refID).RefHasAlignments && (position <= References.at(refID).RefLength) ) {
154 CurrentRefID = refID;
155 CurrentLeft = position;
158 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
159 BamReader* reader = it->first;
160 result &= reader->Jump(refID, position);
162 cerr << "ERROR: could not jump " << reader->GetFilename() << " to " << refID << ":" << position << endl;
166 if (result) UpdateAlignments();
170 bool BamMultiReader::SetRegion(const int& leftRefID, const int& leftPosition, const int& rightRefID, const int& rightPosition) {
172 BamRegion region(leftRefID, leftPosition, rightRefID, rightPosition);
174 return SetRegion(region);
178 bool BamMultiReader::SetRegion(const BamRegion& region) {
183 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
184 BamReader* reader = it->first;
185 result &= reader->SetRegion(region);
187 cerr << "ERROR: could not set region " << reader->GetFilename() << " to "
188 << region.LeftRefID << ":" << region.LeftPosition << ".." << region.RightRefID << ":" << region.RightPosition
193 if (result) UpdateAlignments();
198 void BamMultiReader::UpdateAlignments(void) {
201 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
202 BamReader* br = it->first;
203 BamAlignment* ba = it->second;
204 if (br->GetNextAlignment(*ba)) {
205 alignments.insert(make_pair(make_pair(ba->RefID, ba->Position),
208 // assume BamReader end of region / EOF
214 void BamMultiReader::Open(const vector<string> filenames, bool openIndexes, bool coreMode, bool useDefaultIndex) {
216 // for filename in filenames
217 fileNames = filenames; // save filenames in our multireader
218 for (vector<string>::const_iterator it = filenames.begin(); it != filenames.end(); ++it) {
219 string filename = *it;
220 BamReader* reader = new BamReader;
222 bool openedOK = true;
225 openedOK = reader->Open(filename, filename + ".bai");
227 openedOK = reader->Open(filename, filename + ".bti");
229 openedOK = reader->Open(filename); // for merging, jumping is disallowed
232 // if file opened ok, check that it can be read
236 BamAlignment* alignment = new BamAlignment;
238 fileOK &= reader->GetNextAlignmentCore(*alignment);
240 fileOK &= reader->GetNextAlignment(*alignment);
244 readers.push_back(make_pair(reader, alignment)); // store pointers to our readers for cleanup
245 alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
246 make_pair(reader, alignment)));
248 cerr << "WARNING: could not read first alignment in " << filename << ", ignoring file" << endl;
253 // TODO; error handling on openedOK == false
263 void BamMultiReader::PrintFilenames(void) {
264 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
265 BamReader* reader = it->first;
266 cout << reader->GetFilename() << endl;
271 void BamMultiReader::DumpAlignmentIndex(void) {
272 for (AlignmentIndex::const_iterator it = alignments.begin(); it != alignments.end(); ++it) {
273 cerr << it->first.first << ":" << it->first.second << " " << it->second.first->GetFilename() << endl;
277 // returns BAM file pointers to beginning of alignment data
278 bool BamMultiReader::Rewind(void) {
280 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
281 BamReader* reader = it->first;
282 result &= reader->Rewind();
287 // saves index data to BAM index files (".bai") where necessary, returns success/fail
288 bool BamMultiReader::CreateIndexes(bool useDefaultIndex) {
290 for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
291 BamReader* reader = it->first;
292 result &= reader->CreateIndex(useDefaultIndex);
297 // makes a virtual, unified header for all the bam files in the multireader
298 const string BamMultiReader::GetHeaderText(void) const {
300 string mergedHeader = "";
301 map<string, bool> readGroups;
303 // foreach extraction entry (each BAM file)
304 for (vector<pair<BamReader*, BamAlignment*> >::const_iterator rs = readers.begin(); rs != readers.end(); ++rs) {
306 map<string, bool> currentFileReadGroups;
308 BamReader* reader = rs->first;
310 stringstream header(reader->GetHeaderText());
311 vector<string> lines;
313 while (getline(header, item))
314 lines.push_back(item);
316 for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
318 // get next line from header, skip if empty
319 string headerLine = *it;
320 if ( headerLine.empty() ) { continue; }
322 // if first file, save HD & SQ entries
323 if ( rs == readers.begin() ) {
324 if ( headerLine.find("@HD") == 0 || headerLine.find("@SQ") == 0) {
325 mergedHeader.append(headerLine.c_str());
326 mergedHeader.append(1, '\n');
330 // (for all files) append RG entries if they are unique
331 if ( headerLine.find("@RG") == 0 ) {
332 stringstream headerLineSs(headerLine);
333 string part, readGroupPart, readGroup;
334 while(std::getline(headerLineSs, part, '\t')) {
335 stringstream partSs(part);
337 std::getline(partSs, subtag, ':');
338 if (subtag == "ID") {
339 std::getline(partSs, readGroup, ':');
343 if (readGroups.find(readGroup) == readGroups.end()) { // prevents duplicate @RG entries
344 mergedHeader.append(headerLine.c_str() );
345 mergedHeader.append(1, '\n');
346 readGroups[readGroup] = true;
347 currentFileReadGroups[readGroup] = true;
349 // warn iff we are reading one file and discover duplicated @RG tags in the header
350 // otherwise, we emit no warning, as we might be merging multiple BAM files with identical @RG tags
351 if (currentFileReadGroups.find(readGroup) != currentFileReadGroups.end()) {
352 cerr << "WARNING: duplicate @RG tag " << readGroup
353 << " entry in header of " << reader->GetFilename() << endl;
360 // return merged header text
364 // ValidateReaders checks that all the readers point to BAM files representing
365 // alignments against the same set of reference sequences, and that the
366 // sequences are identically ordered. If these checks fail the operation of
367 // the multireader is undefined, so we force program exit.
368 void BamMultiReader::ValidateReaders(void) const {
369 int firstRefCount = readers.front().first->GetReferenceCount();
370 BamTools::RefVector firstRefData = readers.front().first->GetReferenceData();
371 for (vector<pair<BamReader*, BamAlignment*> >::const_iterator it = readers.begin(); it != readers.end(); ++it) {
372 BamReader* reader = it->first;
373 BamTools::RefVector currentRefData = reader->GetReferenceData();
374 BamTools::RefVector::const_iterator f = firstRefData.begin();
375 BamTools::RefVector::const_iterator c = currentRefData.begin();
376 if (reader->GetReferenceCount() != firstRefCount || firstRefData.size() != currentRefData.size()) {
377 cerr << "ERROR: mismatched number of references in " << reader->GetFilename()
378 << " expected " << firstRefCount
379 << " reference sequences but only found " << reader->GetReferenceCount() << endl;
382 // this will be ok; we just checked above that we have identically-sized sets of references
383 // here we simply check if they are all, in fact, equal in content
384 while (f != firstRefData.end()) {
385 if (f->RefName != c->RefName || f->RefLength != c->RefLength) {
386 cerr << "ERROR: mismatched references found in " << reader->GetFilename()
387 << " expected: " << endl;
388 for (BamTools::RefVector::const_iterator a = firstRefData.begin(); a != firstRefData.end(); ++a)
389 cerr << a->RefName << " " << a->RefLength << endl;
390 cerr << "but found: " << endl;
391 for (BamTools::RefVector::const_iterator a = currentRefData.begin(); a != currentRefData.end(); ++a)
392 cerr << a->RefName << " " << a->RefLength << endl;
400 // NB: The following functions assume that we have identical references for all
401 // BAM files. We enforce this by invoking the above validation function
402 // (ValidateReaders) to verify that our reference data is the same across all
403 // files on Open, so we will not encounter a situation in which there is a
404 // mismatch and we are still live.
406 // returns the number of reference sequences
407 const int BamMultiReader::GetReferenceCount(void) const {
408 return readers.front().first->GetReferenceCount();
411 // returns vector of reference objects
412 const BamTools::RefVector BamMultiReader::GetReferenceData(void) const {
413 return readers.front().first->GetReferenceData();
416 const int BamMultiReader::GetReferenceID(const string& refName) const {
417 return readers.front().first->GetReferenceID(refName);