1 // ***************************************************************************
2 // BamStandardIndex.cpp (c) 2010 Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 25 May 2012 (DB)
6 // ---------------------------------------------------------------------------
7 // Provides index operations for the standardized BAM index format (".bai")
8 // ***************************************************************************
10 #include "api/BamAlignment.h"
11 #include "api/internal/bam/BamReader_p.h"
12 #include "api/internal/index/BamStandardIndex_p.h"
13 #include "api/internal/io/BamDeviceFactory_p.h"
14 #include "api/internal/utils/BamException_p.h"
15 using namespace BamTools;
16 using namespace BamTools::Internal;
25 // -----------------------------------
26 // static BamStandardIndex constants
27 // -----------------------------------
29 const int BamStandardIndex::MAX_BIN = 37450; // =(8^6-1)/7+1
30 const int BamStandardIndex::BAM_LIDX_SHIFT = 14;
31 const string BamStandardIndex::BAI_EXTENSION = ".bai";
32 const char* const BamStandardIndex::BAI_MAGIC = "BAI\1";
33 const int BamStandardIndex::SIZEOF_ALIGNMENTCHUNK = sizeof(uint64_t)*2;
34 const int BamStandardIndex::SIZEOF_BINCORE = sizeof(uint32_t) + sizeof(int32_t);
35 const int BamStandardIndex::SIZEOF_LINEAROFFSET = sizeof(uint64_t);
37 // ----------------------------
38 // RaiiWrapper implementation
39 // ----------------------------
41 BamStandardIndex::RaiiWrapper::RaiiWrapper(void)
46 BamStandardIndex::RaiiWrapper::~RaiiWrapper(void) {
60 // ---------------------------------
61 // BamStandardIndex implementation
62 // ---------------------------------
65 BamStandardIndex::BamStandardIndex(Internal::BamReaderPrivate* reader)
69 m_isBigEndian = BamTools::SystemIsBigEndian();
73 BamStandardIndex::~BamStandardIndex(void) {
77 void BamStandardIndex::AdjustRegion(const BamRegion& region, uint32_t& begin, uint32_t& end) {
79 // retrieve references from reader
80 const RefVector& references = m_reader->GetReferenceData();
82 // LeftPosition cannot be greater than or equal to reference length
83 if ( region.LeftPosition >= references.at(region.LeftRefID).RefLength )
84 throw BamException("BamStandardIndex::AdjustRegion", "invalid region requested");
87 begin = (unsigned int)region.LeftPosition;
89 // if right bound specified AND left&right bounds are on same reference
90 // OK to use right bound position as region 'end'
91 if ( region.isRightBoundSpecified() && ( region.LeftRefID == region.RightRefID ) )
92 end = (unsigned int)region.RightPosition;
94 // otherwise, set region 'end' to last reference base
95 else end = (unsigned int)references.at(region.LeftRefID).RefLength;
99 void BamStandardIndex::CalculateCandidateBins(const uint32_t& begin,
101 set<uint16_t>& candidateBins)
103 // initialize list, bin '0' is always a valid bin
104 candidateBins.insert(0);
106 // get rest of bins that contain this region
108 for (k = 1 + (begin>>26); k <= 1 + (end>>26); ++k) { candidateBins.insert(k); }
109 for (k = 9 + (begin>>23); k <= 9 + (end>>23); ++k) { candidateBins.insert(k); }
110 for (k = 73 + (begin>>20); k <= 73 + (end>>20); ++k) { candidateBins.insert(k); }
111 for (k = 585 + (begin>>17); k <= 585 + (end>>17); ++k) { candidateBins.insert(k); }
112 for (k = 4681 + (begin>>14); k <= 4681 + (end>>14); ++k) { candidateBins.insert(k); }
115 void BamStandardIndex::CalculateCandidateOffsets(const BaiReferenceSummary& refSummary,
116 const uint64_t& minOffset,
117 set<uint16_t>& candidateBins,
118 vector<int64_t>& offsets)
121 Seek(refSummary.FirstBinFilePosition, SEEK_SET);
123 // iterate over reference bins
125 int32_t numAlignmentChunks;
126 set<uint16_t>::iterator candidateBinIter;
127 for ( int i = 0; i < refSummary.NumBins; ++i ) {
129 // read bin contents (if successful, alignment chunks are now in m_buffer)
130 ReadBinIntoBuffer(binId, numAlignmentChunks);
132 // see if bin is a 'candidate bin'
133 candidateBinIter = candidateBins.find(binId);
135 // if not, move on to next bin
136 if ( candidateBinIter == candidateBins.end() )
139 // otherwise, check bin's contents against for overlap
146 // iterate over alignment chunks
147 for ( int j = 0; j < numAlignmentChunks; ++j ) {
149 // read chunk start & stop from buffer
150 memcpy((char*)&chunkStart, m_resources.Buffer+offset, sizeof(uint64_t));
151 offset += sizeof(uint64_t);
152 memcpy((char*)&chunkStop, m_resources.Buffer+offset, sizeof(uint64_t));
153 offset += sizeof(uint64_t);
155 // swap endian-ness if necessary
156 if ( m_isBigEndian ) {
157 SwapEndian_64(chunkStart);
158 SwapEndian_64(chunkStop);
161 // store alignment chunk's start offset
162 // if its stop offset is larger than our 'minOffset'
163 if ( chunkStop >= minOffset )
164 offsets.push_back(chunkStart);
167 // 'pop' bin ID from candidate bins set
168 candidateBins.erase(candidateBinIter);
170 // quit if no more candidates
171 if ( candidateBins.empty() )
177 uint64_t BamStandardIndex::CalculateMinOffset(const BaiReferenceSummary& refSummary,
178 const uint32_t& begin)
180 // if no linear offsets exist, return 0
181 if ( refSummary.NumLinearOffsets == 0 )
184 // if 'begin' starts beyond last linear offset, use the last linear offset as minimum
185 // else use the offset corresponding to the requested start position
186 const int shiftedBegin = begin>>BamStandardIndex::BAM_LIDX_SHIFT;
187 if ( shiftedBegin >= refSummary.NumLinearOffsets )
188 return LookupLinearOffset( refSummary, refSummary.NumLinearOffsets-1 );
190 return LookupLinearOffset( refSummary, shiftedBegin );
193 void BamStandardIndex::CheckBufferSize(char*& buffer,
194 unsigned int& bufferLength,
195 const unsigned int& requestedBytes)
198 if ( requestedBytes > bufferLength ) {
199 bufferLength = requestedBytes + 10;
201 buffer = new char[bufferLength];
203 } catch ( std::bad_alloc& ) {
205 s << "out of memory when allocating " << requestedBytes << " bytes";
206 throw BamException("BamStandardIndex::CheckBufferSize", s.str());
210 void BamStandardIndex::CheckBufferSize(unsigned char*& buffer,
211 unsigned int& bufferLength,
212 const unsigned int& requestedBytes)
215 if ( requestedBytes > bufferLength ) {
216 bufferLength = requestedBytes + 10;
218 buffer = new unsigned char[bufferLength];
220 } catch ( std::bad_alloc& ) {
222 s << "out of memory when allocating " << requestedBytes << " bytes";
223 throw BamException("BamStandardIndex::CheckBufferSize", s.str());
227 void BamStandardIndex::CheckMagicNumber(void) {
229 // check 'magic number' to see if file is BAI index
231 const int64_t numBytesRead = m_resources.Device->Read(magic, sizeof(magic));
232 if ( numBytesRead != 4 )
233 throw BamException("BamStandardIndex::CheckMagicNumber", "could not read BAI magic number");
235 // compare to expected value
236 if ( strncmp(magic, BamStandardIndex::BAI_MAGIC, 4) != 0 )
237 throw BamException("BamStandardIndex::CheckMagicNumber", "invalid BAI magic number");
240 void BamStandardIndex::ClearReferenceEntry(BaiReferenceEntry& refEntry) {
242 refEntry.Bins.clear();
243 refEntry.LinearOffsets.clear();
246 void BamStandardIndex::CloseFile(void) {
249 if ( IsDeviceOpen() ) {
250 m_resources.Device->Close();
251 delete m_resources.Device;
252 m_resources.Device = 0;
255 // clear index file summary data
256 m_indexFileSummary.clear();
258 // clean up I/O buffer
259 delete[] m_resources.Buffer;
260 m_resources.Buffer = 0;
264 // builds index from associated BAM file & writes out to index file
265 bool BamStandardIndex::Create(void) {
267 // skip if BamReader is invalid or not open
268 if ( m_reader == 0 || !m_reader->IsOpen() ) {
269 SetErrorString("BamStandardIndex::Create", "could not create index: reader is not open");
274 if ( !m_reader->Rewind() ) {
275 const string readerError = m_reader->GetErrorString();
276 const string message = "could not create index: \n\t" + readerError;
277 SetErrorString("BamStandardIndex::Create", message);
283 // open new index file (read & write)
284 string indexFilename = m_reader->Filename() + Extension();
285 OpenFile(indexFilename, IBamIODevice::ReadWrite);
287 // initialize BaiFileSummary with number of references
288 const int& numReferences = m_reader->GetReferenceCount();
289 ReserveForSummary(numReferences);
291 // initialize output file
294 // set up bin, ID, offset, & coordinate markers
295 const uint32_t defaultValue = 0xffffffffu;
296 uint32_t currentBin = defaultValue;
297 uint32_t lastBin = defaultValue;
298 int32_t currentRefID = defaultValue;
299 int32_t lastRefID = defaultValue;
300 uint64_t currentOffset = (uint64_t)m_reader->Tell();
301 uint64_t lastOffset = currentOffset;
302 int32_t lastPosition = defaultValue;
304 // iterate through alignments in BAM file
306 BaiReferenceEntry refEntry;
307 while ( m_reader->LoadNextAlignment(al) ) {
309 // changed to new reference
310 if ( lastRefID != al.RefID ) {
312 // if not first reference, save previous reference data
313 if ( lastRefID != (int32_t)defaultValue ) {
315 SaveAlignmentChunkToBin(refEntry.Bins, currentBin, currentOffset, lastOffset);
316 WriteReferenceEntry(refEntry);
317 ClearReferenceEntry(refEntry);
319 // write any empty references between (but *NOT* including) lastRefID & al.RefID
320 for ( int i = lastRefID+1; i < al.RefID; ++i ) {
321 BaiReferenceEntry emptyEntry(i);
322 WriteReferenceEntry(emptyEntry);
325 // update bin markers
326 currentOffset = lastOffset;
329 currentRefID = al.RefID;
332 // otherwise, this is first pass
333 // be sure to write any empty references up to (but *NOT* including) current RefID
335 for ( int i = 0; i < al.RefID; ++i ) {
336 BaiReferenceEntry emptyEntry(i);
337 WriteReferenceEntry(emptyEntry);
341 // update reference markers
342 refEntry.ID = al.RefID;
343 lastRefID = al.RefID;
344 lastBin = defaultValue;
347 // if lastPosition greater than current alignment position - file not sorted properly
348 else if ( lastPosition > al.Position ) {
350 s << "BAM file is not properly sorted by coordinate" << endl
351 << "Current alignment position: " << al.Position
352 << " < previous alignment position: " << lastPosition
353 << " on reference ID: " << al.RefID << endl;
354 SetErrorString("BamStandardIndex::Create", s.str());
358 // if alignment's ref ID is valid & its bin is not a 'leaf'
359 if ( (al.RefID >= 0) && (al.Bin < 4681) )
360 SaveLinearOffsetEntry(refEntry.LinearOffsets, al.Position, al.GetEndPosition(), lastOffset);
362 // changed to new BAI bin
363 if ( al.Bin != lastBin ) {
365 // if not first bin on reference, save previous bin data
366 if ( currentBin != defaultValue )
367 SaveAlignmentChunkToBin(refEntry.Bins, currentBin, currentOffset, lastOffset);
370 currentOffset = lastOffset;
373 currentRefID = al.RefID;
375 // if invalid RefID, break out
376 if ( currentRefID < 0 )
380 // make sure that current file pointer is beyond lastOffset
381 if ( m_reader->Tell() <= (int64_t)lastOffset ) {
382 SetErrorString("BamStandardIndex::Create", "calculating offsets failed");
386 // update lastOffset & lastPosition
387 lastOffset = m_reader->Tell();
388 lastPosition = al.Position;
391 // after finishing alignments, if any data was read, check:
392 if ( lastOffset != currentOffset ) {
394 // store last alignment chunk to its bin, then write last reference entry with data
395 SaveAlignmentChunkToBin(refEntry.Bins, currentBin, currentOffset, lastOffset);
396 WriteReferenceEntry(refEntry);
399 // then write any empty references remaining at end of file
400 for ( int i = currentRefID+1; i < numReferences; ++i ) {
401 BaiReferenceEntry emptyEntry(i);
402 WriteReferenceEntry(emptyEntry);
405 } catch ( BamException& e) {
406 m_errorString = e.what();
411 if ( !m_reader->Rewind() ) {
412 const string readerError = m_reader->GetErrorString();
413 const string message = "could not create index: \n\t" + readerError;
414 SetErrorString("BamStandardIndex::Create", message);
422 // returns format's file extension
423 const string BamStandardIndex::Extension(void) {
424 return BamStandardIndex::BAI_EXTENSION;
427 void BamStandardIndex::GetOffset(const BamRegion& region, int64_t& offset, bool* hasAlignmentsInRegion) {
429 // cannot calculate offsets if unknown/invalid reference ID requested
430 if ( region.LeftRefID < 0 || region.LeftRefID >= (int)m_indexFileSummary.size() )
431 throw BamException("BamStandardIndex::GetOffset", "invalid reference ID requested");
433 // retrieve index summary for left bound reference
434 const BaiReferenceSummary& refSummary = m_indexFileSummary.at(region.LeftRefID);
436 // set up region boundaries based on actual BamReader data
439 AdjustRegion(region, begin, end);
441 // retrieve all candidate bin IDs for region
442 set<uint16_t> candidateBins;
443 CalculateCandidateBins(begin, end, candidateBins);
445 // use reference's linear offsets to calculate the minimum offset
446 // that must be considered to find overlap
447 const uint64_t& minOffset = CalculateMinOffset(refSummary, begin);
449 // attempt to use reference summary, minOffset, & candidateBins to calculate offsets
450 // no data should not be error, just bail
451 vector<int64_t> offsets;
452 CalculateCandidateOffsets(refSummary, minOffset, candidateBins, offsets);
453 if ( offsets.empty() )
456 // ensure that offsets are sorted before processing
457 sort( offsets.begin(), offsets.end() );
459 // binary search for an overlapping block (may not be first one though)
461 typedef vector<int64_t>::const_iterator OffsetConstIterator;
462 OffsetConstIterator offsetFirst = offsets.begin();
463 OffsetConstIterator offsetIter = offsetFirst;
464 OffsetConstIterator offsetLast = offsets.end();
465 iterator_traits<OffsetConstIterator>::difference_type count = distance(offsetFirst, offsetLast);
466 iterator_traits<OffsetConstIterator>::difference_type step;
467 while ( count > 0 ) {
468 offsetIter = offsetFirst;
470 advance(offsetIter, step);
472 // attempt seek to candidate offset
473 const int64_t& candidateOffset = (*offsetIter);
474 if ( !m_reader->Seek(candidateOffset) ) {
475 const string readerError = m_reader->GetErrorString();
476 const string message = "could not seek in BAM file: \n\t" + readerError;
477 throw BamException("BamToolsIndex::GetOffset", message);
480 // load first available alignment, setting flag to true if data exists
481 *hasAlignmentsInRegion = m_reader->LoadNextAlignment(al);
483 // check alignment against region
484 if ( al.GetEndPosition() <= region.LeftPosition ) {
485 offsetFirst = ++offsetIter;
490 // step back to the offset before the 'current offset' (to make sure we cover overlaps)
491 if ( offsetIter != offsets.begin() )
493 offset = (*offsetIter);
496 // returns whether reference has alignments or no
497 bool BamStandardIndex::HasAlignments(const int& referenceID) const {
498 if ( referenceID < 0 || referenceID >= (int)m_indexFileSummary.size() )
500 const BaiReferenceSummary& refSummary = m_indexFileSummary.at(referenceID);
501 return ( refSummary.NumBins > 0 );
504 bool BamStandardIndex::IsDeviceOpen(void) const {
505 if ( m_resources.Device == 0 )
507 return m_resources.Device->IsOpen();
510 // attempts to use index data to jump to @region, returns success/fail
511 // a "successful" jump indicates no error, but not whether this region has data
512 // * thus, the method sets a flag to indicate whether there are alignments
513 // available after the jump position
514 bool BamStandardIndex::Jump(const BamRegion& region, bool* hasAlignmentsInRegion) {
517 *hasAlignmentsInRegion = false;
519 // skip if invalid reader or not open
520 if ( m_reader == 0 || !m_reader->IsOpen() ) {
521 SetErrorString("BamStandardIndex::Jump", "could not jump: reader is not open");
525 // calculate nearest offset to jump to
528 GetOffset(region, offset, hasAlignmentsInRegion);
529 } catch ( BamException& e ) {
530 m_errorString = e.what();
534 // if region has alignments, return success/fail of seeking there
535 if ( *hasAlignmentsInRegion )
536 return m_reader->Seek(offset);
538 // otherwise, simply return true (but hasAlignmentsInRegion flag has been set to false)
539 // (this is OK, BamReader will check this flag before trying to load data)
543 // loads existing data from file into memory
544 bool BamStandardIndex::Load(const std::string& filename) {
548 // attempt to open file (read-only)
549 OpenFile(filename, IBamIODevice::ReadOnly);
554 // load in-memory summary of index data
555 SummarizeIndexFile();
560 } catch ( BamException& e ) {
561 m_errorString = e.what();
566 uint64_t BamStandardIndex::LookupLinearOffset(const BaiReferenceSummary& refSummary, const int& index) {
568 // attempt seek to proper index file position
569 const int64_t linearOffsetFilePosition = (int64_t)refSummary.FirstLinearOffsetFilePosition +
570 index*BamStandardIndex::SIZEOF_LINEAROFFSET;
571 Seek(linearOffsetFilePosition, SEEK_SET);
573 // read linear offset from BAI file
574 uint64_t linearOffset;
575 ReadLinearOffset(linearOffset);
579 void BamStandardIndex::MergeAlignmentChunks(BaiAlignmentChunkVector& chunks) {
581 // skip if chunks are empty, nothing to merge
582 if ( chunks.empty() )
585 // set up merged alignment chunk container
586 BaiAlignmentChunkVector mergedChunks;
587 mergedChunks.push_back( chunks[0] );
589 // iterate over chunks
591 BaiAlignmentChunkVector::iterator chunkIter = chunks.begin();
592 BaiAlignmentChunkVector::iterator chunkEnd = chunks.end();
593 for ( ++chunkIter; chunkIter != chunkEnd; ++chunkIter) {
595 // get 'currentMergeChunk' based on numeric index
596 BaiAlignmentChunk& currentMergeChunk = mergedChunks[i];
598 // get sourceChunk based on source vector iterator
599 BaiAlignmentChunk& sourceChunk = (*chunkIter);
601 // if currentMergeChunk ends where sourceChunk starts, then merge the two
602 if ( currentMergeChunk.Stop>>16 == sourceChunk.Start>>16 )
603 currentMergeChunk.Stop = sourceChunk.Stop;
607 // append sourceChunk after currentMergeChunk
608 mergedChunks.push_back(sourceChunk);
610 // update i, so the next iteration will consider the
611 // recently-appended sourceChunk as new mergeChunk candidate
616 // saved newly-merged chunks into (parameter) chunks
617 chunks = mergedChunks;
620 void BamStandardIndex::OpenFile(const std::string& filename, IBamIODevice::OpenMode mode) {
622 // make sure any previous index file is closed
625 m_resources.Device = BamDeviceFactory::CreateDevice(filename);
626 if ( m_resources.Device == 0 ) {
627 const string message = string("could not open file: ") + filename;
628 throw BamException("BamStandardIndex::OpenFile", message);
631 // attempt to open file
632 m_resources.Device->Open(mode);
633 if ( !IsDeviceOpen() ) {
634 const string message = string("could not open file: ") + filename;
635 throw BamException("BamStandardIndex::OpenFile", message);
639 void BamStandardIndex::ReadBinID(uint32_t& binId) {
640 const int64_t numBytesRead = m_resources.Device->Read((char*)&binId, sizeof(binId));
641 if ( m_isBigEndian ) SwapEndian_32(binId);
642 if ( numBytesRead != sizeof(binId) )
643 throw BamException("BamStandardIndex::ReadBinID", "could not read BAI bin ID");
646 void BamStandardIndex::ReadBinIntoBuffer(uint32_t& binId, int32_t& numAlignmentChunks) {
650 ReadNumAlignmentChunks(numAlignmentChunks);
653 const unsigned int bytesRequested = numAlignmentChunks*BamStandardIndex::SIZEOF_ALIGNMENTCHUNK;
654 ReadIntoBuffer(bytesRequested);
657 void BamStandardIndex::ReadIntoBuffer(const unsigned int& bytesRequested) {
659 // ensure that our buffer is big enough for request
660 BamStandardIndex::CheckBufferSize(m_resources.Buffer, m_bufferLength, bytesRequested);
662 // read from BAI file stream
663 const int64_t bytesRead = m_resources.Device->Read(m_resources.Buffer, bytesRequested);
664 if ( bytesRead != (int64_t)bytesRequested ) {
666 s << "expected to read: " << bytesRequested << " bytes, "
667 << "but instead read: " << bytesRead;
668 throw BamException("BamStandardIndex::ReadIntoBuffer", s.str());
672 void BamStandardIndex::ReadLinearOffset(uint64_t& linearOffset) {
673 const int64_t numBytesRead = m_resources.Device->Read((char*)&linearOffset, sizeof(linearOffset));
674 if ( m_isBigEndian ) SwapEndian_64(linearOffset);
675 if ( numBytesRead != sizeof(linearOffset) )
676 throw BamException("BamStandardIndex::ReadLinearOffset", "could not read BAI linear offset");
679 void BamStandardIndex::ReadNumAlignmentChunks(int& numAlignmentChunks) {
680 const int64_t numBytesRead = m_resources.Device->Read((char*)&numAlignmentChunks, sizeof(numAlignmentChunks));
681 if ( m_isBigEndian ) SwapEndian_32(numAlignmentChunks);
682 if ( numBytesRead != sizeof(numAlignmentChunks) )
683 throw BamException("BamStandardIndex::ReadNumAlignmentChunks", "could not read BAI chunk count");
686 void BamStandardIndex::ReadNumBins(int& numBins) {
687 const int64_t numBytesRead = m_resources.Device->Read((char*)&numBins, sizeof(numBins));
688 if ( m_isBigEndian ) SwapEndian_32(numBins);
689 if ( numBytesRead != sizeof(numBins) )
690 throw BamException("BamStandardIndex::ReadNumBins", "could not read BAI bin count");
693 void BamStandardIndex::ReadNumLinearOffsets(int& numLinearOffsets) {
694 const int64_t numBytesRead = m_resources.Device->Read((char*)&numLinearOffsets, sizeof(numLinearOffsets));
695 if ( m_isBigEndian ) SwapEndian_32(numLinearOffsets);
696 if ( numBytesRead != sizeof(numLinearOffsets) )
697 throw BamException("BamStandardIndex::ReadNumAlignmentChunks", "could not read BAI linear offset count");
700 void BamStandardIndex::ReadNumReferences(int& numReferences) {
701 const int64_t numBytesRead = m_resources.Device->Read((char*)&numReferences, sizeof(numReferences));
702 if ( m_isBigEndian ) SwapEndian_32(numReferences);
703 if ( numBytesRead != sizeof(numReferences) )
704 throw BamException("BamStandardIndex::ReadNumReferences", "could not read reference count");
707 void BamStandardIndex::ReserveForSummary(const int& numReferences) {
708 m_indexFileSummary.clear();
709 m_indexFileSummary.assign( numReferences, BaiReferenceSummary() );
712 void BamStandardIndex::SaveAlignmentChunkToBin(BaiBinMap& binMap,
713 const uint32_t& currentBin,
714 const uint64_t& currentOffset,
715 const uint64_t& lastOffset)
717 // create new alignment chunk
718 BaiAlignmentChunk newChunk(currentOffset, lastOffset);
720 // if no entry exists yet for this bin, create one and store alignment chunk
721 BaiBinMap::iterator binIter = binMap.find(currentBin);
722 if ( binIter == binMap.end() ) {
723 BaiAlignmentChunkVector newChunks;
724 newChunks.push_back(newChunk);
725 binMap.insert( pair<uint32_t, BaiAlignmentChunkVector>(currentBin, newChunks));
728 // otherwise, just append alignment chunk
730 BaiAlignmentChunkVector& binChunks = (*binIter).second;
731 binChunks.push_back( newChunk );
735 void BamStandardIndex::SaveBinsSummary(const int& refId, const int& numBins) {
736 BaiReferenceSummary& refSummary = m_indexFileSummary.at(refId);
737 refSummary.NumBins = numBins;
738 refSummary.FirstBinFilePosition = Tell();
741 void BamStandardIndex::SaveLinearOffsetEntry(BaiLinearOffsetVector& offsets,
742 const int& alignmentStartPosition,
743 const int& alignmentStopPosition,
744 const uint64_t& lastOffset)
746 // get converted offsets
747 const int beginOffset = alignmentStartPosition >> BamStandardIndex::BAM_LIDX_SHIFT;
748 const int endOffset = (alignmentStopPosition - 1) >> BamStandardIndex::BAM_LIDX_SHIFT;
750 // resize vector if necessary
751 int oldSize = offsets.size();
752 int newSize = endOffset + 1;
753 if ( oldSize < newSize )
754 offsets.resize(newSize, 0);
757 for( int i = beginOffset + 1; i <= endOffset; ++i ) {
758 if ( offsets[i] == 0 )
759 offsets[i] = lastOffset;
763 void BamStandardIndex::SaveLinearOffsetsSummary(const int& refId, const int& numLinearOffsets) {
764 BaiReferenceSummary& refSummary = m_indexFileSummary.at(refId);
765 refSummary.NumLinearOffsets = numLinearOffsets;
766 refSummary.FirstLinearOffsetFilePosition = Tell();
769 // seek to position in index file stream
770 void BamStandardIndex::Seek(const int64_t& position, const int origin) {
771 if ( !m_resources.Device->Seek(position, origin) )
772 throw BamException("BamStandardIndex::Seek", "could not seek in BAI file");
775 void BamStandardIndex::SkipBins(const int& numBins) {
777 int32_t numAlignmentChunks;
778 for (int i = 0; i < numBins; ++i)
779 ReadBinIntoBuffer(binId, numAlignmentChunks); // results & buffer ignored
782 void BamStandardIndex::SkipLinearOffsets(const int& numLinearOffsets) {
783 const unsigned int bytesRequested = numLinearOffsets*BamStandardIndex::SIZEOF_LINEAROFFSET;
784 ReadIntoBuffer(bytesRequested);
787 void BamStandardIndex::SortLinearOffsets(BaiLinearOffsetVector& linearOffsets) {
788 sort( linearOffsets.begin(), linearOffsets.end() );
791 void BamStandardIndex::SummarizeBins(BaiReferenceSummary& refSummary) {
793 // load number of bins
795 ReadNumBins(numBins);
797 // store bins summary for this reference
798 refSummary.NumBins = numBins;
799 refSummary.FirstBinFilePosition = Tell();
801 // skip this reference's bins
805 void BamStandardIndex::SummarizeIndexFile(void) {
807 // load number of reference sequences
809 ReadNumReferences(numReferences);
811 // initialize file summary data
812 ReserveForSummary(numReferences);
814 // iterate over reference entries
815 BaiFileSummary::iterator summaryIter = m_indexFileSummary.begin();
816 BaiFileSummary::iterator summaryEnd = m_indexFileSummary.end();
817 for ( int i = 0; summaryIter != summaryEnd; ++summaryIter, ++i )
818 SummarizeReference(*summaryIter);
821 void BamStandardIndex::SummarizeLinearOffsets(BaiReferenceSummary& refSummary) {
823 // load number of linear offsets
824 int numLinearOffsets;
825 ReadNumLinearOffsets(numLinearOffsets);
827 // store bin summary data for this reference
828 refSummary.NumLinearOffsets = numLinearOffsets;
829 refSummary.FirstLinearOffsetFilePosition = Tell();
831 // skip linear offsets in index file
832 SkipLinearOffsets(numLinearOffsets);
835 void BamStandardIndex::SummarizeReference(BaiReferenceSummary& refSummary) {
836 SummarizeBins(refSummary);
837 SummarizeLinearOffsets(refSummary);
840 // return position of file pointer in index file stream
841 int64_t BamStandardIndex::Tell(void) const {
842 return m_resources.Device->Tell();
845 void BamStandardIndex::WriteAlignmentChunk(const BaiAlignmentChunk& chunk) {
847 // localize alignment chunk offsets
848 uint64_t start = chunk.Start;
849 uint64_t stop = chunk.Stop;
851 // swap endian-ness if necessary
852 if ( m_isBigEndian ) {
853 SwapEndian_64(start);
857 // write to index file
858 int64_t numBytesWritten = 0;
859 numBytesWritten += m_resources.Device->Write((const char*)&start, sizeof(start));
860 numBytesWritten += m_resources.Device->Write((const char*)&stop, sizeof(stop));
861 if ( numBytesWritten != (sizeof(start)+sizeof(stop)) )
862 throw BamException("BamStandardIndex::WriteAlignmentChunk", "could not write BAI alignment chunk");
865 void BamStandardIndex::WriteAlignmentChunks(BaiAlignmentChunkVector& chunks) {
867 // make sure chunks are merged (simplified) before writing & saving summary
868 MergeAlignmentChunks(chunks);
871 int32_t chunkCount = chunks.size();
872 if ( m_isBigEndian ) SwapEndian_32(chunkCount);
873 const int64_t numBytesWritten = m_resources.Device->Write((const char*)&chunkCount, sizeof(chunkCount));
874 if ( numBytesWritten != sizeof(chunkCount) )
875 throw BamException("BamStandardIndex::WriteAlignmentChunks", "could not write BAI chunk count");
877 // iterate over chunks
878 BaiAlignmentChunkVector::const_iterator chunkIter = chunks.begin();
879 BaiAlignmentChunkVector::const_iterator chunkEnd = chunks.end();
880 for ( ; chunkIter != chunkEnd; ++chunkIter )
881 WriteAlignmentChunk( (*chunkIter) );
884 void BamStandardIndex::WriteBin(const uint32_t& binId, BaiAlignmentChunkVector& chunks) {
887 uint32_t binKey = binId;
888 if ( m_isBigEndian ) SwapEndian_32(binKey);
889 const int64_t numBytesWritten = m_resources.Device->Write((const char*)&binKey, sizeof(binKey));
890 if ( numBytesWritten != sizeof(binKey) )
891 throw BamException("BamStandardIndex::WriteBin", "could not write bin ID");
893 // write bin's alignment chunks
894 WriteAlignmentChunks(chunks);
897 void BamStandardIndex::WriteBins(const int& refId, BaiBinMap& bins) {
899 // write number of bins
900 int32_t binCount = bins.size();
901 if ( m_isBigEndian ) SwapEndian_32(binCount);
902 const int64_t numBytesWritten = m_resources.Device->Write((const char*)&binCount, sizeof(binCount));
903 if ( numBytesWritten != sizeof(binCount) )
904 throw BamException("BamStandardIndex::WriteBins", "could not write bin count");
906 // save summary for reference's bins
907 SaveBinsSummary(refId, bins.size());
910 BaiBinMap::iterator binIter = bins.begin();
911 BaiBinMap::iterator binEnd = bins.end();
912 for ( ; binIter != binEnd; ++binIter )
913 WriteBin( (*binIter).first, (*binIter).second );
916 void BamStandardIndex::WriteHeader(void) {
918 int64_t numBytesWritten = 0;
920 // write magic number
921 numBytesWritten += m_resources.Device->Write(BamStandardIndex::BAI_MAGIC, 4);
923 // write number of reference sequences
924 int32_t numReferences = m_indexFileSummary.size();
925 if ( m_isBigEndian ) SwapEndian_32(numReferences);
926 numBytesWritten += m_resources.Device->Write((const char*)&numReferences, sizeof(numReferences));
928 if ( numBytesWritten != sizeof(numReferences)+4 )
929 throw BamException("BamStandardIndex::WriteHeader", "could not write BAI header");
932 void BamStandardIndex::WriteLinearOffsets(const int& refId, BaiLinearOffsetVector& linearOffsets) {
934 // make sure linear offsets are sorted before writing & saving summary
935 SortLinearOffsets(linearOffsets);
937 int64_t numBytesWritten = 0;
939 // write number of linear offsets
940 int32_t offsetCount = linearOffsets.size();
941 if ( m_isBigEndian ) SwapEndian_32(offsetCount);
942 numBytesWritten += m_resources.Device->Write((const char*)&offsetCount, sizeof(offsetCount));
944 // save summary for reference's linear offsets
945 SaveLinearOffsetsSummary(refId, linearOffsets.size());
947 // iterate over linear offsets
948 BaiLinearOffsetVector::const_iterator offsetIter = linearOffsets.begin();
949 BaiLinearOffsetVector::const_iterator offsetEnd = linearOffsets.end();
950 for ( ; offsetIter != offsetEnd; ++offsetIter ) {
952 // write linear offset
953 uint64_t linearOffset = (*offsetIter);
954 if ( m_isBigEndian ) SwapEndian_64(linearOffset);
955 numBytesWritten += m_resources.Device->Write((const char*)&linearOffset, sizeof(linearOffset));
958 if ( numBytesWritten != (sizeof(offsetCount) + linearOffsets.size()*sizeof(uint64_t)) )
959 throw BamException("BamStandardIndex::WriteLinearOffsets", "could not write BAI linear offsets");
962 void BamStandardIndex::WriteReferenceEntry(BaiReferenceEntry& refEntry) {
963 WriteBins(refEntry.ID, refEntry.Bins);
964 WriteLinearOffsets(refEntry.ID, refEntry.LinearOffsets);