]> git.donarmstrong.com Git - bamtools.git/blob - src/api/BamMultiReader.cpp
Moved BamAlignment data structure out to its own .h/.cpp. BamAux.h was getting over...
[bamtools.git] / src / api / BamMultiReader.cpp
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
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 #include <algorithm>
20 #include <fstream>
21 #include <iostream>
22 #include <iterator>
23 #include <sstream>
24 #include <string>
25 #include <vector>
26 #include "BGZF.h"
27 #include "BamMultiReader.h"
28 using namespace BamTools;
29 using namespace std;
30
31 // -----------------------------------------------------
32 // BamMultiReader implementation
33 // -----------------------------------------------------
34
35 // constructor
36 BamMultiReader::BamMultiReader(void)
37     : CurrentRefID(0)
38     , CurrentLeft(0)
39 { }
40
41 // destructor
42 BamMultiReader::~BamMultiReader(void) {
43     Close(); 
44 }
45
46 // close the BAM files
47 void BamMultiReader::Close(void) {
48   
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) {
53       
54         BamReader* reader = (*readerIter).first;
55         BamAlignment* alignment = (*readerIter).second;
56         
57         // close the reader
58         if ( reader) reader->Close();  
59         
60         // delete reader pointer
61         delete reader;
62         reader = 0;
63
64         // delete alignment pointer
65         delete alignment;
66         alignment = 0;
67     }
68
69     // clear out the container
70     readers.clear();
71 }
72
73 // saves index data to BAM index files (".bai"/".bti") where necessary, returns success/fail
74 bool BamMultiReader::CreateIndexes(bool useStandardIndex) {
75     bool result = true;
76     for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
77         BamReader* reader = it->first;
78         result &= reader->CreateIndex(useStandardIndex);
79     }
80     return result;
81 }
82
83 // for debugging
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;
87     }
88 }
89
90 // makes a virtual, unified header for all the bam files in the multireader
91 const string BamMultiReader::GetHeaderText(void) const {
92
93     string mergedHeader = "";
94     map<string, bool> readGroups;
95
96     // foreach extraction entry (each BAM file)
97     for (vector<pair<BamReader*, BamAlignment*> >::const_iterator rs = readers.begin(); rs != readers.end(); ++rs) {
98
99         BamReader* reader = rs->first;
100         string headerText = reader->GetHeaderText();
101         if ( headerText.empty() ) continue;
102         
103         map<string, bool> currentFileReadGroups;
104         stringstream header(headerText);
105         vector<string> lines;
106         string item;
107         while (getline(header, item))
108             lines.push_back(item);
109
110         for (vector<string>::const_iterator it = lines.begin(); it != lines.end(); ++it) {
111
112             // get next line from header, skip if empty
113             string headerLine = *it;
114             if ( headerLine.empty() ) { continue; }
115
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');
121                 }
122             }
123
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);
130                     string subtag;
131                     std::getline(partSs, subtag, ':');
132                     if (subtag == "ID") {
133                         std::getline(partSs, readGroup, ':');
134                         break;
135                     }
136                 }
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;
142                 } else {
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;
148                     }
149                 }
150             }
151         }
152     }
153
154     // return merged header text
155     return mergedHeader;
156 }
157
158 // get next alignment among all files
159 bool BamMultiReader::GetNextAlignment(BamAlignment& nextAlignment) {
160
161     // bail out if we are at EOF in all files, means no more alignments to process
162     if (!HasOpenReaders())
163         return false;
164
165     // when all alignments have stepped into a new target sequence, update our
166     // current reference sequence id
167     UpdateReferenceID();
168
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;
172
173     // now that we have the lowest alignment in the set, save it by copy to our argument
174     nextAlignment = BamAlignment(*alignment);
175
176     // remove this alignment index entry from our alignment index
177     alignments.erase(alignments.begin());
178
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;
185     }
186
187     return true;
188
189 }
190
191 // get next alignment among all files without parsing character data from alignments
192 bool BamMultiReader::GetNextAlignmentCore(BamAlignment& nextAlignment) {
193
194     // bail out if we are at EOF in all files, means no more alignments to process
195     if (!HasOpenReaders())
196         return false;
197
198     // when all alignments have stepped into a new target sequence, update our
199     // current reference sequence id
200     UpdateReferenceID();
201
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;
205
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));
209
210     // remove this alignment index entry from our alignment index
211     alignments.erase(alignments.begin());
212
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;
219     }
220
221     return true;
222
223 }
224
225 // ---------------------------------------------------------------------------------------
226 //
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.
232 //
233 // ---------------------------------------------------------------------------------------
234
235 // returns the number of reference sequences
236 const int BamMultiReader::GetReferenceCount(void) const {
237     return readers.front().first->GetReferenceCount();
238 }
239
240 // returns vector of reference objects
241 const BamTools::RefVector BamMultiReader::GetReferenceData(void) const {
242     return readers.front().first->GetReferenceData();
243 }
244
245 // returns refID from reference name
246 const int BamMultiReader::GetReferenceID(const string& refName) const { 
247     return readers.front().first->GetReferenceID(refName);
248 }
249
250 // ---------------------------------------------------------------------------------------
251
252 // checks if any readers still have alignments
253 bool BamMultiReader::HasOpenReaders() {
254     return alignments.size() > 0;
255 }
256
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 {
260     bool ok = true;
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();
266     }
267     return ok;
268 }
269
270 // jumps to specified region(refID, leftBound) in BAM files, returns success/fail
271 bool BamMultiReader::Jump(int refID, int position) {
272
273     //if ( References.at(refID).RefHasAlignments && (position <= References.at(refID).RefLength) ) {
274     CurrentRefID = refID;
275     CurrentLeft  = position;
276
277     bool result = true;
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);
281         if (!result) {
282             cerr << "ERROR: could not jump " << reader->GetFilename() << " to " << refID << ":" << position << endl;
283             exit(1);
284         }
285     }
286     if (result) UpdateAlignments();
287     return result;
288 }
289
290 // opens BAM files
291 bool BamMultiReader::Open(const vector<string>& filenames, bool openIndexes, bool coreMode, bool useDefaultIndex) {
292     
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) {
296         
297         const string filename = *it;
298         BamReader* reader = new BamReader;
299
300         bool openedOK = true;
301         if (openIndexes) {
302             
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);
307         } 
308         
309         // ignoring index file(s)
310         else openedOK = reader->Open(filename); 
311         
312         // if file opened ok, check that it can be read
313         if ( openedOK ) {
314            
315             bool fileOK = true;
316             BamAlignment* alignment = new BamAlignment;
317             fileOK &= ( coreMode ? reader->GetNextAlignmentCore(*alignment) : reader->GetNextAlignment(*alignment) );
318             
319             if (fileOK) {
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)));
323             } else {
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;
327             }
328         } 
329        
330         // TODO; any further error handling when openedOK is false ??
331         else 
332             return false;
333     }
334
335     // files opened ok, at least one alignment could be read,
336     // now need to check that all files use same reference data
337     ValidateReaders();
338     return true;
339 }
340
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;
345     }
346 }
347
348 // returns BAM file pointers to beginning of alignment data
349 bool BamMultiReader::Rewind(void) { 
350     bool result = true;
351     for (vector<pair<BamReader*, BamAlignment*> >::iterator it = readers.begin(); it != readers.end(); ++it) {
352         BamReader* reader = it->first;
353         result &= reader->Rewind();
354     }
355     return result;
356 }
357
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);
361 }
362
363 bool BamMultiReader::SetRegion(const BamRegion& region) {
364
365     Region = region;
366
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.
371
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;
377         }
378     }
379
380     UpdateAlignments();
381     return true;
382 }
383
384 void BamMultiReader::UpdateAlignments(void) {
385     // Update Alignments
386     alignments.clear();
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), 
392                                         make_pair(br, ba)));
393         } else {
394             // assume BamReader end of region / EOF
395         }
396     }
397 }
398
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) {
409             ++nextRefID;
410         }
411         //cerr << "updating reference id from " << CurrentRefID << " to " << nextRefID << endl;
412         CurrentRefID = nextRefID;
413     }
414 }
415
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;
432             exit(1);
433         }
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;
445                 exit(1);
446             }
447             ++f; ++c;
448         }
449     }
450 }