]> git.donarmstrong.com Git - bamtools.git/blob - BamMultiReader.cpp
f0a8ceda8b2bc1bf8b43803e794be9e229357415
[bamtools.git] / BamMultiReader.cpp
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
9 // Institute.
10 // ---------------------------------------------------------------------------
11 // Functionality for simultaneously reading multiple BAM files.
12 //
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 // ***************************************************************************
18
19 // C++ includes
20 #include <algorithm>
21 #include <iterator>
22 #include <string>
23 #include <vector>
24 #include <iostream>
25 #include <sstream>
26
27 // BamTools includes
28 #include "BGZF.h"
29 #include "BamMultiReader.h"
30 using namespace BamTools;
31 using namespace std;
32
33 // -----------------------------------------------------
34 // BamMultiReader implementation
35 // -----------------------------------------------------
36
37 // constructor
38 BamMultiReader::BamMultiReader(void)
39     : CurrentRefID(0)
40     , CurrentLeft(0)
41 { }
42
43 // destructor
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) {
48         delete it->first;
49         delete it->second;
50     }
51 }
52
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
58     }
59 }
60
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) {
71             ++nextRefID;
72         }
73         //cerr << "updating reference id from " << CurrentRefID << " to " << nextRefID << endl;
74         CurrentRefID = nextRefID;
75     }
76 }
77
78 // checks if any readers still have alignments
79 bool BamMultiReader::HasOpenReaders() {
80     return alignments.size() > 0;
81 }
82
83 // get next alignment among all files
84 bool BamMultiReader::GetNextAlignment(BamAlignment& nextAlignment) {
85
86     // bail out if we are at EOF in all files, means no more alignments to process
87     if (!HasOpenReaders())
88         return false;
89
90     // when all alignments have stepped into a new target sequence, update our
91     // current reference sequence id
92     UpdateReferenceID();
93
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;
97
98     // now that we have the lowest alignment in the set, save it by copy to our argument
99     nextAlignment = BamAlignment(*alignment);
100
101     // remove this alignment index entry from our alignment index
102     alignments.erase(alignments.begin());
103
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;
110     }
111
112     return true;
113
114 }
115
116 // get next alignment among all files without parsing character data from alignments
117 bool BamMultiReader::GetNextAlignmentCore(BamAlignment& nextAlignment) {
118
119     // bail out if we are at EOF in all files, means no more alignments to process
120     if (!HasOpenReaders())
121         return false;
122
123     // when all alignments have stepped into a new target sequence, update our
124     // current reference sequence id
125     UpdateReferenceID();
126
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;
130
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));
134
135     // remove this alignment index entry from our alignment index
136     alignments.erase(alignments.begin());
137
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;
144     }
145
146     return true;
147
148 }
149
150 // jumps to specified region(refID, leftBound) in BAM files, returns success/fail
151 bool BamMultiReader::Jump(int refID, int position) {
152
153     //if ( References.at(refID).RefHasAlignments && (position <= References.at(refID).RefLength) ) {
154     CurrentRefID = refID;
155     CurrentLeft  = position;
156
157     bool result = true;
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);
161         if (!result) {
162             cerr << "ERROR: could not jump " << reader->GetFilename() << " to " << refID << ":" << position << endl;
163             exit(1);
164         }
165     }
166     if (result) {
167         // Update Alignments
168         alignments.clear();
169         for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
170             BamReader* br = it->first;
171             BamAlignment* ba = it->second;
172             if (br->GetNextAlignment(*ba)) {
173                 alignments.insert(make_pair(make_pair(ba->RefID, ba->Position), 
174                                             make_pair(br, ba)));
175             } else {
176                 // assume BamReader EOF
177             }
178         }
179     }
180     return result;
181 }
182
183 // opens BAM files
184 void BamMultiReader::Open(const vector<string> filenames, bool openIndexes, bool coreMode) {
185     // for filename in filenames
186     fileNames = filenames; // save filenames in our multireader
187     for (vector<string>::const_iterator it = filenames.begin(); it != filenames.end(); ++it) {
188         string filename = *it;
189         BamReader* reader = new BamReader;
190         if (openIndexes) {
191             reader->Open(filename, filename + ".bai");
192         } else {
193             reader->Open(filename); // for merging, jumping is disallowed
194         }
195         BamAlignment* alignment = new BamAlignment;
196         if (coreMode) {
197             reader->GetNextAlignmentCore(*alignment);
198         } else {
199             reader->GetNextAlignment(*alignment);
200         }
201         readers.push_back(make_pair(reader, alignment)); // store pointers to our readers for cleanup
202         alignments.insert(make_pair(make_pair(alignment->RefID, alignment->Position),
203                                     make_pair(reader, alignment)));
204     }
205     ValidateReaders();
206 }
207
208 void BamMultiReader::PrintFilenames(void) {
209     for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
210         BamReader* reader = it->first;
211         cout << reader->GetFilename() << endl;
212     }
213 }
214
215 // for debugging
216 void BamMultiReader::DumpAlignmentIndex(void) {
217     for (AlignmentIndex::const_iterator it = alignments.begin(); it != alignments.end(); ++it) {
218         cerr << it->first.first << ":" << it->first.second << " " << it->second.first->GetFilename() << endl;
219     }
220 }
221
222 // returns BAM file pointers to beginning of alignment data
223 bool BamMultiReader::Rewind(void) { 
224     bool result = true;
225     for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
226         BamReader* reader = it->first;
227         result &= reader->Rewind();
228     }
229     return result;
230 }
231
232 // saves index data to BAM index files (".bai") where necessary, returns success/fail
233 bool BamMultiReader::CreateIndexes(void) {
234     bool result = true;
235     for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
236         BamReader* reader = it->first;
237         result &= reader->CreateIndex();
238     }
239     return result;
240 }
241
242 // makes a virtual, unified header for all the bam files in the multireader
243 const string BamMultiReader::GetHeaderText(void) const {
244
245     string mergedHeader = "";
246     map<string, bool> readGroups;
247
248     // foreach extraction entry (each BAM file)
249     for (vector<pair<BamReader*, BamAlignment*> >::const_iterator rs = readers.begin(); rs != readers.end(); ++rs) {
250
251         map<string, bool> currentFileReadGroups;
252
253         BamReader* reader = rs->first;
254
255         stringstream header(reader->GetHeaderText());
256         vector<string> lines;
257         string item;
258         while (getline(header, item))
259             lines.push_back(item);
260
261         for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
262
263             // get next line from header, skip if empty
264             string headerLine = *it;
265             if ( headerLine.empty() ) { continue; }
266
267             // if first file, save HD & SQ entries
268             if ( rs == readers.begin() ) {
269                 if ( headerLine.find("@HD") == 0 || headerLine.find("@SQ") == 0) {
270                     mergedHeader.append(headerLine.c_str());
271                     mergedHeader.append(1, '\n');
272                 }
273             }
274
275             // (for all files) append RG entries if they are unique
276             if ( headerLine.find("@RG") == 0 ) {
277                 stringstream headerLineSs(headerLine);
278                 string part, readGroupPart, readGroup;
279                 while(std::getline(headerLineSs, part, '\t')) {
280                     stringstream partSs(part);
281                     string subtag;
282                     std::getline(partSs, subtag, ':');
283                     if (subtag == "ID") {
284                         std::getline(partSs, readGroup, ':');
285                         break;
286                     }
287                 }
288                 if (readGroups.find(readGroup) == readGroups.end()) { // prevents duplicate @RG entries
289                     mergedHeader.append(headerLine.c_str() );
290                     mergedHeader.append(1, '\n');
291                     readGroups[readGroup] = true;
292                     currentFileReadGroups[readGroup] = true;
293                 } else {
294                     // warn iff we are reading one file and discover duplicated @RG tags in the header
295                     // otherwise, we emit no warning, as we might be merging multiple BAM files with identical @RG tags
296                     if (currentFileReadGroups.find(readGroup) != currentFileReadGroups.end()) {
297                         cerr << "WARNING: duplicate @RG tag " << readGroup 
298                             << " entry in header of " << reader->GetFilename() << endl;
299                     }
300                 }
301             }
302         }
303     }
304
305     // return merged header text
306     return mergedHeader;
307 }
308
309 // ValidateReaders checks that all the readers point to BAM files representing
310 // alignments against the same set of reference sequences, and that the
311 // sequences are identically ordered.  If these checks fail the operation of
312 // the multireader is undefined, so we force program exit.
313 void BamMultiReader::ValidateReaders(void) const {
314     int firstRefCount = readers.front().first->GetReferenceCount();
315     BamTools::RefVector firstRefData = readers.front().first->GetReferenceData();
316     for (vector<pair<BamReader*, BamAlignment*> >::const_iterator it = readers.begin(); it != readers.end(); ++it) {
317         BamReader* reader = it->first;
318         BamTools::RefVector currentRefData = reader->GetReferenceData();
319         BamTools::RefVector::const_iterator f = firstRefData.begin();
320         BamTools::RefVector::const_iterator c = currentRefData.begin();
321         if (reader->GetReferenceCount() != firstRefCount || firstRefData.size() != currentRefData.size()) {
322             cerr << "ERROR: mismatched number of references in " << reader->GetFilename()
323                       << " expected " << firstRefCount 
324                       << " reference sequences but only found " << reader->GetReferenceCount() << endl;
325             exit(1);
326         }
327         // this will be ok; we just checked above that we have identically-sized sets of references
328         // here we simply check if they are all, in fact, equal in content
329         while (f != firstRefData.end()) {
330             if (f->RefName != c->RefName || f->RefLength != c->RefLength) {
331                 cerr << "ERROR: mismatched references found in " << reader->GetFilename()
332                           << " expected: " << endl;
333                 for (BamTools::RefVector::const_iterator a = firstRefData.begin(); a != firstRefData.end(); ++a)
334                     cerr << a->RefName << " " << a->RefLength << endl;
335                 cerr << "but found: " << endl;
336                 for (BamTools::RefVector::const_iterator a = currentRefData.begin(); a != currentRefData.end(); ++a)
337                     cerr << a->RefName << " " << a->RefLength << endl;
338                 exit(1);
339             }
340             ++f; ++c;
341         }
342     }
343 }
344
345 // NB: The following functions assume that we have identical references for all
346 // BAM files.  We enforce this by invoking the above validation function
347 // (ValidateReaders) to verify that our reference data is the same across all
348 // files on Open, so we will not encounter a situation in which there is a
349 // mismatch and we are still live.
350
351 // returns the number of reference sequences
352 const int BamMultiReader::GetReferenceCount(void) const {
353     return readers.front().first->GetReferenceCount();
354 }
355
356 // returns vector of reference objects
357 const BamTools::RefVector BamMultiReader::GetReferenceData(void) const {
358     return readers.front().first->GetReferenceData();
359 }
360
361 const int BamMultiReader::GetReferenceID(const string& refName) const { 
362     return readers.front().first->GetReferenceID(refName);
363 }