1 // ***************************************************************************
2 // BamReader_p.cpp (c) 2009 Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // All rights reserved.
5 // ---------------------------------------------------------------------------
6 // Last modified: 19 November 2010 (DB)
7 // ---------------------------------------------------------------------------
8 // Provides the basic functionality for reading BAM files
9 // ***************************************************************************
11 #include <api/BamReader.h>
12 #include <api/BamReader_p.h>
14 using namespace BamTools;
15 using namespace BamTools::Internal;
24 BamReaderPrivate::BamReaderPrivate(BamReader* parent)
28 , AlignmentsBeginOffset(0)
30 , IndexCacheMode(BamIndex::LimitedIndexCaching)
31 , HasAlignmentsInRegion(true)
33 , DNA_LOOKUP("=ACMGRSVTWYHKDBN")
34 , CIGAR_LOOKUP("MIDNSHP")
36 IsBigEndian = SystemIsBigEndian();
40 BamReaderPrivate::~BamReaderPrivate(void) {
44 // adjusts requested region if necessary (depending on where data actually begins)
45 void BamReaderPrivate::AdjustRegion(BamRegion& region) {
47 // check for valid index first
48 if ( Index == 0 ) return;
50 // see if any references in region have alignments
51 HasAlignmentsInRegion = false;
52 int currentId = region.LeftRefID;
53 while ( currentId <= region.RightRefID ) {
54 HasAlignmentsInRegion = Index->HasAlignments(currentId);
55 if ( HasAlignmentsInRegion ) break;
59 // if no data found on any reference in region
60 if ( !HasAlignmentsInRegion ) return;
62 // if left bound of desired region had no data, use first reference that had data
63 // otherwise, leave requested region as-is
64 if ( currentId != region.LeftRefID ) {
65 region.LeftRefID = currentId;
66 region.LeftPosition = 0;
70 // fills out character data for BamAlignment data
71 bool BamReaderPrivate::BuildCharData(BamAlignment& bAlignment) {
73 // calculate character lengths/offsets
74 const unsigned int dataLength = bAlignment.SupportData.BlockLength - BAM_CORE_SIZE;
75 const unsigned int seqDataOffset = bAlignment.SupportData.QueryNameLength + (bAlignment.SupportData.NumCigarOperations * 4);
76 const unsigned int qualDataOffset = seqDataOffset + (bAlignment.SupportData.QuerySequenceLength+1)/2;
77 const unsigned int tagDataOffset = qualDataOffset + bAlignment.SupportData.QuerySequenceLength;
78 const unsigned int tagDataLength = dataLength - tagDataOffset;
80 // set up char buffers
81 const char* allCharData = bAlignment.SupportData.AllCharData.data();
82 const char* seqData = ((const char*)allCharData) + seqDataOffset;
83 const char* qualData = ((const char*)allCharData) + qualDataOffset;
84 char* tagData = ((char*)allCharData) + tagDataOffset;
86 // store alignment name (relies on null char in name as terminator)
87 bAlignment.Name.assign((const char*)(allCharData));
89 // save query sequence
90 bAlignment.QueryBases.clear();
91 bAlignment.QueryBases.reserve(bAlignment.SupportData.QuerySequenceLength);
92 for (unsigned int i = 0; i < bAlignment.SupportData.QuerySequenceLength; ++i) {
93 char singleBase = DNA_LOOKUP[ ( (seqData[(i/2)] >> (4*(1-(i%2)))) & 0xf ) ];
94 bAlignment.QueryBases.append(1, singleBase);
97 // save qualities, converting from numeric QV to 'FASTQ-style' ASCII character
98 bAlignment.Qualities.clear();
99 bAlignment.Qualities.reserve(bAlignment.SupportData.QuerySequenceLength);
100 for (unsigned int i = 0; i < bAlignment.SupportData.QuerySequenceLength; ++i) {
101 char singleQuality = (char)(qualData[i]+33);
102 bAlignment.Qualities.append(1, singleQuality);
105 // if QueryBases is empty (and this is a allowed case)
106 if ( bAlignment.QueryBases.empty() )
107 bAlignment.AlignedBases = bAlignment.QueryBases;
109 // if QueryBases contains data, then build AlignedBases using CIGAR data
112 // resize AlignedBases
113 bAlignment.AlignedBases.clear();
114 bAlignment.AlignedBases.reserve(bAlignment.SupportData.QuerySequenceLength);
116 // iterate over CigarOps
118 vector<CigarOp>::const_iterator cigarIter = bAlignment.CigarData.begin();
119 vector<CigarOp>::const_iterator cigarEnd = bAlignment.CigarData.end();
120 for ( ; cigarIter != cigarEnd; ++cigarIter ) {
122 const CigarOp& op = (*cigarIter);
127 bAlignment.AlignedBases.append(bAlignment.QueryBases.substr(k, op.Length)); // for 'M', 'I' - write bases
131 k += op.Length; // for 'S' - soft clip, skip over query bases
135 bAlignment.AlignedBases.append(op.Length, '-'); // for 'D' - write gap character
139 bAlignment.AlignedBases.append( op.Length, '*' ); // for 'P' - write padding character
143 bAlignment.AlignedBases.append( op.Length, 'N' ); // for 'N' - write N's, skip bases in original query sequence
147 break; // for 'H' - hard clip, do nothing to AlignedBases, move to next op
150 fprintf(stderr, "ERROR: Invalid Cigar op type\n"); // shouldn't get here
156 // -----------------------
157 // Added: 3-25-2010 DB
158 // Fixed: endian-correctness for tag data
159 // -----------------------
162 while ( (unsigned int)i < tagDataLength ) {
164 i += 2; // skip tag type (e.g. "RG", "NM", etc)
165 uint8_t type = toupper(tagData[i]); // lower & upper case letters have same meaning
166 ++i; // skip value type
176 SwapEndian_16p(&tagData[i]);
177 i += sizeof(uint16_t);
182 SwapEndian_32p(&tagData[i]);
183 i += sizeof(uint32_t);
187 SwapEndian_64p(&tagData[i]);
188 i += sizeof(uint64_t);
193 while (tagData[i]) { ++i; }
194 ++i; // increment one more for null terminator
198 fprintf(stderr, "ERROR: Invalid tag value type\n"); // shouldn't get here
205 bAlignment.TagData.clear();
206 bAlignment.TagData.resize(tagDataLength);
207 memcpy((char*)bAlignment.TagData.data(), tagData, tagDataLength);
209 // clear the core-only flag
210 bAlignment.SupportData.HasCoreOnly = false;
216 // clear index data structure
217 void BamReaderPrivate::ClearIndex(void) {
223 // closes the BAM file
224 void BamReaderPrivate::Close(void) {
226 // close BGZF file stream
229 // clear out index data
232 // clear out header data
239 // clear out region flags
243 // creates index for BAM file, saves to file
244 // default behavior is to create the BAM standard index (".bai")
245 // set flag to false to create the BamTools-specific index (".bti")
246 bool BamReaderPrivate::CreateIndex(bool useStandardIndex) {
248 // clear out prior index data
251 // create index based on type requested
252 if ( useStandardIndex )
253 Index = new BamStandardIndex(&mBGZF, Parent);
255 Index = new BamToolsIndex(&mBGZF, Parent);
257 // set index cache mode to full for writing
258 Index->SetCacheMode(BamIndex::FullIndexCaching);
262 ok &= Index->Build();
265 // mark empty references
268 // attempt to save index data to file
269 ok &= Index->Write(Filename);
271 // set client's desired index cache mode
272 Index->SetCacheMode(IndexCacheMode);
274 // return success/fail of both building & writing index
278 const string BamReaderPrivate::GetHeaderText(void) const {
283 // return m_header->Text();
285 // return string("");
288 // get next alignment (from specified region, if given)
289 bool BamReaderPrivate::GetNextAlignment(BamAlignment& bAlignment) {
291 // if valid alignment found, attempt to parse char data, and return success/failure
292 if ( GetNextAlignmentCore(bAlignment) )
293 return BuildCharData(bAlignment);
295 // no valid alignment found
299 // retrieves next available alignment core data (returns success/fail)
300 // ** DOES NOT parse any character data (read name, bases, qualities, tag data)
301 // these can be accessed, if necessary, from the supportData
302 // useful for operations requiring ONLY positional or other alignment-related information
303 bool BamReaderPrivate::GetNextAlignmentCore(BamAlignment& bAlignment) {
305 // if region is set but has no alignments
306 if ( !Region.isNull() && !HasAlignmentsInRegion )
309 // if valid alignment available
310 if ( LoadNextAlignment(bAlignment) ) {
312 // set core-only flag
313 bAlignment.SupportData.HasCoreOnly = true;
315 // if region not specified with at least a left boundary, return success
316 if ( !Region.isLeftBoundSpecified() ) return true;
318 // determine region state (before, within, after)
319 BamReaderPrivate::RegionState state = IsOverlap(bAlignment);
321 // if alignment lies after region, return false
322 if ( state == AFTER_REGION ) return false;
324 while ( state != WITHIN_REGION ) {
325 // if no valid alignment available (likely EOF) return failure
326 if ( !LoadNextAlignment(bAlignment) ) return false;
327 // if alignment lies after region, return false (no available read within region)
328 state = IsOverlap(bAlignment);
329 if ( state == AFTER_REGION ) return false;
332 // return success (alignment found that overlaps region)
336 // no valid alignment
340 // returns RefID for given RefName (returns References.size() if not found)
341 int BamReaderPrivate::GetReferenceID(const string& refName) const {
343 // retrieve names from reference data
344 vector<string> refNames;
345 RefVector::const_iterator refIter = References.begin();
346 RefVector::const_iterator refEnd = References.end();
347 for ( ; refIter != refEnd; ++refIter)
348 refNames.push_back( (*refIter).RefName );
350 // return 'index-of' refName ( if not found, returns refNames.size() )
351 return distance(refNames.begin(), find(refNames.begin(), refNames.end(), refName));
354 // returns region state - whether alignment ends before, overlaps, or starts after currently specified region
355 // this *internal* method should ONLY called when (at least) IsLeftBoundSpecified == true
356 BamReaderPrivate::RegionState BamReaderPrivate::IsOverlap(BamAlignment& bAlignment) {
358 // if alignment is on any reference sequence before left bound
359 if ( bAlignment.RefID < Region.LeftRefID ) return BEFORE_REGION;
361 // if alignment starts on left bound reference
362 else if ( bAlignment.RefID == Region.LeftRefID ) {
364 // if alignment starts at or after left boundary
365 if ( bAlignment.Position >= Region.LeftPosition) {
367 // if right boundary is specified AND
368 // left/right boundaries are on same reference AND
369 // alignment starts past right boundary
370 if ( Region.isRightBoundSpecified() &&
371 Region.LeftRefID == Region.RightRefID &&
372 bAlignment.Position > Region.RightPosition )
375 // otherwise, alignment is within region
376 return WITHIN_REGION;
379 // alignment starts before left boundary
381 // check if alignment overlaps left boundary
382 if ( bAlignment.GetEndPosition() >= Region.LeftPosition ) return WITHIN_REGION;
383 else return BEFORE_REGION;
387 // alignment starts on a reference after the left bound
390 // if region has a right boundary
391 if ( Region.isRightBoundSpecified() ) {
393 // alignment is on reference between boundaries
394 if ( bAlignment.RefID < Region.RightRefID ) return WITHIN_REGION;
396 // alignment is on reference after right boundary
397 else if ( bAlignment.RefID > Region.RightRefID ) return AFTER_REGION;
399 // alignment is on right bound reference
401 // check if alignment starts before or at right boundary
402 if ( bAlignment.Position <= Region.RightPosition ) return WITHIN_REGION;
403 else return AFTER_REGION;
407 // otherwise, alignment is after left bound reference, but there is no right boundary
408 else return WITHIN_REGION;
412 // load BAM header data
413 void BamReaderPrivate::LoadHeaderData(void) {
415 // m_header = new BamHeader(&mBGZF);
416 // bool headerLoadedOk = m_header->Load();
417 // if ( !headerLoadedOk )
418 // cerr << "BamReader could not load header" << endl;
420 // check to see if proper BAM header
422 if (mBGZF.Read(buffer, 4) != 4) {
423 fprintf(stderr, "Could not read header type\n");
427 if (strncmp(buffer, "BAM\001", 4)) {
428 fprintf(stderr, "wrong header type!\n");
432 // get BAM header text length
433 mBGZF.Read(buffer, 4);
434 unsigned int headerTextLength = BgzfData::UnpackUnsignedInt(buffer);
435 if ( IsBigEndian ) SwapEndian_32(headerTextLength);
437 // get BAM header text
438 char* headerText = (char*)calloc(headerTextLength + 1, 1);
439 mBGZF.Read(headerText, headerTextLength);
440 HeaderText = (string)((const char*)headerText);
442 // clean up calloc-ed temp variable
446 // load existing index data from BAM index file (".bti" OR ".bai"), return success/fail
447 bool BamReaderPrivate::LoadIndex(const bool lookForIndex, const bool preferStandardIndex) {
449 // clear out any existing index data
452 // if no index filename provided, so we need to look for available index files
453 if ( IndexFilename.empty() ) {
455 // attempt to load BamIndex based on current Filename provided & preferStandardIndex flag
456 const BamIndex::PreferredIndexType type = (preferStandardIndex ? BamIndex::STANDARD : BamIndex::BAMTOOLS);
457 Index = BamIndex::FromBamFilename(Filename, &mBGZF, Parent, type);
459 // if null, return failure
460 if ( Index == 0 ) return false;
462 // generate proper IndexFilename based on type of index created
463 IndexFilename = Filename + Index->Extension();
468 // attempt to load BamIndex based on IndexFilename provided by client
469 Index = BamIndex::FromIndexFilename(IndexFilename, &mBGZF, Parent);
471 // if null, return failure
472 if ( Index == 0 ) return false;
475 // set cache mode for BamIndex
476 Index->SetCacheMode(IndexCacheMode);
478 // loading the index data from file
479 HasIndex = Index->Load(IndexFilename);
481 // mark empty references
484 // return index status
488 // populates BamAlignment with alignment data under file pointer, returns success/fail
489 bool BamReaderPrivate::LoadNextAlignment(BamAlignment& bAlignment) {
491 // read in the 'block length' value, make sure it's not zero
493 mBGZF.Read(buffer, 4);
494 bAlignment.SupportData.BlockLength = BgzfData::UnpackUnsignedInt(buffer);
495 if ( IsBigEndian ) { SwapEndian_32(bAlignment.SupportData.BlockLength); }
496 if ( bAlignment.SupportData.BlockLength == 0 ) return false;
498 // read in core alignment data, make sure the right size of data was read
499 char x[BAM_CORE_SIZE];
500 if ( mBGZF.Read(x, BAM_CORE_SIZE) != BAM_CORE_SIZE ) return false;
503 for ( int i = 0; i < BAM_CORE_SIZE; i+=sizeof(uint32_t) )
504 SwapEndian_32p(&x[i]);
507 // set BamAlignment 'core' and 'support' data
508 bAlignment.RefID = BgzfData::UnpackSignedInt(&x[0]);
509 bAlignment.Position = BgzfData::UnpackSignedInt(&x[4]);
511 unsigned int tempValue = BgzfData::UnpackUnsignedInt(&x[8]);
512 bAlignment.Bin = tempValue >> 16;
513 bAlignment.MapQuality = tempValue >> 8 & 0xff;
514 bAlignment.SupportData.QueryNameLength = tempValue & 0xff;
516 tempValue = BgzfData::UnpackUnsignedInt(&x[12]);
517 bAlignment.AlignmentFlag = tempValue >> 16;
518 bAlignment.SupportData.NumCigarOperations = tempValue & 0xffff;
520 bAlignment.SupportData.QuerySequenceLength = BgzfData::UnpackUnsignedInt(&x[16]);
521 bAlignment.MateRefID = BgzfData::UnpackSignedInt(&x[20]);
522 bAlignment.MatePosition = BgzfData::UnpackSignedInt(&x[24]);
523 bAlignment.InsertSize = BgzfData::UnpackSignedInt(&x[28]);
525 // set BamAlignment length
526 bAlignment.Length = bAlignment.SupportData.QuerySequenceLength;
528 // read in character data - make sure proper data size was read
529 bool readCharDataOK = false;
530 const unsigned int dataLength = bAlignment.SupportData.BlockLength - BAM_CORE_SIZE;
531 char* allCharData = (char*)calloc(sizeof(char), dataLength);
533 if ( mBGZF.Read(allCharData, dataLength) == (signed int)dataLength) {
535 // store 'allCharData' in supportData structure
536 bAlignment.SupportData.AllCharData.assign((const char*)allCharData, dataLength);
539 readCharDataOK = true;
542 // need to calculate this here so that BamAlignment::GetEndPosition() performs correctly,
543 // even when GetNextAlignmentCore() is called
544 const unsigned int cigarDataOffset = bAlignment.SupportData.QueryNameLength;
545 uint32_t* cigarData = (uint32_t*)(allCharData + cigarDataOffset);
547 bAlignment.CigarData.clear();
548 bAlignment.CigarData.reserve(bAlignment.SupportData.NumCigarOperations);
549 for (unsigned int i = 0; i < bAlignment.SupportData.NumCigarOperations; ++i) {
552 if ( IsBigEndian ) SwapEndian_32(cigarData[i]);
554 // build CigarOp structure
555 op.Length = (cigarData[i] >> BAM_CIGAR_SHIFT);
556 op.Type = CIGAR_LOOKUP[ (cigarData[i] & BAM_CIGAR_MASK) ];
559 bAlignment.CigarData.push_back(op);
564 return readCharDataOK;
567 // loads reference data from BAM file
568 void BamReaderPrivate::LoadReferenceData(void) {
570 // get number of reference sequences
572 mBGZF.Read(buffer, 4);
573 unsigned int numberRefSeqs = BgzfData::UnpackUnsignedInt(buffer);
574 if ( IsBigEndian ) SwapEndian_32(numberRefSeqs);
575 if ( numberRefSeqs == 0 ) return;
576 References.reserve((int)numberRefSeqs);
578 // iterate over all references in header
579 for (unsigned int i = 0; i != numberRefSeqs; ++i) {
581 // get length of reference name
582 mBGZF.Read(buffer, 4);
583 unsigned int refNameLength = BgzfData::UnpackUnsignedInt(buffer);
584 if ( IsBigEndian ) SwapEndian_32(refNameLength);
585 char* refName = (char*)calloc(refNameLength, 1);
587 // get reference name and reference sequence length
588 mBGZF.Read(refName, refNameLength);
589 mBGZF.Read(buffer, 4);
590 int refLength = BgzfData::UnpackSignedInt(buffer);
591 if ( IsBigEndian ) SwapEndian_32(refLength);
593 // store data for reference
595 aReference.RefName = (string)((const char*)refName);
596 aReference.RefLength = refLength;
597 References.push_back(aReference);
599 // clean up calloc-ed temp variable
604 // mark references with no alignment data
605 void BamReaderPrivate::MarkReferences(void) {
607 // ensure index is available
608 if ( !HasIndex ) return;
610 // mark empty references
611 for ( int i = 0; i < (int)References.size(); ++i )
612 References.at(i).RefHasAlignments = Index->HasAlignments(i);
615 // opens BAM file (and index)
616 bool BamReaderPrivate::Open(const string& filename, const string& indexFilename, const bool lookForIndex, const bool preferStandardIndex) {
620 IndexFilename = indexFilename;
622 // open the BGZF file for reading, return false on failure
623 if ( !mBGZF.Open(filename, "rb") ) return false;
625 // retrieve header text & reference data
629 // store file offset of first alignment
630 AlignmentsBeginOffset = mBGZF.Tell();
632 // if no index filename provided
633 if ( IndexFilename.empty() ) {
635 // client did not specify that index SHOULD be found
636 // useful for cases where sequential access is all that is required
637 if ( !lookForIndex ) return true;
639 // otherwise, look for index file, return success/fail
640 return LoadIndex(lookForIndex, preferStandardIndex) ;
643 // client supplied an index filename
644 // attempt to load index data, return success/fail
645 return LoadIndex(lookForIndex, preferStandardIndex);
648 // returns BAM file pointer to beginning of alignment data
649 bool BamReaderPrivate::Rewind(void) {
651 // rewind to first alignment, return false if unable to seek
652 if ( !mBGZF.Seek(AlignmentsBeginOffset) ) return false;
654 // retrieve first alignment data, return false if unable to read
656 if ( !LoadNextAlignment(al) ) return false;
658 // reset default region info using first alignment in file
660 HasAlignmentsInRegion = true;
662 // rewind back to beginning of first alignment
663 // return success/fail of seek
664 return mBGZF.Seek(AlignmentsBeginOffset);
667 // change the index caching behavior
668 void BamReaderPrivate::SetIndexCacheMode(const BamIndex::BamIndexCacheMode mode) {
669 IndexCacheMode = mode;
670 if ( Index == 0 ) return;
671 Index->SetCacheMode(mode);
674 // asks Index to attempt a Jump() to specified region
675 // returns success/failure
676 bool BamReaderPrivate::SetRegion(const BamRegion& region) {
678 // clear out any prior BamReader region data
680 // N.B. - this is cleared so that BamIndex now has free reign to call
681 // GetNextAlignmentCore() and do overlap checking without worrying about BamReader
682 // performing any overlap checking of its own and moving on to the next read... Calls
683 // to GetNextAlignmentCore() with no Region set, simply return the next alignment.
684 // This ensures that the Index is able to do just that. (All without exposing
685 // LoadNextAlignment() to the public API, and potentially confusing clients with the nomenclature)
688 // check for existing index
689 if ( !HasIndex ) return false;
691 // adjust region if necessary to reflect where data actually begins
692 BamRegion adjustedRegion(region);
693 AdjustRegion(adjustedRegion);
695 // if no data present, return true
696 // not an error, but BamReader knows that no data is there for future alignment access
697 // (this is useful in a MultiBamReader setting where some BAM files may lack data in regions
698 // that other BAMs have data)
699 if ( !HasAlignmentsInRegion ) {
700 Region = adjustedRegion;
704 // attempt jump to user-specified region return false if jump could not be performed at all
705 // (invalid index, unknown reference, etc)
707 // Index::Jump() is allowed to modify the HasAlignmentsInRegion flag
708 // * This covers case where a region is requested that lies beyond the last alignment on a reference
709 // If this occurs, any subsequent calls to GetNexAlignment[Core] simply return false
710 // BamMultiReader is then able to successfully pull alignments from a region from multiple files
711 // even if one or more have no data.
712 if ( !Index->Jump(adjustedRegion, &HasAlignmentsInRegion) ) return false;
714 // save region and return success
715 Region = adjustedRegion;