1 // ***************************************************************************
\r
2 // BamReader.cpp (c) 2009 Derek Barnett, Michael Str�mberg
\r
3 // Marth Lab, Department of Biology, Boston College
\r
4 // All rights reserved.
\r
5 // ---------------------------------------------------------------------------
\r
6 // Last modified: 15 July 2010 (DB)
\r
7 // ---------------------------------------------------------------------------
\r
8 // Uses BGZF routines were adapted from the bgzf.c code developed at the Broad
\r
10 // ---------------------------------------------------------------------------
\r
11 // Provides the basic functionality for reading BAM files
\r
12 // ***************************************************************************
\r
15 #include <algorithm>
\r
21 // BamTools includes
\r
23 #include "BamReader.h"
\r
24 #include "BamIndex.h"
\r
25 using namespace BamTools;
\r
26 using namespace std;
\r
28 struct BamReader::BamReaderPrivate {
\r
30 // -------------------------------
\r
31 // structs, enums, typedefs
\r
32 // -------------------------------
\r
33 enum RegionState { BEFORE_REGION = 0
\r
38 // -------------------------------
\r
40 // -------------------------------
\r
42 // general file data
\r
47 RefVector References;
\r
49 int64_t AlignmentsBeginOffset;
\r
51 string IndexFilename;
\r
56 // user-specified region values
\r
58 bool IsLeftBoundSpecified;
\r
59 bool IsRightBoundSpecified;
\r
61 bool IsRegionSpecified;
\r
68 // BAM character constants
\r
69 const char* DNA_LOOKUP;
\r
70 const char* CIGAR_LOOKUP;
\r
72 // -------------------------------
\r
73 // constructor & destructor
\r
74 // -------------------------------
\r
75 BamReaderPrivate(BamReader* parent);
\r
76 ~BamReaderPrivate(void);
\r
78 // -------------------------------
\r
79 // "public" interface
\r
80 // -------------------------------
\r
84 bool Jump(int refID, int position = 0);
\r
85 bool Open(const string& filename, const string& indexFilename = "");
\r
87 bool SetRegion(const BamRegion& region);
\r
89 // access alignment data
\r
90 bool GetNextAlignment(BamAlignment& bAlignment);
\r
91 bool GetNextAlignmentCore(BamAlignment& bAlignment);
\r
93 // access auxiliary data
\r
94 int GetReferenceID(const string& refName) const;
\r
97 bool CreateIndex(bool useDefaultIndex);
\r
99 // -------------------------------
\r
100 // internal methods
\r
101 // -------------------------------
\r
103 // *** reading alignments and auxiliary data *** //
\r
105 // fills out character data for BamAlignment data
\r
106 bool BuildCharData(BamAlignment& bAlignment);
\r
107 // checks to see if alignment overlaps current region
\r
108 RegionState IsOverlap(BamAlignment& bAlignment);
\r
109 // retrieves header text from BAM file
\r
110 void LoadHeaderData(void);
\r
111 // retrieves BAM alignment under file pointer
\r
112 bool LoadNextAlignment(BamAlignment& bAlignment);
\r
113 // builds reference data structure from BAM file
\r
114 void LoadReferenceData(void);
\r
116 // *** index file handling *** //
\r
118 // clear out inernal index data structure
\r
119 void ClearIndex(void);
\r
120 // loads index from BAM index file
\r
121 bool LoadIndex(void);
\r
124 // -----------------------------------------------------
\r
125 // BamReader implementation (wrapper around BRPrivate)
\r
126 // -----------------------------------------------------
\r
128 BamReader::BamReader(void) {
\r
129 d = new BamReaderPrivate(this);
\r
133 BamReader::~BamReader(void) {
\r
139 void BamReader::Close(void) { d->Close(); }
\r
140 bool BamReader::IsOpen(void) const { return d->mBGZF.IsOpen; }
\r
141 bool BamReader::Jump(int refID, int position) {
\r
142 d->Region.LeftRefID = refID;
\r
143 d->Region.LeftPosition = position;
\r
144 d->IsLeftBoundSpecified = true;
\r
145 d->IsRightBoundSpecified = false;
\r
146 return d->Jump(refID, position);
\r
148 bool BamReader::Open(const string& filename, const string& indexFilename) { return d->Open(filename, indexFilename); }
\r
149 bool BamReader::Rewind(void) { return d->Rewind(); }
\r
150 bool BamReader::SetRegion(const BamRegion& region) { return d->SetRegion(region); }
\r
151 bool BamReader::SetRegion(const int& leftRefID, const int& leftBound, const int& rightRefID, const int& rightBound) {
\r
152 return d->SetRegion( BamRegion(leftRefID, leftBound, rightRefID, rightBound) );
\r
155 // access alignment data
\r
156 bool BamReader::GetNextAlignment(BamAlignment& bAlignment) { return d->GetNextAlignment(bAlignment); }
\r
157 bool BamReader::GetNextAlignmentCore(BamAlignment& bAlignment) { return d->GetNextAlignmentCore(bAlignment); }
\r
159 // access auxiliary data
\r
160 const string BamReader::GetHeaderText(void) const { return d->HeaderText; }
\r
161 int BamReader::GetReferenceCount(void) const { return d->References.size(); }
\r
162 const RefVector& BamReader::GetReferenceData(void) const { return d->References; }
\r
163 int BamReader::GetReferenceID(const string& refName) const { return d->GetReferenceID(refName); }
\r
164 const std::string BamReader::GetFilename(void) const { return d->Filename; }
\r
166 // index operations
\r
167 bool BamReader::CreateIndex(bool useDefaultIndex) { return d->CreateIndex(useDefaultIndex); }
\r
169 // -----------------------------------------------------
\r
170 // BamReaderPrivate implementation
\r
171 // -----------------------------------------------------
\r
174 BamReader::BamReaderPrivate::BamReaderPrivate(BamReader* parent)
\r
176 , IsIndexLoaded(false)
\r
177 , AlignmentsBeginOffset(0)
\r
178 , IsLeftBoundSpecified(false)
\r
179 , IsRightBoundSpecified(false)
\r
180 , IsRegionSpecified(false)
\r
184 , DNA_LOOKUP("=ACMGRSVTWYHKDBN")
\r
185 , CIGAR_LOOKUP("MIDNSHP")
\r
187 IsBigEndian = SystemIsBigEndian();
\r
191 BamReader::BamReaderPrivate::~BamReaderPrivate(void) {
\r
195 bool BamReader::BamReaderPrivate::BuildCharData(BamAlignment& bAlignment) {
\r
197 // calculate character lengths/offsets
\r
198 const unsigned int dataLength = bAlignment.SupportData.BlockLength - BAM_CORE_SIZE;
\r
199 const unsigned int cigarDataOffset = bAlignment.SupportData.QueryNameLength;
\r
200 const unsigned int seqDataOffset = bAlignment.SupportData.QueryNameLength + (bAlignment.SupportData.NumCigarOperations * 4);
\r
201 const unsigned int qualDataOffset = seqDataOffset + (bAlignment.SupportData.QuerySequenceLength+1)/2;
\r
202 const unsigned int tagDataOffset = qualDataOffset + bAlignment.SupportData.QuerySequenceLength;
\r
203 const unsigned int tagDataLength = dataLength - tagDataOffset;
\r
205 // set up char buffers
\r
206 const char* allCharData = bAlignment.SupportData.AllCharData.data();
\r
207 uint32_t* cigarData = (uint32_t*)(allCharData + cigarDataOffset);
\r
208 const char* seqData = ((const char*)allCharData) + seqDataOffset;
\r
209 const char* qualData = ((const char*)allCharData) + qualDataOffset;
\r
210 char* tagData = ((char*)allCharData) + tagDataOffset;
\r
212 // store alignment name (depends on null char as terminator)
\r
213 bAlignment.Name.assign((const char*)(allCharData));
\r
217 bAlignment.CigarData.clear();
\r
218 bAlignment.CigarData.reserve(bAlignment.SupportData.NumCigarOperations);
\r
219 for (unsigned int i = 0; i < bAlignment.SupportData.NumCigarOperations; ++i) {
\r
221 // swap if necessary
\r
222 if ( IsBigEndian ) { SwapEndian_32(cigarData[i]); }
\r
224 // build CigarOp structure
\r
225 op.Length = (cigarData[i] >> BAM_CIGAR_SHIFT);
\r
226 op.Type = CIGAR_LOOKUP[ (cigarData[i] & BAM_CIGAR_MASK) ];
\r
229 bAlignment.CigarData.push_back(op);
\r
233 // save query sequence
\r
234 bAlignment.QueryBases.clear();
\r
235 bAlignment.QueryBases.reserve(bAlignment.SupportData.QuerySequenceLength);
\r
236 for (unsigned int i = 0; i < bAlignment.SupportData.QuerySequenceLength; ++i) {
\r
237 char singleBase = DNA_LOOKUP[ ( ( seqData[(i/2)] >> (4*(1-(i%2)))) & 0xf ) ];
\r
238 bAlignment.QueryBases.append(1, singleBase);
\r
241 // save qualities, converting from numeric QV to 'FASTQ-style' ASCII character
\r
242 bAlignment.Qualities.clear();
\r
243 bAlignment.Qualities.reserve(bAlignment.SupportData.QuerySequenceLength);
\r
244 for (unsigned int i = 0; i < bAlignment.SupportData.QuerySequenceLength; ++i) {
\r
245 char singleQuality = (char)(qualData[i]+33);
\r
246 bAlignment.Qualities.append(1, singleQuality);
\r
249 // if QueryBases is empty (and this is a allowed case)
\r
250 if ( bAlignment.QueryBases.empty() )
\r
251 bAlignment.AlignedBases = bAlignment.QueryBases;
\r
253 // if QueryBases contains data, then build AlignedBases using CIGAR data
\r
256 // resize AlignedBases
\r
257 bAlignment.AlignedBases.clear();
\r
258 bAlignment.AlignedBases.reserve(bAlignment.SupportData.QuerySequenceLength);
\r
260 // iterate over CigarOps
\r
262 vector<CigarOp>::const_iterator cigarIter = bAlignment.CigarData.begin();
\r
263 vector<CigarOp>::const_iterator cigarEnd = bAlignment.CigarData.end();
\r
264 for ( ; cigarIter != cigarEnd; ++cigarIter ) {
\r
266 const CigarOp& op = (*cigarIter);
\r
271 bAlignment.AlignedBases.append(bAlignment.QueryBases.substr(k, op.Length)); // for 'M', 'I' - write bases
\r
275 k += op.Length; // for 'S' - soft clip, skip over query bases
\r
279 bAlignment.AlignedBases.append(op.Length, '-'); // for 'D' - write gap character
\r
283 bAlignment.AlignedBases.append( op.Length, '*' ); // for 'P' - write padding character
\r
287 bAlignment.AlignedBases.append( op.Length, 'N' ); // for 'N' - write N's, skip bases in original query sequence
\r
291 break; // for 'H' - hard clip, do nothing to AlignedBases, move to next op
\r
294 printf("ERROR: Invalid Cigar op type\n"); // shouldn't get here
\r
300 // -----------------------
\r
301 // Added: 3-25-2010 DB
\r
302 // Fixed: endian-correctness for tag data
\r
303 // -----------------------
\r
304 if ( IsBigEndian ) {
\r
306 while ( (unsigned int)i < tagDataLength ) {
\r
308 i += 2; // skip tag type (e.g. "RG", "NM", etc)
\r
309 uint8_t type = toupper(tagData[i]); // lower & upper case letters have same meaning
\r
310 ++i; // skip value type
\r
320 SwapEndian_16p(&tagData[i]);
\r
321 i += sizeof(uint16_t);
\r
326 SwapEndian_32p(&tagData[i]);
\r
327 i += sizeof(uint32_t);
\r
331 SwapEndian_64p(&tagData[i]);
\r
332 i += sizeof(uint64_t);
\r
337 while (tagData[i]) { ++i; }
\r
338 ++i; // increment one more for null terminator
\r
342 printf("ERROR: Invalid tag value type\n"); // shouldn't get here
\r
349 bAlignment.TagData.clear();
\r
350 bAlignment.TagData.resize(tagDataLength);
\r
351 memcpy((char*)bAlignment.TagData.data(), tagData, tagDataLength);
\r
353 // clear the core-only flag
\r
354 bAlignment.SupportData.HasCoreOnly = false;
\r
360 // clear index data structure
\r
361 void BamReader::BamReaderPrivate::ClearIndex(void) {
\r
366 // closes the BAM file
\r
367 void BamReader::BamReaderPrivate::Close(void) {
\r
369 // close BGZF file stream
\r
372 // clear out index data
\r
375 // clear out header data
\r
376 HeaderText.clear();
\r
378 // clear out region flags
\r
379 IsLeftBoundSpecified = false;
\r
380 IsRightBoundSpecified = false;
\r
381 IsRegionSpecified = false;
\r
384 // create BAM index from BAM file (keep structure in memory) and write to default index output file
\r
385 bool BamReader::BamReaderPrivate::CreateIndex(bool useDefaultIndex) {
\r
387 // clear out prior index data
\r
390 // create default index
\r
391 if ( useDefaultIndex )
\r
392 NewIndex = new BamDefaultIndex(&mBGZF, Parent, IsBigEndian);
\r
393 // create BamTools 'custom' index
\r
395 NewIndex = new BamToolsIndex(&mBGZF, Parent, IsBigEndian);
\r
398 ok &= NewIndex->Build();
\r
399 ok &= NewIndex->Write(Filename);
\r
401 // return success/fail
\r
405 // get next alignment (from specified region, if given)
\r
406 bool BamReader::BamReaderPrivate::GetNextAlignment(BamAlignment& bAlignment) {
\r
408 // if valid alignment found, attempt to parse char data, and return success/failure
\r
409 if ( GetNextAlignmentCore(bAlignment) )
\r
410 return BuildCharData(bAlignment);
\r
412 // no valid alignment found
\r
417 // retrieves next available alignment core data (returns success/fail)
\r
418 // ** DOES NOT parse any character data (read name, bases, qualities, tag data)
\r
419 // these can be accessed, if necessary, from the supportData
\r
420 // useful for operations requiring ONLY positional or other alignment-related information
\r
421 bool BamReader::BamReaderPrivate::GetNextAlignmentCore(BamAlignment& bAlignment) {
\r
423 // if valid alignment available
\r
424 if ( LoadNextAlignment(bAlignment) ) {
\r
426 // set core-only flag
\r
427 bAlignment.SupportData.HasCoreOnly = true;
\r
429 // if region not specified, return success
\r
430 if ( !IsLeftBoundSpecified ) return true;
\r
432 // determine region state (before, within, after)
\r
433 BamReader::BamReaderPrivate::RegionState state = IsOverlap(bAlignment);
\r
435 // if alignment lies after region, return false
\r
436 if ( state == AFTER_REGION )
\r
439 while ( state != WITHIN_REGION ) {
\r
440 // if no valid alignment available (likely EOF) return failure
\r
441 if ( !LoadNextAlignment(bAlignment) ) return false;
\r
442 // if alignment lies after region, return false (no available read within region)
\r
443 state = IsOverlap(bAlignment);
\r
444 if ( state == AFTER_REGION) return false;
\r
448 // return success (alignment found that overlaps region)
\r
452 // no valid alignment
\r
457 // returns RefID for given RefName (returns References.size() if not found)
\r
458 int BamReader::BamReaderPrivate::GetReferenceID(const string& refName) const {
\r
460 // retrieve names from reference data
\r
461 vector<string> refNames;
\r
462 RefVector::const_iterator refIter = References.begin();
\r
463 RefVector::const_iterator refEnd = References.end();
\r
464 for ( ; refIter != refEnd; ++refIter) {
\r
465 refNames.push_back( (*refIter).RefName );
\r
468 // return 'index-of' refName ( if not found, returns refNames.size() )
\r
469 return distance(refNames.begin(), find(refNames.begin(), refNames.end(), refName));
\r
472 // returns region state - whether alignment ends before, overlaps, or starts after currently specified region
\r
473 // this *internal* method should ONLY called when (at least) IsLeftBoundSpecified == true
\r
474 BamReader::BamReaderPrivate::RegionState BamReader::BamReaderPrivate::IsOverlap(BamAlignment& bAlignment) {
\r
476 // --------------------------------------------------
\r
477 // check alignment start against right bound cutoff
\r
479 // if full region of interest was given
\r
480 if ( IsRightBoundSpecified ) {
\r
482 // read starts on right bound reference, but AFTER right bound position
\r
483 if ( bAlignment.RefID == Region.RightRefID && bAlignment.Position > Region.RightPosition )
\r
484 return AFTER_REGION;
\r
486 // if read starts on reference AFTER right bound, return false
\r
487 if ( bAlignment.RefID > Region.RightRefID )
\r
488 return AFTER_REGION;
\r
491 // --------------------------------------------------------
\r
492 // no right bound given OR read starts before right bound
\r
493 // so, check if it overlaps left bound
\r
495 // if read starts on left bound reference AND after left boundary, return success
\r
496 if ( bAlignment.RefID == Region.LeftRefID && bAlignment.Position >= Region.LeftPosition)
\r
497 return WITHIN_REGION;
\r
499 // if read is on any reference sequence before left bound, return false
\r
500 if ( bAlignment.RefID < Region.LeftRefID )
\r
501 return BEFORE_REGION;
\r
503 // --------------------------------------------------------
\r
504 // read is on left bound reference, but starts before left bound position
\r
506 // if it overlaps, return WITHIN_REGION
\r
507 if ( bAlignment.GetEndPosition() >= Region.LeftPosition )
\r
508 return WITHIN_REGION;
\r
509 // else begins before left bound position
\r
511 return BEFORE_REGION;
\r
514 // jumps to specified region(refID, leftBound) in BAM file, returns success/fail
\r
515 bool BamReader::BamReaderPrivate::Jump(int refID, int position) {
\r
517 // -----------------------------------------------------------------------
\r
518 // check for existing index
\r
519 if ( NewIndex == 0 ) return false;
\r
520 // see if reference has alignments
\r
521 if ( !NewIndex->HasAlignments(refID) ) return false;
\r
522 // make sure position is valid
\r
523 if ( position > References.at(refID).RefLength ) return false;
\r
525 // determine possible offsets
\r
526 vector<int64_t> offsets;
\r
527 if ( !NewIndex->GetOffsets(Region, IsRightBoundSpecified, offsets) ) {
\r
528 printf("ERROR: Could not jump: unable to calculate offset for specified region.\n");
\r
532 // iterate through offsets
\r
533 BamAlignment bAlignment;
\r
534 bool result = true;
\r
535 for ( vector<int64_t>::const_iterator o = offsets.begin(); o != offsets.end(); ++o) {
\r
537 // attempt seek & load first available alignment
\r
538 result &= mBGZF.Seek(*o);
\r
539 LoadNextAlignment(bAlignment);
\r
541 // if this alignment corresponds to desired position
\r
542 // return success of seeking back to 'current offset'
\r
543 if ( (bAlignment.RefID == refID && bAlignment.Position + bAlignment.Length > position) || (bAlignment.RefID > refID) )
\r
544 return mBGZF.Seek(*o);
\r
550 // load BAM header data
\r
551 void BamReader::BamReaderPrivate::LoadHeaderData(void) {
\r
553 // check to see if proper BAM header
\r
555 if (mBGZF.Read(buffer, 4) != 4) {
\r
556 printf("Could not read header type\n");
\r
560 if (strncmp(buffer, "BAM\001", 4)) {
\r
561 printf("wrong header type!\n");
\r
565 // get BAM header text length
\r
566 mBGZF.Read(buffer, 4);
\r
567 unsigned int headerTextLength = BgzfData::UnpackUnsignedInt(buffer);
\r
568 if ( IsBigEndian ) { SwapEndian_32(headerTextLength); }
\r
570 // get BAM header text
\r
571 char* headerText = (char*)calloc(headerTextLength + 1, 1);
\r
572 mBGZF.Read(headerText, headerTextLength);
\r
573 HeaderText = (string)((const char*)headerText);
\r
575 // clean up calloc-ed temp variable
\r
579 // load existing index data from BAM index file (".bai"), return success/fail
\r
580 bool BamReader::BamReaderPrivate::LoadIndex(void) {
\r
582 // clear out any existing index data
\r
585 // skip if index file empty
\r
586 if ( IndexFilename.empty() )
\r
589 // check supplied filename for index type
\r
590 size_t defaultExtensionFound = IndexFilename.find(".bai");
\r
591 size_t customExtensionFound = IndexFilename.find(".bti");
\r
593 // if SAM/BAM default (".bai")
\r
594 if ( defaultExtensionFound != string::npos )
\r
595 NewIndex = new BamDefaultIndex(&mBGZF, Parent, IsBigEndian);
\r
597 // if BamTools custom index (".bti")
\r
598 else if ( customExtensionFound != string::npos )
\r
599 NewIndex = new BamToolsIndex(&mBGZF, Parent, IsBigEndian);
\r
603 printf("ERROR: Unknown index file extension.\n");
\r
607 // return success of loading index data
\r
608 return NewIndex->Load(IndexFilename);
\r
611 // populates BamAlignment with alignment data under file pointer, returns success/fail
\r
612 bool BamReader::BamReaderPrivate::LoadNextAlignment(BamAlignment& bAlignment) {
\r
614 // read in the 'block length' value, make sure it's not zero
\r
616 mBGZF.Read(buffer, 4);
\r
617 bAlignment.SupportData.BlockLength = BgzfData::UnpackUnsignedInt(buffer);
\r
618 if ( IsBigEndian ) { SwapEndian_32(bAlignment.SupportData.BlockLength); }
\r
619 if ( bAlignment.SupportData.BlockLength == 0 ) { return false; }
\r
621 // read in core alignment data, make sure the right size of data was read
\r
622 char x[BAM_CORE_SIZE];
\r
623 if ( mBGZF.Read(x, BAM_CORE_SIZE) != BAM_CORE_SIZE ) { return false; }
\r
625 if ( IsBigEndian ) {
\r
626 for ( int i = 0; i < BAM_CORE_SIZE; i+=sizeof(uint32_t) ) {
\r
627 SwapEndian_32p(&x[i]);
\r
631 // set BamAlignment 'core' and 'support' data
\r
632 bAlignment.RefID = BgzfData::UnpackSignedInt(&x[0]);
\r
633 bAlignment.Position = BgzfData::UnpackSignedInt(&x[4]);
\r
635 unsigned int tempValue = BgzfData::UnpackUnsignedInt(&x[8]);
\r
636 bAlignment.Bin = tempValue >> 16;
\r
637 bAlignment.MapQuality = tempValue >> 8 & 0xff;
\r
638 bAlignment.SupportData.QueryNameLength = tempValue & 0xff;
\r
640 tempValue = BgzfData::UnpackUnsignedInt(&x[12]);
\r
641 bAlignment.AlignmentFlag = tempValue >> 16;
\r
642 bAlignment.SupportData.NumCigarOperations = tempValue & 0xffff;
\r
644 bAlignment.SupportData.QuerySequenceLength = BgzfData::UnpackUnsignedInt(&x[16]);
\r
645 bAlignment.MateRefID = BgzfData::UnpackSignedInt(&x[20]);
\r
646 bAlignment.MatePosition = BgzfData::UnpackSignedInt(&x[24]);
\r
647 bAlignment.InsertSize = BgzfData::UnpackSignedInt(&x[28]);
\r
649 // set BamAlignment length
\r
650 bAlignment.Length = bAlignment.SupportData.QuerySequenceLength;
\r
652 // read in character data - make sure proper data size was read
\r
653 bool readCharDataOK = false;
\r
654 const unsigned int dataLength = bAlignment.SupportData.BlockLength - BAM_CORE_SIZE;
\r
655 char* allCharData = (char*)calloc(sizeof(char), dataLength);
\r
657 if ( mBGZF.Read(allCharData, dataLength) == (signed int)dataLength) {
\r
659 // store 'allCharData' in supportData structure
\r
660 bAlignment.SupportData.AllCharData.assign((const char*)allCharData, dataLength);
\r
662 // set success flag
\r
663 readCharDataOK = true;
\r
667 return readCharDataOK;
\r
670 // loads reference data from BAM file
\r
671 void BamReader::BamReaderPrivate::LoadReferenceData(void) {
\r
673 // get number of reference sequences
\r
675 mBGZF.Read(buffer, 4);
\r
676 unsigned int numberRefSeqs = BgzfData::UnpackUnsignedInt(buffer);
\r
677 if ( IsBigEndian ) { SwapEndian_32(numberRefSeqs); }
\r
678 if (numberRefSeqs == 0) { return; }
\r
679 References.reserve((int)numberRefSeqs);
\r
681 // iterate over all references in header
\r
682 for (unsigned int i = 0; i != numberRefSeqs; ++i) {
\r
684 // get length of reference name
\r
685 mBGZF.Read(buffer, 4);
\r
686 unsigned int refNameLength = BgzfData::UnpackUnsignedInt(buffer);
\r
687 if ( IsBigEndian ) { SwapEndian_32(refNameLength); }
\r
688 char* refName = (char*)calloc(refNameLength, 1);
\r
690 // get reference name and reference sequence length
\r
691 mBGZF.Read(refName, refNameLength);
\r
692 mBGZF.Read(buffer, 4);
\r
693 int refLength = BgzfData::UnpackSignedInt(buffer);
\r
694 if ( IsBigEndian ) { SwapEndian_32(refLength); }
\r
696 // store data for reference
\r
697 RefData aReference;
\r
698 aReference.RefName = (string)((const char*)refName);
\r
699 aReference.RefLength = refLength;
\r
700 References.push_back(aReference);
\r
702 // clean up calloc-ed temp variable
\r
707 // opens BAM file (and index)
\r
708 bool BamReader::BamReaderPrivate::Open(const string& filename, const string& indexFilename) {
\r
710 Filename = filename;
\r
711 IndexFilename = indexFilename;
\r
713 // open the BGZF file for reading, return false on failure
\r
714 if ( !mBGZF.Open(filename, "rb") )
\r
717 // retrieve header text & reference data
\r
719 LoadReferenceData();
\r
721 // store file offset of first alignment
\r
722 AlignmentsBeginOffset = mBGZF.Tell();
\r
724 // open index file & load index data (if exists)
\r
725 if ( !IndexFilename.empty() )
\r
732 // returns BAM file pointer to beginning of alignment data
\r
733 bool BamReader::BamReaderPrivate::Rewind(void) {
\r
735 // rewind to first alignment
\r
736 if ( !mBGZF.Seek(AlignmentsBeginOffset) ) return false;
\r
738 // retrieve first alignment data
\r
740 if ( !LoadNextAlignment(al) ) return false;
\r
742 // reset default region info using first alignment in file
\r
743 Region.LeftRefID = al.RefID;
\r
744 Region.LeftPosition = al.Position;
\r
745 Region.RightRefID = -1;
\r
746 Region.RightPosition = -1;
\r
747 IsLeftBoundSpecified = false;
\r
748 IsRightBoundSpecified = false;
\r
750 // rewind back to before first alignment
\r
751 // return success/fail of seek
\r
752 return mBGZF.Seek(AlignmentsBeginOffset);
\r
755 // sets a region of interest (with left & right bound reference/position)
\r
756 // attempts a Jump() to left bound as well
\r
757 // returns success/failure of Jump()
\r
758 bool BamReader::BamReaderPrivate::SetRegion(const BamRegion& region) {
\r
760 // save region of interest
\r
764 if ( region.LeftRefID >= 0 && region.LeftPosition >= 0 )
\r
765 IsLeftBoundSpecified = true;
\r
766 if ( region.RightRefID >= 0 && region.RightPosition >= 0 )
\r
767 IsRightBoundSpecified = true;
\r
769 // attempt jump to beginning of region, return success/fail of Jump()
\r
770 return Jump( Region.LeftRefID, Region.LeftPosition );
\r