1 // ***************************************************************************
2 // BamReader_p.cpp (c) 2009 Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 18 November 2012 (DB)
6 // ---------------------------------------------------------------------------
7 // Provides the basic functionality for reading BAM files
8 // ***************************************************************************
10 #include "api/BamConstants.h"
11 #include "api/BamReader.h"
12 #include "api/IBamIODevice.h"
13 #include "api/internal/bam/BamHeader_p.h"
14 #include "api/internal/bam/BamRandomAccessController_p.h"
15 #include "api/internal/bam/BamReader_p.h"
16 #include "api/internal/index/BamStandardIndex_p.h"
17 #include "api/internal/index/BamToolsIndex_p.h"
18 #include "api/internal/io/BamDeviceFactory_p.h"
19 #include "api/internal/utils/BamException_p.h"
20 using namespace BamTools;
21 using namespace BamTools::Internal;
31 BamReaderPrivate::BamReaderPrivate(BamReader* parent)
32 : m_alignmentsBeginOffset(0)
35 m_isBigEndian = BamTools::SystemIsBigEndian();
39 BamReaderPrivate::~BamReaderPrivate(void) {
43 // closes the BAM file
44 bool BamReaderPrivate::Close(void) {
53 // close random access controller
54 m_randomAccessController.Close();
56 // if stream is open, attempt close
60 } catch ( BamException& e ) {
61 const string streamError = e.what();
62 const string message = string("encountered error closing BAM file: \n\t") + streamError;
63 SetErrorString("BamReader::Close", message);
72 // creates an index file of requested type on current BAM file
73 bool BamReaderPrivate::CreateIndex(const BamIndex::IndexType& type) {
75 // skip if BAM file not open
77 SetErrorString("BamReader::CreateIndex", "cannot create index on unopened BAM file");
81 // attempt to create index
82 if ( m_randomAccessController.CreateIndex(this, type) )
85 const string bracError = m_randomAccessController.GetErrorString();
86 const string message = string("could not create index: \n\t") + bracError;
87 SetErrorString("BamReader::CreateIndex", message);
92 // return path & filename of current BAM file
93 const string BamReaderPrivate::Filename(void) const {
97 const SamHeader& BamReaderPrivate::GetConstSamHeader(void) const {
98 return m_header.ToConstSamHeader();
101 string BamReaderPrivate::GetErrorString(void) const {
102 return m_errorString;
105 // return header data as std::string
106 string BamReaderPrivate::GetHeaderText(void) const {
107 return m_header.ToString();
110 // return header data as SamHeader object
111 SamHeader BamReaderPrivate::GetSamHeader(void) const {
112 return m_header.ToSamHeader();
115 // get next alignment (with character data fully parsed)
116 bool BamReaderPrivate::GetNextAlignment(BamAlignment& alignment) {
118 // if valid alignment found
119 if ( GetNextAlignmentCore(alignment) ) {
121 // store alignment's "source" filename
122 alignment.Filename = m_filename;
124 // return success/failure of parsing char data
125 if ( alignment.BuildCharData() )
128 const string alError = alignment.GetErrorString();
129 const string message = string("could not populate alignment data: \n\t") + alError;
130 SetErrorString("BamReader::GetNextAlignment", message);
135 // no valid alignment found
139 // retrieves next available alignment core data (returns success/fail)
140 // ** DOES NOT populate any character data fields (read name, bases, qualities, tag data, filename)
141 // these can be accessed, if necessary, from the supportData
142 // useful for operations requiring ONLY positional or other alignment-related information
143 bool BamReaderPrivate::GetNextAlignmentCore(BamAlignment& alignment) {
145 // skip if stream not opened
146 if ( !m_stream.IsOpen() )
151 // skip if region is set but has no alignments
152 if ( m_randomAccessController.HasRegion() &&
153 !m_randomAccessController.RegionHasAlignments() )
158 // if can't read next alignment
159 if ( !LoadNextAlignment(alignment) )
162 // check alignment's region-overlap state
163 BamRandomAccessController::RegionState state = m_randomAccessController.AlignmentState(alignment);
165 // if alignment starts after region, no need to keep reading
166 if ( state == BamRandomAccessController::AfterRegion )
169 // read until overlap is found
170 while ( state != BamRandomAccessController::OverlapsRegion ) {
172 // if can't read next alignment
173 if ( !LoadNextAlignment(alignment) )
176 // check alignment's region-overlap state
177 state = m_randomAccessController.AlignmentState(alignment);
179 // if alignment starts after region, no need to keep reading
180 if ( state == BamRandomAccessController::AfterRegion )
184 // if we get here, we found the next 'valid' alignment
185 // (e.g. overlaps current region if one was set, simply the next alignment if not)
186 alignment.SupportData.HasCoreOnly = true;
189 } catch ( BamException& e ) {
190 const string streamError = e.what();
191 const string message = string("encountered error reading BAM alignment: \n\t") + streamError;
192 SetErrorString("BamReader::GetNextAlignmentCore", message);
197 int BamReaderPrivate::GetReferenceCount(void) const {
198 return m_references.size();
201 const RefVector& BamReaderPrivate::GetReferenceData(void) const {
205 // returns RefID for given RefName (returns References.size() if not found)
206 int BamReaderPrivate::GetReferenceID(const string& refName) const {
208 // retrieve names from reference data
209 vector<string> refNames;
210 RefVector::const_iterator refIter = m_references.begin();
211 RefVector::const_iterator refEnd = m_references.end();
212 for ( ; refIter != refEnd; ++refIter)
213 refNames.push_back( (*refIter).RefName );
215 // return 'index-of' refName (or -1 if not found)
216 int index = distance(refNames.begin(), find(refNames.begin(), refNames.end(), refName));
217 if ( index == (int)m_references.size() ) return -1;
221 bool BamReaderPrivate::HasIndex(void) const {
222 return m_randomAccessController.HasIndex();
225 bool BamReaderPrivate::IsOpen(void) const {
226 return m_stream.IsOpen();
229 // load BAM header data
230 void BamReaderPrivate::LoadHeaderData(void) {
231 m_header.Load(&m_stream);
234 // populates BamAlignment with alignment data under file pointer, returns success/fail
235 bool BamReaderPrivate::LoadNextAlignment(BamAlignment& alignment) {
237 // read in the 'block length' value, make sure it's not zero
238 char buffer[sizeof(uint32_t)];
239 fill_n(buffer, sizeof(uint32_t), 0);
240 m_stream.Read(buffer, sizeof(uint32_t));
241 alignment.SupportData.BlockLength = BamTools::UnpackUnsignedInt(buffer);
242 if ( m_isBigEndian ) BamTools::SwapEndian_32(alignment.SupportData.BlockLength);
243 if ( alignment.SupportData.BlockLength == 0 )
246 // read in core alignment data, make sure the right size of data was read
247 char x[Constants::BAM_CORE_SIZE];
248 if ( m_stream.Read(x, Constants::BAM_CORE_SIZE) != Constants::BAM_CORE_SIZE )
251 // swap core endian-ness if necessary
252 if ( m_isBigEndian ) {
253 for ( unsigned int i = 0; i < Constants::BAM_CORE_SIZE; i+=sizeof(uint32_t) )
254 BamTools::SwapEndian_32p(&x[i]);
257 // set BamAlignment 'core' and 'support' data
258 alignment.RefID = BamTools::UnpackSignedInt(&x[0]);
259 alignment.Position = BamTools::UnpackSignedInt(&x[4]);
261 unsigned int tempValue = BamTools::UnpackUnsignedInt(&x[8]);
262 alignment.Bin = tempValue >> 16;
263 alignment.MapQuality = tempValue >> 8 & 0xff;
264 alignment.SupportData.QueryNameLength = tempValue & 0xff;
266 tempValue = BamTools::UnpackUnsignedInt(&x[12]);
267 alignment.AlignmentFlag = tempValue >> 16;
268 alignment.SupportData.NumCigarOperations = tempValue & 0xffff;
270 alignment.SupportData.QuerySequenceLength = BamTools::UnpackUnsignedInt(&x[16]);
271 alignment.MateRefID = BamTools::UnpackSignedInt(&x[20]);
272 alignment.MatePosition = BamTools::UnpackSignedInt(&x[24]);
273 alignment.InsertSize = BamTools::UnpackSignedInt(&x[28]);
275 // set BamAlignment length
276 alignment.Length = alignment.SupportData.QuerySequenceLength;
278 // read in character data - make sure proper data size was read
279 bool readCharDataOK = false;
280 const unsigned int dataLength = alignment.SupportData.BlockLength - Constants::BAM_CORE_SIZE;
281 RaiiBuffer allCharData(dataLength);
283 if ( m_stream.Read(allCharData.Buffer, dataLength) == dataLength ) {
285 // store 'allCharData' in supportData structure
286 alignment.SupportData.AllCharData.assign((const char*)allCharData.Buffer, dataLength);
289 readCharDataOK = true;
292 // need to calculate this here so that BamAlignment::GetEndPosition() performs correctly,
293 // even when GetNextAlignmentCore() is called
294 const unsigned int cigarDataOffset = alignment.SupportData.QueryNameLength;
295 uint32_t* cigarData = (uint32_t*)(allCharData.Buffer + cigarDataOffset);
297 alignment.CigarData.clear();
298 alignment.CigarData.reserve(alignment.SupportData.NumCigarOperations);
299 for ( unsigned int i = 0; i < alignment.SupportData.NumCigarOperations; ++i ) {
301 // swap endian-ness if necessary
302 if ( m_isBigEndian ) BamTools::SwapEndian_32(cigarData[i]);
304 // build CigarOp structure
305 op.Length = (cigarData[i] >> Constants::BAM_CIGAR_SHIFT);
306 op.Type = Constants::BAM_CIGAR_LOOKUP[ (cigarData[i] & Constants::BAM_CIGAR_MASK) ];
309 alignment.CigarData.push_back(op);
313 // return success/failure
314 return readCharDataOK;
317 // loads reference data from BAM file
318 bool BamReaderPrivate::LoadReferenceData(void) {
320 // get number of reference sequences
321 char buffer[sizeof(uint32_t)];
322 m_stream.Read(buffer, sizeof(uint32_t));
323 uint32_t numberRefSeqs = BamTools::UnpackUnsignedInt(buffer);
324 if ( m_isBigEndian ) BamTools::SwapEndian_32(numberRefSeqs);
325 m_references.reserve((int)numberRefSeqs);
327 // iterate over all references in header
328 for ( unsigned int i = 0; i != numberRefSeqs; ++i ) {
330 // get length of reference name
331 m_stream.Read(buffer, sizeof(uint32_t));
332 uint32_t refNameLength = BamTools::UnpackUnsignedInt(buffer);
333 if ( m_isBigEndian ) BamTools::SwapEndian_32(refNameLength);
334 RaiiBuffer refName(refNameLength);
336 // get reference name and reference sequence length
337 m_stream.Read(refName.Buffer, refNameLength);
338 m_stream.Read(buffer, sizeof(int32_t));
339 int32_t refLength = BamTools::UnpackSignedInt(buffer);
340 if ( m_isBigEndian ) BamTools::SwapEndian_32(refLength);
342 // store data for reference
344 aReference.RefName = (string)((const char*)refName.Buffer);
345 aReference.RefLength = refLength;
346 m_references.push_back(aReference);
353 bool BamReaderPrivate::LocateIndex(const BamIndex::IndexType& preferredType) {
355 if ( m_randomAccessController.LocateIndex(this, preferredType) )
358 const string bracError = m_randomAccessController.GetErrorString();
359 const string message = string("could not locate index: \n\t") + bracError;
360 SetErrorString("BamReader::LocateIndex", message);
365 // opens BAM file (and index)
366 bool BamReaderPrivate::Open(const string& filename) {
370 // make sure we're starting with fresh state
374 m_stream.Open(filename, IBamIODevice::ReadOnly);
380 // store filename & offset of first alignment
381 m_filename = filename;
382 m_alignmentsBeginOffset = m_stream.Tell();
387 } catch ( BamException& e ) {
388 const string error = e.what();
389 const string message = string("could not open file: ") + filename +
391 SetErrorString("BamReader::Open", message);
396 bool BamReaderPrivate::OpenIndex(const std::string& indexFilename) {
398 if ( m_randomAccessController.OpenIndex(indexFilename, this) )
401 const string bracError = m_randomAccessController.GetErrorString();
402 const string message = string("could not open index: \n\t") + bracError;
403 SetErrorString("BamReader::OpenIndex", message);
408 // returns BAM file pointer to beginning of alignment data
409 bool BamReaderPrivate::Rewind(void) {
412 m_randomAccessController.ClearRegion();
414 // return status of seeking back to first alignment
415 if ( Seek(m_alignmentsBeginOffset) )
418 const string currentError = m_errorString;
419 const string message = string("could not rewind: \n\t") + currentError;
420 SetErrorString("BamReader::Rewind", message);
425 bool BamReaderPrivate::Seek(const int64_t& position) {
427 // skip if BAM file not open
429 SetErrorString("BamReader::Seek", "cannot seek on unopened BAM file");
434 m_stream.Seek(position);
437 catch ( BamException& e ) {
438 const string streamError = e.what();
439 const string message = string("could not seek in BAM file: \n\t") + streamError;
440 SetErrorString("BamReader::Seek", message);
445 void BamReaderPrivate::SetErrorString(const string& where, const string& what) {
446 static const string SEPARATOR = ": ";
447 m_errorString = where + SEPARATOR + what;
450 void BamReaderPrivate::SetIndex(BamIndex* index) {
451 m_randomAccessController.SetIndex(index);
454 // sets current region & attempts to jump to it
455 // returns success/failure
456 bool BamReaderPrivate::SetRegion(const BamRegion& region) {
458 if ( m_randomAccessController.SetRegion(region, m_references.size()) )
461 const string bracError = m_randomAccessController.GetErrorString();
462 const string message = string("could not set region: \n\t") + bracError;
463 SetErrorString("BamReader::SetRegion", message);
468 int64_t BamReaderPrivate::Tell(void) const {
469 return m_stream.Tell();