1 // ***************************************************************************
2 // BamWriter_p.cpp (c) 2010 Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 10 October 2011 (DB)
6 // ---------------------------------------------------------------------------
7 // Provides the basic functionality for producing BAM files
8 // ***************************************************************************
10 #include "api/BamAlignment.h"
11 #include "api/BamConstants.h"
12 #include "api/IBamIODevice.h"
13 #include "api/internal/BamException_p.h"
14 #include "api/internal/BamWriter_p.h"
15 using namespace BamTools;
16 using namespace BamTools::Internal;
23 BamWriterPrivate::BamWriterPrivate(void)
24 : m_isBigEndian( BamTools::SystemIsBigEndian() )
28 BamWriterPrivate::~BamWriterPrivate(void) {
32 // calculates minimum bin for a BAM alignment interval [begin, end)
33 uint32_t BamWriterPrivate::CalculateMinimumBin(const int begin, int end) const {
35 if ( (begin >> 14) == (end >> 14) ) return 4681 + (begin >> 14);
36 if ( (begin >> 17) == (end >> 17) ) return 585 + (begin >> 17);
37 if ( (begin >> 20) == (end >> 20) ) return 73 + (begin >> 20);
38 if ( (begin >> 23) == (end >> 23) ) return 9 + (begin >> 23);
39 if ( (begin >> 26) == (end >> 26) ) return 1 + (begin >> 26);
43 // closes the alignment archive
44 void BamWriterPrivate::Close(void) {
46 // skip if file not open
47 if ( !IsOpen() ) return;
49 // close output stream
52 } catch ( BamException& e ) {
53 m_errorString = e.what();
57 // creates a cigar string from the supplied alignment
58 void BamWriterPrivate::CreatePackedCigar(const vector<CigarOp>& cigarOperations, string& packedCigar) {
61 const size_t numCigarOperations = cigarOperations.size();
62 packedCigar.resize(numCigarOperations * Constants::BAM_SIZEOF_INT);
64 // pack the cigar data into the string
65 unsigned int* pPackedCigar = (unsigned int*)packedCigar.data();
67 // iterate over cigar operations
68 vector<CigarOp>::const_iterator coIter = cigarOperations.begin();
69 vector<CigarOp>::const_iterator coEnd = cigarOperations.end();
70 for ( ; coIter != coEnd; ++coIter ) {
72 // store op in packedCigar
74 switch ( coIter->Type ) {
75 case (Constants::BAM_CIGAR_MATCH_CHAR) : cigarOp = Constants::BAM_CIGAR_MATCH; break;
76 case (Constants::BAM_CIGAR_INS_CHAR) : cigarOp = Constants::BAM_CIGAR_INS; break;
77 case (Constants::BAM_CIGAR_DEL_CHAR) : cigarOp = Constants::BAM_CIGAR_DEL; break;
78 case (Constants::BAM_CIGAR_REFSKIP_CHAR) : cigarOp = Constants::BAM_CIGAR_REFSKIP; break;
79 case (Constants::BAM_CIGAR_SOFTCLIP_CHAR) : cigarOp = Constants::BAM_CIGAR_SOFTCLIP; break;
80 case (Constants::BAM_CIGAR_HARDCLIP_CHAR) : cigarOp = Constants::BAM_CIGAR_HARDCLIP; break;
81 case (Constants::BAM_CIGAR_PAD_CHAR) : cigarOp = Constants::BAM_CIGAR_PAD; break;
82 case (Constants::BAM_CIGAR_SEQMATCH_CHAR) : cigarOp = Constants::BAM_CIGAR_SEQMATCH; break;
83 case (Constants::BAM_CIGAR_MISMATCH_CHAR) : cigarOp = Constants::BAM_CIGAR_MISMATCH; break;
85 const string message = string("invalid CIGAR operation type") + coIter->Type;
86 throw BamException("BamWriter::CreatePackedCigar", message);
89 *pPackedCigar = coIter->Length << Constants::BAM_CIGAR_SHIFT | cigarOp;
94 // encodes the supplied query sequence into 4-bit notation
95 void BamWriterPrivate::EncodeQuerySequence(const string& query, string& encodedQuery) {
97 // prepare the encoded query string
98 const size_t queryLength = query.size();
99 const size_t encodedQueryLength = static_cast<size_t>((queryLength+1)/2);
100 encodedQuery.resize(encodedQueryLength);
101 char* pEncodedQuery = (char*)encodedQuery.data();
102 const char* pQuery = (const char*)query.data();
104 // walk through original query sequence, encoding its bases
105 unsigned char nucleotideCode;
106 bool useHighWord = true;
109 case (Constants::BAM_DNA_EQUAL) : nucleotideCode = Constants::BAM_BASECODE_EQUAL; break;
110 case (Constants::BAM_DNA_A) : nucleotideCode = Constants::BAM_BASECODE_A; break;
111 case (Constants::BAM_DNA_C) : nucleotideCode = Constants::BAM_BASECODE_C; break;
112 case (Constants::BAM_DNA_M) : nucleotideCode = Constants::BAM_BASECODE_M; break;
113 case (Constants::BAM_DNA_G) : nucleotideCode = Constants::BAM_BASECODE_G; break;
114 case (Constants::BAM_DNA_R) : nucleotideCode = Constants::BAM_BASECODE_R; break;
115 case (Constants::BAM_DNA_S) : nucleotideCode = Constants::BAM_BASECODE_S; break;
116 case (Constants::BAM_DNA_V) : nucleotideCode = Constants::BAM_BASECODE_V; break;
117 case (Constants::BAM_DNA_T) : nucleotideCode = Constants::BAM_BASECODE_T; break;
118 case (Constants::BAM_DNA_W) : nucleotideCode = Constants::BAM_BASECODE_W; break;
119 case (Constants::BAM_DNA_Y) : nucleotideCode = Constants::BAM_BASECODE_Y; break;
120 case (Constants::BAM_DNA_H) : nucleotideCode = Constants::BAM_BASECODE_H; break;
121 case (Constants::BAM_DNA_K) : nucleotideCode = Constants::BAM_BASECODE_K; break;
122 case (Constants::BAM_DNA_D) : nucleotideCode = Constants::BAM_BASECODE_D; break;
123 case (Constants::BAM_DNA_B) : nucleotideCode = Constants::BAM_BASECODE_B; break;
124 case (Constants::BAM_DNA_N) : nucleotideCode = Constants::BAM_BASECODE_N; break;
126 const string message = string("invalid base: ") + *pQuery;
127 throw BamException("BamWriter::EncodeQuerySequence", message);
130 // pack the nucleotide code
132 *pEncodedQuery = nucleotideCode << 4;
135 *pEncodedQuery |= nucleotideCode;
140 // increment the query position
145 // returns a description of the last error that occurred
146 std::string BamWriterPrivate::GetErrorString(void) const {
147 return m_errorString;
150 // returns whether BAM file is open for writing or not
151 bool BamWriterPrivate::IsOpen(void) const {
152 return m_stream.IsOpen();
155 // opens the alignment archive
156 bool BamWriterPrivate::Open(const string& filename,
157 const string& samHeaderText,
158 const RefVector& referenceSequences)
162 // open the BGZF file for writing
163 m_stream.Open(filename, IBamIODevice::WriteOnly);
165 // write BAM file 'metadata' components
167 WriteSamHeaderText(samHeaderText);
168 WriteReferences(referenceSequences);
173 } catch ( BamException& e ) {
174 m_errorString = e.what();
179 // saves the alignment to the alignment archive
180 bool BamWriterPrivate::SaveAlignment(const BamAlignment& al) {
184 // if BamAlignment contains only the core data and a raw char data buffer
185 // (as a result of BamReader::GetNextAlignmentCore())
186 if ( al.SupportData.HasCoreOnly )
187 WriteCoreAlignment(al);
189 // otherwise, BamAlignment should contain character in the standard fields: Name, QueryBases, etc
190 // (resulting from BamReader::GetNextAlignment() *OR* being generated directly by client code)
191 else WriteAlignment(al);
193 // if we get here, everything OK
196 } catch ( BamException& e ) {
197 m_errorString = e.what();
202 void BamWriterPrivate::SetWriteCompressed(bool ok) {
203 // modifying compression is not allowed if BAM file is open
205 m_stream.SetWriteCompressed(ok);
208 void BamWriterPrivate::WriteAlignment(const BamAlignment& al) {
210 // calculate char lengths
211 const unsigned int nameLength = al.Name.size() + 1;
212 const unsigned int numCigarOperations = al.CigarData.size();
213 const unsigned int queryLength = al.QueryBases.size();
214 const unsigned int tagDataLength = al.TagData.size();
216 // no way to tell if alignment's bin is already defined (there is no default, invalid value)
217 // so we'll go ahead calculate its bin ID before storing
218 const uint32_t alignmentBin = CalculateMinimumBin(al.Position, al.GetEndPosition());
220 // create our packed cigar string
222 CreatePackedCigar(al.CigarData, packedCigar);
223 const unsigned int packedCigarLength = packedCigar.size();
227 EncodeQuerySequence(al.QueryBases, encodedQuery);
228 const unsigned int encodedQueryLength = encodedQuery.size();
230 // write the block size
231 const unsigned int dataBlockSize = nameLength +
236 unsigned int blockSize = Constants::BAM_CORE_SIZE + dataBlockSize;
237 if ( m_isBigEndian ) BamTools::SwapEndian_32(blockSize);
238 m_stream.Write((char*)&blockSize, Constants::BAM_SIZEOF_INT);
240 // assign the BAM core data
241 uint32_t buffer[Constants::BAM_CORE_BUFFER_SIZE];
242 buffer[0] = al.RefID;
243 buffer[1] = al.Position;
244 buffer[2] = (alignmentBin << 16) | (al.MapQuality << 8) | nameLength;
245 buffer[3] = (al.AlignmentFlag << 16) | numCigarOperations;
246 buffer[4] = queryLength;
247 buffer[5] = al.MateRefID;
248 buffer[6] = al.MatePosition;
249 buffer[7] = al.InsertSize;
251 // swap BAM core endian-ness, if necessary
252 if ( m_isBigEndian ) {
253 for ( int i = 0; i < 8; ++i )
254 BamTools::SwapEndian_32(buffer[i]);
257 // write the BAM core
258 m_stream.Write((char*)&buffer, Constants::BAM_CORE_SIZE);
260 // write the query name
261 m_stream.Write(al.Name.c_str(), nameLength);
263 // write the packed cigar
264 if ( m_isBigEndian ) {
265 char* cigarData = new char[packedCigarLength]();
266 memcpy(cigarData, packedCigar.data(), packedCigarLength);
267 if ( m_isBigEndian ) {
268 for ( size_t i = 0; i < packedCigarLength; ++i )
269 BamTools::SwapEndian_32p(&cigarData[i]);
271 m_stream.Write(cigarData, packedCigarLength);
272 delete[] cigarData; // TODO: cleanup on Write exception thrown?
275 m_stream.Write(packedCigar.data(), packedCigarLength);
277 // write the encoded query sequence
278 m_stream.Write(encodedQuery.data(), encodedQueryLength);
280 // write the base qualities
281 char* pBaseQualities = (char*)al.Qualities.data();
282 for ( size_t i = 0; i < queryLength; ++i )
283 pBaseQualities[i] -= 33; // FASTQ conversion
284 m_stream.Write(pBaseQualities, queryLength);
286 // write the read group tag
287 if ( m_isBigEndian ) {
289 char* tagData = new char[tagDataLength]();
290 memcpy(tagData, al.TagData.data(), tagDataLength);
293 while ( i < tagDataLength ) {
295 i += Constants::BAM_TAG_TAGSIZE; // skip tag chars (e.g. "RG", "NM", etc.)
296 const char type = tagData[i]; // get tag type at position i
301 case(Constants::BAM_TAG_TYPE_ASCII) :
302 case(Constants::BAM_TAG_TYPE_INT8) :
303 case(Constants::BAM_TAG_TYPE_UINT8) :
307 case(Constants::BAM_TAG_TYPE_INT16) :
308 case(Constants::BAM_TAG_TYPE_UINT16) :
309 BamTools::SwapEndian_16p(&tagData[i]);
310 i += sizeof(uint16_t);
313 case(Constants::BAM_TAG_TYPE_FLOAT) :
314 case(Constants::BAM_TAG_TYPE_INT32) :
315 case(Constants::BAM_TAG_TYPE_UINT32) :
316 BamTools::SwapEndian_32p(&tagData[i]);
317 i += sizeof(uint32_t);
320 case(Constants::BAM_TAG_TYPE_HEX) :
321 case(Constants::BAM_TAG_TYPE_STRING) :
322 // no endian swapping necessary for hex-string/string data
325 // increment one more for null terminator
329 case(Constants::BAM_TAG_TYPE_ARRAY) :
333 const char arrayType = tagData[i];
336 // swap endian-ness of number of elements in place, then retrieve for loop
337 BamTools::SwapEndian_32p(&tagData[i]);
339 memcpy(&numElements, &tagData[i], sizeof(uint32_t));
340 i += sizeof(uint32_t);
342 // swap endian-ness of array elements
343 for ( int j = 0; j < numElements; ++j ) {
345 case (Constants::BAM_TAG_TYPE_INT8) :
346 case (Constants::BAM_TAG_TYPE_UINT8) :
347 // no endian-swapping necessary
350 case (Constants::BAM_TAG_TYPE_INT16) :
351 case (Constants::BAM_TAG_TYPE_UINT16) :
352 BamTools::SwapEndian_16p(&tagData[i]);
353 i += sizeof(uint16_t);
355 case (Constants::BAM_TAG_TYPE_FLOAT) :
356 case (Constants::BAM_TAG_TYPE_INT32) :
357 case (Constants::BAM_TAG_TYPE_UINT32) :
358 BamTools::SwapEndian_32p(&tagData[i]);
359 i += sizeof(uint32_t);
363 const string message = string("invalid binary array type: ") + arrayType;
364 throw BamException("BamWriter::SaveAlignment", message);
373 const string message = string("invalid tag type: ") + type;
374 throw BamException("BamWriter::SaveAlignment", message);
378 m_stream.Write(tagData, tagDataLength);
379 delete[] tagData; // TODO: cleanup on Write exception thrown?
382 m_stream.Write(al.TagData.data(), tagDataLength);
385 void BamWriterPrivate::WriteCoreAlignment(const BamAlignment& al) {
387 // write the block size
388 unsigned int blockSize = al.SupportData.BlockLength;
389 if ( m_isBigEndian ) BamTools::SwapEndian_32(blockSize);
390 m_stream.Write((char*)&blockSize, Constants::BAM_SIZEOF_INT);
392 // re-calculate bin (in case BamAlignment's position has been previously modified)
393 const uint32_t alignmentBin = CalculateMinimumBin(al.Position, al.GetEndPosition());
395 // assign the BAM core data
396 uint32_t buffer[Constants::BAM_CORE_BUFFER_SIZE];
397 buffer[0] = al.RefID;
398 buffer[1] = al.Position;
399 buffer[2] = (alignmentBin << 16) | (al.MapQuality << 8) | al.SupportData.QueryNameLength;
400 buffer[3] = (al.AlignmentFlag << 16) | al.SupportData.NumCigarOperations;
401 buffer[4] = al.SupportData.QuerySequenceLength;
402 buffer[5] = al.MateRefID;
403 buffer[6] = al.MatePosition;
404 buffer[7] = al.InsertSize;
406 // swap BAM core endian-ness, if necessary
407 if ( m_isBigEndian ) {
408 for ( int i = 0; i < 8; ++i )
409 BamTools::SwapEndian_32(buffer[i]);
412 // write the BAM core
413 m_stream.Write((char*)&buffer, Constants::BAM_CORE_SIZE);
415 // write the raw char data
416 m_stream.Write((char*)al.SupportData.AllCharData.data(),
417 al.SupportData.BlockLength-Constants::BAM_CORE_SIZE);
420 void BamWriterPrivate::WriteMagicNumber(void) {
421 // write BAM file 'magic number'
422 m_stream.Write(Constants::BAM_HEADER_MAGIC, Constants::BAM_HEADER_MAGIC_LENGTH);
425 void BamWriterPrivate::WriteReferences(const BamTools::RefVector& referenceSequences) {
427 // write the number of reference sequences
428 uint32_t numReferenceSequences = referenceSequences.size();
429 if ( m_isBigEndian ) BamTools::SwapEndian_32(numReferenceSequences);
430 m_stream.Write((char*)&numReferenceSequences, Constants::BAM_SIZEOF_INT);
432 // foreach reference sequence
433 RefVector::const_iterator rsIter = referenceSequences.begin();
434 RefVector::const_iterator rsEnd = referenceSequences.end();
435 for ( ; rsIter != rsEnd; ++rsIter ) {
437 // write the reference sequence name length
438 uint32_t referenceSequenceNameLen = rsIter->RefName.size() + 1;
439 if ( m_isBigEndian ) BamTools::SwapEndian_32(referenceSequenceNameLen);
440 m_stream.Write((char*)&referenceSequenceNameLen, Constants::BAM_SIZEOF_INT);
442 // write the reference sequence name
443 m_stream.Write(rsIter->RefName.c_str(), referenceSequenceNameLen);
445 // write the reference sequence length
446 int32_t referenceLength = rsIter->RefLength;
447 if ( m_isBigEndian ) BamTools::SwapEndian_32(referenceLength);
448 m_stream.Write((char*)&referenceLength, Constants::BAM_SIZEOF_INT);
452 void BamWriterPrivate::WriteSamHeaderText(const std::string& samHeaderText) {
454 // write the SAM header text length
455 uint32_t samHeaderLen = samHeaderText.size();
456 if ( m_isBigEndian ) BamTools::SwapEndian_32(samHeaderLen);
457 m_stream.Write((char*)&samHeaderLen, Constants::BAM_SIZEOF_INT);
459 // write the SAM header text
460 if ( samHeaderLen > 0 )
461 m_stream.Write(samHeaderText.data(), samHeaderLen);