1 // ***************************************************************************
2 // BamStandardIndex.cpp (c) 2010 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 index operations for the standardized BAM index format (".bai")
9 // ***************************************************************************
11 #include <api/BamAlignment.h>
12 #include <api/BamReader.h>
13 #include <api/BamStandardIndex.h>
15 using namespace BamTools;
16 using namespace BamTools::Internal;
25 BamStandardIndex::BamStandardIndex(BgzfData* bgzf, BamReader* reader)
26 : BamIndex(bgzf, reader)
27 , m_dataBeginOffset(0)
28 , m_hasFullDataCache(false)
30 m_isBigEndian = BamTools::SystemIsBigEndian();
33 BamStandardIndex::~BamStandardIndex(void) {
37 // calculate bins that overlap region
38 int BamStandardIndex::BinsFromRegion(const BamRegion& region,
39 const bool isRightBoundSpecified,
40 uint16_t bins[MAX_BIN])
42 // get region boundaries
43 uint32_t begin = (unsigned int)region.LeftPosition;
46 // if right bound specified AND left&right bounds are on same reference
47 // OK to use right bound position
48 if ( isRightBoundSpecified && ( region.LeftRefID == region.RightRefID ) )
49 end = (unsigned int)region.RightPosition;
51 // otherwise, use end of left bound reference as cutoff
53 end = (unsigned int)m_references.at(region.LeftRefID).RefLength - 1;
55 // initialize list, bin '0' always a valid bin
59 // get rest of bins that contain this region
61 for (k = 1 + (begin>>26); k <= 1 + (end>>26); ++k) { bins[i++] = k; }
62 for (k = 9 + (begin>>23); k <= 9 + (end>>23); ++k) { bins[i++] = k; }
63 for (k = 73 + (begin>>20); k <= 73 + (end>>20); ++k) { bins[i++] = k; }
64 for (k = 585 + (begin>>17); k <= 585 + (end>>17); ++k) { bins[i++] = k; }
65 for (k = 4681 + (begin>>14); k <= 4681 + (end>>14); ++k) { bins[i++] = k; }
67 // return number of bins stored
71 // creates index data (in-memory) from current reader data
72 bool BamStandardIndex::Build(void) {
74 // be sure reader & BGZF file are valid & open for reading
75 if ( m_reader == 0 || m_BGZF == 0 || !m_BGZF->IsOpen )
78 // move file pointer to beginning of alignments
81 // get reference count, reserve index space
82 const int numReferences = (int)m_references.size();
84 m_hasFullDataCache = false;
85 SetReferenceCount(numReferences);
87 // sets default constant for bin, ID, offset, coordinate variables
88 const uint32_t defaultValue = 0xffffffffu;
91 uint32_t saveBin(defaultValue);
92 uint32_t lastBin(defaultValue);
95 int32_t saveRefID(defaultValue);
96 int32_t lastRefID(defaultValue);
99 uint64_t saveOffset = m_BGZF->Tell();
100 uint64_t lastOffset = saveOffset;
103 int32_t lastCoordinate = defaultValue;
105 BamAlignment bAlignment;
106 while ( m_reader->GetNextAlignmentCore(bAlignment) ) {
108 // change of chromosome, save ID, reset bin
109 if ( lastRefID != bAlignment.RefID ) {
110 lastRefID = bAlignment.RefID;
111 lastBin = defaultValue;
114 // if lastCoordinate greater than BAM position - file not sorted properly
115 else if ( lastCoordinate > bAlignment.Position ) {
116 fprintf(stderr, "BAM file not properly sorted:\n");
117 fprintf(stderr, "Alignment %s : %d > %d on reference (id = %d)", bAlignment.Name.c_str(),
118 lastCoordinate, bAlignment.Position, bAlignment.RefID);
122 // if valid reference && BAM bin spans some minimum cutoff (smaller bin ids span larger regions)
123 if ( (bAlignment.RefID >= 0) && (bAlignment.Bin < 4681) ) {
125 // save linear offset entry (matched to BAM entry refID)
126 BamStandardIndexData::iterator indexIter = m_indexData.find(bAlignment.RefID);
127 if ( indexIter == m_indexData.end() ) return false; // error
128 ReferenceIndex& refIndex = (*indexIter).second;
129 LinearOffsetVector& offsets = refIndex.Offsets;
130 SaveLinearOffset(offsets, bAlignment, lastOffset);
133 // if current BamAlignment bin != lastBin, "then possibly write the binning index"
134 if ( bAlignment.Bin != lastBin ) {
136 // if not first time through
137 if ( saveBin != defaultValue ) {
139 // save Bam bin entry
140 BamStandardIndexData::iterator indexIter = m_indexData.find(saveRefID);
141 if ( indexIter == m_indexData.end() ) return false; // error
142 ReferenceIndex& refIndex = (*indexIter).second;
143 BamBinMap& binMap = refIndex.Bins;
144 SaveBinEntry(binMap, saveBin, saveOffset, lastOffset);
148 saveOffset = lastOffset;
151 saveBin = bAlignment.Bin;
152 lastBin = bAlignment.Bin;
155 saveRefID = bAlignment.RefID;
157 // if invalid RefID, break out
158 if ( saveRefID < 0 ) break;
161 // make sure that current file pointer is beyond lastOffset
162 if ( m_BGZF->Tell() <= (int64_t)lastOffset ) {
163 fprintf(stderr, "Error in BGZF offsets.\n");
168 lastOffset = m_BGZF->Tell();
170 // update lastCoordinate
171 lastCoordinate = bAlignment.Position;
174 // save any leftover BAM data (as long as refID is valid)
175 if ( saveRefID >= 0 ) {
176 // save Bam bin entry
177 BamStandardIndexData::iterator indexIter = m_indexData.find(saveRefID);
178 if ( indexIter == m_indexData.end() ) return false; // error
179 ReferenceIndex& refIndex = (*indexIter).second;
180 BamBinMap& binMap = refIndex.Bins;
181 SaveBinEntry(binMap, saveBin, saveOffset, lastOffset);
184 // simplify index by merging chunks
187 // iterate through references in index
188 // sort offsets in linear offset vector
189 BamStandardIndexData::iterator indexIter = m_indexData.begin();
190 BamStandardIndexData::iterator indexEnd = m_indexData.end();
191 for ( int i = 0; indexIter != indexEnd; ++indexIter, ++i ) {
193 // get reference index data
194 ReferenceIndex& refIndex = (*indexIter).second;
195 LinearOffsetVector& offsets = refIndex.Offsets;
197 // sort linear offsets
198 sort(offsets.begin(), offsets.end());
201 // rewind file pointer to beginning of alignments, return success/fail
202 return m_reader->Rewind();
205 // check index file magic number, return true if OK
206 bool BamStandardIndex::CheckMagicNumber(void) {
208 // read in magic number
210 size_t elementsRead = fread(magic, sizeof(char), 4, m_indexStream);
212 // compare to expected value
213 if ( strncmp(magic, "BAI\1", 4) != 0 ) {
214 fprintf(stderr, "Problem with index file - invalid format.\n");
215 fclose(m_indexStream);
219 // return success/failure of load
220 return (elementsRead == 4);
223 // clear all current index offset data in memory
224 void BamStandardIndex::ClearAllData(void) {
225 BamStandardIndexData::const_iterator indexIter = m_indexData.begin();
226 BamStandardIndexData::const_iterator indexEnd = m_indexData.end();
227 for ( ; indexIter != indexEnd; ++indexIter ) {
228 const int& refId = (*indexIter).first;
229 ClearReferenceOffsets(refId);
233 // clear all index offset data for desired reference
234 void BamStandardIndex::ClearReferenceOffsets(const int& refId) {
236 // look up refId, skip if not found
237 BamStandardIndexData::iterator indexIter = m_indexData.find(refId);
238 if ( indexIter == m_indexData.end() ) return ;
240 // clear reference data
241 ReferenceIndex& refEntry = (*indexIter).second;
242 refEntry.Bins.clear();
243 refEntry.Offsets.clear();
246 m_hasFullDataCache = false;
249 // return file position after header metadata
250 const off_t BamStandardIndex::DataBeginOffset(void) const {
251 return m_dataBeginOffset;
254 // calculates offset(s) for a given region
255 bool BamStandardIndex::GetOffsets(const BamRegion& region,
256 const bool isRightBoundSpecified,
257 vector<int64_t>& offsets,
258 bool* hasAlignmentsInRegion)
260 // return false if leftBound refID is not found in index data
261 if ( m_indexData.find(region.LeftRefID) == m_indexData.end() )
264 // load index data for region if not already cached
265 if ( !IsDataLoaded(region.LeftRefID) ) {
266 bool loadedOk = true;
267 loadedOk &= SkipToReference(region.LeftRefID);
268 loadedOk &= LoadReference(region.LeftRefID);
269 if ( !loadedOk ) return false;
272 // calculate which bins overlap this region
273 uint16_t* bins = (uint16_t*)calloc(MAX_BIN, 2);
274 int numBins = BinsFromRegion(region, isRightBoundSpecified, bins);
276 // get bins for this reference
277 BamStandardIndexData::const_iterator indexIter = m_indexData.find(region.LeftRefID);
278 if ( indexIter == m_indexData.end() ) return false; // error
279 const ReferenceIndex& refIndex = (*indexIter).second;
280 const BamBinMap& binMap = refIndex.Bins;
282 // get minimum offset to consider
283 const LinearOffsetVector& linearOffsets = refIndex.Offsets;
284 const uint64_t minOffset = ( (unsigned int)(region.LeftPosition>>BAM_LIDX_SHIFT) >= linearOffsets.size() )
285 ? 0 : linearOffsets.at(region.LeftPosition>>BAM_LIDX_SHIFT);
287 // store all alignment 'chunk' starts (file offsets) for bins in this region
288 for ( int i = 0; i < numBins; ++i ) {
290 const uint16_t binKey = bins[i];
291 map<uint32_t, ChunkVector>::const_iterator binIter = binMap.find(binKey);
292 if ( (binIter != binMap.end()) && ((*binIter).first == binKey) ) {
294 // iterate over chunks
295 const ChunkVector& chunks = (*binIter).second;
296 std::vector<Chunk>::const_iterator chunksIter = chunks.begin();
297 std::vector<Chunk>::const_iterator chunksEnd = chunks.end();
298 for ( ; chunksIter != chunksEnd; ++chunksIter) {
300 // if valid chunk found, store its file offset
301 const Chunk& chunk = (*chunksIter);
302 if ( chunk.Stop > minOffset )
303 offsets.push_back( chunk.Start );
311 // sort the offsets before returning
312 sort(offsets.begin(), offsets.end());
314 // set flag & return success
315 *hasAlignmentsInRegion = (offsets.size() != 0 );
317 // if cache mode set to none, dump the data we just loaded
318 if (m_cacheMode == BamIndex::NoIndexCaching )
319 ClearReferenceOffsets(region.LeftRefID);
325 // returns whether reference has alignments or no
326 bool BamStandardIndex::HasAlignments(const int& refId) const {
327 BamStandardIndexData::const_iterator indexIter = m_indexData.find(refId);
328 if ( indexIter == m_indexData.end() ) return false; // error
329 const ReferenceIndex& refEntry = (*indexIter).second;
330 return refEntry.HasAlignments;
333 // return true if all index data is cached
334 bool BamStandardIndex::HasFullDataCache(void) const {
335 return m_hasFullDataCache;
338 // returns true if index cache has data for desired reference
339 bool BamStandardIndex::IsDataLoaded(const int& refId) const {
341 // look up refId, return false if not found
342 BamStandardIndexData::const_iterator indexIter = m_indexData.find(refId);
343 if ( indexIter == m_indexData.end() ) return false;
345 // see if reference has alignments
346 // if not, it's not a problem to have no offset data
347 const ReferenceIndex& refEntry = (*indexIter).second;
348 if ( !refEntry.HasAlignments ) return true;
350 // return whether bin map contains data
351 return ( !refEntry.Bins.empty() );
354 // attempts to use index to jump to region; returns success/fail
355 bool BamStandardIndex::Jump(const BamRegion& region, bool* hasAlignmentsInRegion) {
357 // be sure reader & BGZF file are valid & open for reading
358 if ( m_reader == 0 || m_BGZF == 0 || !m_BGZF->IsOpen )
361 // make sure left-bound position is valid
362 if ( region.LeftPosition > m_references.at(region.LeftRefID).RefLength )
365 // calculate offsets for this region
366 // if failed, print message, set flag, and return failure
367 vector<int64_t> offsets;
368 if ( !GetOffsets(region, region.isRightBoundSpecified(), offsets, hasAlignmentsInRegion) ) {
369 fprintf(stderr, "ERROR: Could not jump: unable to calculate offset(s) for specified region.\n");
370 *hasAlignmentsInRegion = false;
374 // iterate through offsets
375 BamAlignment bAlignment;
377 for ( vector<int64_t>::const_iterator o = offsets.begin(); o != offsets.end(); ++o) {
379 // attempt seek & load first available alignment
380 // set flag to true if data exists
381 result &= m_BGZF->Seek(*o);
382 *hasAlignmentsInRegion = m_reader->GetNextAlignmentCore(bAlignment);
384 // if this alignment corresponds to desired position
385 // return success of seeking back to the offset before the 'current offset' (to cover overlaps)
386 if ( ((bAlignment.RefID == region.LeftRefID) &&
387 ((bAlignment.Position + bAlignment.Length) > region.LeftPosition)) ||
388 (bAlignment.RefID > region.LeftRefID) )
390 if ( o != offsets.begin() ) --o;
391 return m_BGZF->Seek(*o);
395 // if error in jumping, print message & set flag
397 fprintf(stderr, "ERROR: Could not jump: unable to determine correct offset for specified region.\n");
398 *hasAlignmentsInRegion = false;
401 // return success/failure
405 // clears index data from all references except the first
406 void BamStandardIndex::KeepOnlyFirstReferenceOffsets(void) {
407 BamStandardIndexData::const_iterator indexBegin = m_indexData.begin();
408 KeepOnlyReferenceOffsets((*indexBegin).first);
411 // clears index data from all references except the one specified
412 void BamStandardIndex::KeepOnlyReferenceOffsets(const int& refId) {
413 BamStandardIndexData::iterator mapIter = m_indexData.begin();
414 BamStandardIndexData::iterator mapEnd = m_indexData.end();
415 for ( ; mapIter != mapEnd; ++mapIter ) {
416 const int entryRefId = (*mapIter).first;
417 if ( entryRefId != refId )
418 ClearReferenceOffsets(entryRefId);
422 bool BamStandardIndex::LoadAllReferences(bool saveData) {
424 // skip if data already loaded
425 if ( m_hasFullDataCache ) return true;
427 // get number of reference sequences
428 uint32_t numReferences;
429 if ( !LoadReferenceCount((int&)numReferences) )
432 // iterate over reference entries
433 bool loadedOk = true;
434 for ( int i = 0; i < (int)numReferences; ++i )
435 loadedOk &= LoadReference(i, saveData);
438 if ( loadedOk && saveData )
439 m_hasFullDataCache = true;
441 // return success/failure of loading references
445 // load header data from index file, return true if loaded OK
446 bool BamStandardIndex::LoadHeader(void) {
448 bool loadedOk = CheckMagicNumber();
450 // store offset of beginning of data
451 m_dataBeginOffset = ftell64(m_indexStream);
453 // return success/failure of load
457 // load a single index bin entry from file, return true if loaded OK
458 // @saveData - save data in memory if true, just read & discard if false
459 bool BamStandardIndex::LoadBin(ReferenceIndex& refEntry, bool saveData) {
461 size_t elementsRead = 0;
465 elementsRead += fread(&binId, sizeof(binId), 1, m_indexStream);
466 if ( m_isBigEndian ) SwapEndian_32(binId);
468 // load alignment chunks for this bin
470 bool chunksOk = LoadChunks(chunks, saveData);
473 if ( chunksOk && saveData )
474 refEntry.Bins.insert(pair<uint32_t, ChunkVector>(binId, chunks));
476 // return success/failure of load
477 return ( (elementsRead == 1) && chunksOk );
480 bool BamStandardIndex::LoadBins(ReferenceIndex& refEntry, bool saveData) {
482 size_t elementsRead = 0;
484 // get number of bins
486 elementsRead += fread(&numBins, sizeof(numBins), 1, m_indexStream);
487 if ( m_isBigEndian ) SwapEndian_32(numBins);
490 refEntry.HasAlignments = ( numBins != 0 );
494 for ( int i = 0; i < numBins; ++i )
495 binsOk &= LoadBin(refEntry, saveData);
497 // return success/failure of load
498 return ( (elementsRead == 1) && binsOk );
501 // load a single index bin entry from file, return true if loaded OK
502 // @saveData - save data in memory if true, just read & discard if false
503 bool BamStandardIndex::LoadChunk(ChunkVector& chunks, bool saveData) {
505 size_t elementsRead = 0;
507 // read in chunk data
510 elementsRead += fread(&start, sizeof(start), 1, m_indexStream);
511 elementsRead += fread(&stop, sizeof(stop), 1, m_indexStream);
513 // swap endian-ness if necessary
514 if ( m_isBigEndian ) {
515 SwapEndian_64(start);
519 // save data if requested
520 if ( saveData ) chunks.push_back( Chunk(start, stop) );
522 // return success/failure of load
523 return ( elementsRead == 2 );
526 bool BamStandardIndex::LoadChunks(ChunkVector& chunks, bool saveData) {
528 size_t elementsRead = 0;
530 // read in number of chunks
532 elementsRead += fread(&numChunks, sizeof(numChunks), 1, m_indexStream);
533 if ( m_isBigEndian ) SwapEndian_32(numChunks);
535 // initialize space for chunks if we're storing this data
536 if ( saveData ) chunks.reserve(numChunks);
538 // iterate over chunks
539 bool chunksOk = true;
540 for ( int i = 0; i < (int)numChunks; ++i )
541 chunksOk &= LoadChunk(chunks, saveData);
544 sort( chunks.begin(), chunks.end(), ChunkLessThan );
546 // return success/failure of load
547 return ( (elementsRead == 1) && chunksOk );
550 // load a single index linear offset entry from file, return true if loaded OK
551 // @saveData - save data in memory if true, just read & discard if false
552 bool BamStandardIndex::LoadLinearOffsets(ReferenceIndex& refEntry, bool saveData) {
554 size_t elementsRead = 0;
556 // read in number of linear offsets
557 int32_t numLinearOffsets;
558 elementsRead += fread(&numLinearOffsets, sizeof(numLinearOffsets), 1, m_indexStream);
559 if ( m_isBigEndian ) SwapEndian_32(numLinearOffsets);
561 // set up destination vector (if we're saving the data)
562 LinearOffsetVector linearOffsets;
563 if ( saveData ) linearOffsets.reserve(numLinearOffsets);
565 // iterate over linear offsets
566 uint64_t linearOffset;
567 for ( int i = 0; i < numLinearOffsets; ++i ) {
568 elementsRead += fread(&linearOffset, sizeof(linearOffset), 1, m_indexStream);
569 if ( m_isBigEndian ) SwapEndian_64(linearOffset);
570 if ( saveData ) linearOffsets.push_back(linearOffset);
573 // sort linear offsets
574 sort ( linearOffsets.begin(), linearOffsets.end() );
576 // save in reference index entry if desired
577 if ( saveData ) refEntry.Offsets = linearOffsets;
579 // return success/failure of load
580 return ( elementsRead == (size_t)(numLinearOffsets + 1) );
583 bool BamStandardIndex::LoadFirstReference(bool saveData) {
584 BamStandardIndexData::const_iterator indexBegin = m_indexData.begin();
585 return LoadReference((*indexBegin).first, saveData);
588 // load a single reference from file, return true if loaded OK
589 // @saveData - save data in memory if true, just read & discard if false
590 bool BamStandardIndex::LoadReference(const int& refId, bool saveData) {
593 BamStandardIndexData::iterator indexIter = m_indexData.find(refId);
595 // if reference not previously loaded, create new entry
596 if ( indexIter == m_indexData.end() ) {
597 ReferenceIndex newEntry;
598 newEntry.HasAlignments = false;
599 m_indexData.insert( pair<int32_t, ReferenceIndex>(refId, newEntry) );
602 // load reference data
603 indexIter = m_indexData.find(refId);
604 ReferenceIndex& entry = (*indexIter).second;
605 bool loadedOk = true;
606 loadedOk &= LoadBins(entry, saveData);
607 loadedOk &= LoadLinearOffsets(entry, saveData);
611 // loads number of references, return true if loaded OK
612 bool BamStandardIndex::LoadReferenceCount(int& numReferences) {
614 size_t elementsRead = 0;
616 // read reference count
617 elementsRead += fread(&numReferences, sizeof(numReferences), 1, m_indexStream);
618 if ( m_isBigEndian ) SwapEndian_32(numReferences);
620 // return success/failure of load
621 return ( elementsRead == 1 );
624 // merges 'alignment chunks' in BAM bin (used for index building)
625 void BamStandardIndex::MergeChunks(void) {
627 // iterate over reference enties
628 BamStandardIndexData::iterator indexIter = m_indexData.begin();
629 BamStandardIndexData::iterator indexEnd = m_indexData.end();
630 for ( ; indexIter != indexEnd; ++indexIter ) {
632 // get BAM bin map for this reference
633 ReferenceIndex& refIndex = (*indexIter).second;
634 BamBinMap& bamBinMap = refIndex.Bins;
636 // iterate over BAM bins
637 BamBinMap::iterator binIter = bamBinMap.begin();
638 BamBinMap::iterator binEnd = bamBinMap.end();
639 for ( ; binIter != binEnd; ++binIter ) {
641 // get chunk vector for this bin
642 ChunkVector& binChunks = (*binIter).second;
643 if ( binChunks.size() == 0 ) continue;
645 ChunkVector mergedChunks;
646 mergedChunks.push_back( binChunks[0] );
648 // iterate over chunks
650 ChunkVector::iterator chunkIter = binChunks.begin();
651 ChunkVector::iterator chunkEnd = binChunks.end();
652 for ( ++chunkIter; chunkIter != chunkEnd; ++chunkIter) {
654 // get 'currentChunk' based on numeric index
655 Chunk& currentChunk = mergedChunks[i];
657 // get iteratorChunk based on vector iterator
658 Chunk& iteratorChunk = (*chunkIter);
660 // if chunk ends where (iterator) chunk starts, then merge
661 if ( currentChunk.Stop>>16 == iteratorChunk.Start>>16 )
662 currentChunk.Stop = iteratorChunk.Stop;
666 // set currentChunk + 1 to iteratorChunk
667 mergedChunks.push_back(iteratorChunk);
672 // saved merged chunk vector
673 (*binIter).second = mergedChunks;
678 // saves BAM bin entry for index
679 void BamStandardIndex::SaveBinEntry(BamBinMap& binMap,
680 const uint32_t& saveBin,
681 const uint64_t& saveOffset,
682 const uint64_t& lastOffset)
685 BamBinMap::iterator binIter = binMap.find(saveBin);
688 Chunk newChunk(saveOffset, lastOffset);
690 // if entry doesn't exist
691 if ( binIter == binMap.end() ) {
692 ChunkVector newChunks;
693 newChunks.push_back(newChunk);
694 binMap.insert( pair<uint32_t, ChunkVector>(saveBin, newChunks));
699 ChunkVector& binChunks = (*binIter).second;
700 binChunks.push_back( newChunk );
704 // saves linear offset entry for index
705 void BamStandardIndex::SaveLinearOffset(LinearOffsetVector& offsets,
706 const BamAlignment& bAlignment,
707 const uint64_t& lastOffset)
709 // get converted offsets
710 int beginOffset = bAlignment.Position >> BAM_LIDX_SHIFT;
711 int endOffset = (bAlignment.GetEndPosition() - 1) >> BAM_LIDX_SHIFT;
713 // resize vector if necessary
714 int oldSize = offsets.size();
715 int newSize = endOffset + 1;
716 if ( oldSize < newSize )
717 offsets.resize(newSize, 0);
720 for( int i = beginOffset + 1; i <= endOffset; ++i ) {
721 if ( offsets[i] == 0 )
722 offsets[i] = lastOffset;
726 // initializes index data structure to hold @count references
727 void BamStandardIndex::SetReferenceCount(const int& count) {
728 for ( int i = 0; i < count; ++i )
729 m_indexData[i].HasAlignments = false;
732 bool BamStandardIndex::SkipToFirstReference(void) {
733 BamStandardIndexData::const_iterator indexBegin = m_indexData.begin();
734 return SkipToReference( (*indexBegin).first );
737 // position file pointer to desired reference begin, return true if skipped OK
738 bool BamStandardIndex::SkipToReference(const int& refId) {
741 if ( !Rewind() ) return false;
743 // read in number of references
744 uint32_t numReferences;
745 size_t elementsRead = fread(&numReferences, sizeof(numReferences), 1, m_indexStream);
746 if ( elementsRead != 1 ) return false;
747 if ( m_isBigEndian ) SwapEndian_32(numReferences);
749 // iterate over reference entries
750 bool skippedOk = true;
751 int currentRefId = 0;
752 while (currentRefId != refId) {
753 skippedOk &= LoadReference(currentRefId, false);
761 // write header to new index file
762 bool BamStandardIndex::WriteHeader(void) {
764 size_t elementsWritten = 0;
766 // write magic number
767 elementsWritten += fwrite("BAI\1", sizeof(char), 4, m_indexStream);
769 // store offset of beginning of data
770 m_dataBeginOffset = ftell64(m_indexStream);
772 // return success/failure of write
773 return (elementsWritten == 4);
776 // write index data for all references to new index file
777 bool BamStandardIndex::WriteAllReferences(void) {
779 size_t elementsWritten = 0;
781 // write number of reference sequences
782 int32_t numReferenceSeqs = m_indexData.size();
783 if ( m_isBigEndian ) SwapEndian_32(numReferenceSeqs);
784 elementsWritten += fwrite(&numReferenceSeqs, sizeof(numReferenceSeqs), 1, m_indexStream);
786 // iterate over reference sequences
788 BamStandardIndexData::const_iterator indexIter = m_indexData.begin();
789 BamStandardIndexData::const_iterator indexEnd = m_indexData.end();
790 for ( ; indexIter != indexEnd; ++ indexIter )
791 refsOk &= WriteReference( (*indexIter).second );
793 // return success/failure of write
794 return ( (elementsWritten == 1) && refsOk );
797 // write index data for bin to new index file
798 bool BamStandardIndex::WriteBin(const uint32_t& binId, const ChunkVector& chunks) {
800 size_t elementsWritten = 0;
803 uint32_t binKey = binId;
804 if ( m_isBigEndian ) SwapEndian_32(binKey);
805 elementsWritten += fwrite(&binKey, sizeof(binKey), 1, m_indexStream);
808 bool chunksOk = WriteChunks(chunks);
810 // return success/failure of write
811 return ( (elementsWritten == 1) && chunksOk );
814 // write index data for bins to new index file
815 bool BamStandardIndex::WriteBins(const BamBinMap& bins) {
817 size_t elementsWritten = 0;
819 // write number of bins
820 int32_t binCount = bins.size();
821 if ( m_isBigEndian ) SwapEndian_32(binCount);
822 elementsWritten += fwrite(&binCount, sizeof(binCount), 1, m_indexStream);
826 BamBinMap::const_iterator binIter = bins.begin();
827 BamBinMap::const_iterator binEnd = bins.end();
828 for ( ; binIter != binEnd; ++binIter )
829 binsOk &= WriteBin( (*binIter).first, (*binIter).second );
831 // return success/failure of write
832 return ( (elementsWritten == 1) && binsOk );
835 // write index data for chunk entry to new index file
836 bool BamStandardIndex::WriteChunk(const Chunk& chunk) {
838 size_t elementsWritten = 0;
840 // localize alignment chunk offsets
841 uint64_t start = chunk.Start;
842 uint64_t stop = chunk.Stop;
844 // swap endian-ness if necessary
845 if ( m_isBigEndian ) {
846 SwapEndian_64(start);
850 // write to index file
851 elementsWritten += fwrite(&start, sizeof(start), 1, m_indexStream);
852 elementsWritten += fwrite(&stop, sizeof(stop), 1, m_indexStream);
854 // return success/failure of write
855 return ( elementsWritten == 2 );
858 // write index data for chunk entry to new index file
859 bool BamStandardIndex::WriteChunks(const ChunkVector& chunks) {
861 size_t elementsWritten = 0;
864 int32_t chunkCount = chunks.size();
865 if ( m_isBigEndian ) SwapEndian_32(chunkCount);
866 elementsWritten += fwrite(&chunkCount, sizeof(chunkCount), 1, m_indexStream);
868 // iterate over chunks
869 bool chunksOk = true;
870 ChunkVector::const_iterator chunkIter = chunks.begin();
871 ChunkVector::const_iterator chunkEnd = chunks.end();
872 for ( ; chunkIter != chunkEnd; ++chunkIter )
873 chunksOk &= WriteChunk( (*chunkIter) );
875 // return success/failure of write
876 return ( (elementsWritten == 1) && chunksOk );
879 // write index data for linear offsets entry to new index file
880 bool BamStandardIndex::WriteLinearOffsets(const LinearOffsetVector& offsets) {
882 size_t elementsWritten = 0;
884 // write number of linear offsets
885 int32_t offsetCount = offsets.size();
886 if ( m_isBigEndian ) SwapEndian_32(offsetCount);
887 elementsWritten += fwrite(&offsetCount, sizeof(offsetCount), 1, m_indexStream);
889 // iterate over linear offsets
890 LinearOffsetVector::const_iterator offsetIter = offsets.begin();
891 LinearOffsetVector::const_iterator offsetEnd = offsets.end();
892 for ( ; offsetIter != offsetEnd; ++offsetIter ) {
894 // write linear offset
895 uint64_t linearOffset = (*offsetIter);
896 if ( m_isBigEndian ) SwapEndian_64(linearOffset);
897 elementsWritten += fwrite(&linearOffset, sizeof(linearOffset), 1, m_indexStream);
900 // return success/failure of write
901 return ( elementsWritten == (size_t)(offsetCount + 1) );
904 // write index data for a single reference to new index file
905 bool BamStandardIndex::WriteReference(const ReferenceIndex& refEntry) {
907 refOk &= WriteBins(refEntry.Bins);
908 refOk &= WriteLinearOffsets(refEntry.Offsets);