1 // ***************************************************************************
2 // BamWriter_p.cpp (c) 2010 Derek Barnett
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 7 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
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 BamAlignment.Bin is already defined (no default, invalid value)
217 // force calculation of Bin before storing
218 const int endPosition = al.GetEndPosition();
219 const uint32_t alignmentBin = CalculateMinimumBin(al.Position, endPosition);
221 // create our packed cigar string
223 CreatePackedCigar(al.CigarData, packedCigar);
224 const unsigned int packedCigarLength = packedCigar.size();
228 EncodeQuerySequence(al.QueryBases, encodedQuery);
229 const unsigned int encodedQueryLength = encodedQuery.size();
231 // write the block size
232 const unsigned int dataBlockSize = nameLength +
237 unsigned int blockSize = Constants::BAM_CORE_SIZE + dataBlockSize;
238 if ( m_isBigEndian ) BamTools::SwapEndian_32(blockSize);
239 m_stream.Write((char*)&blockSize, Constants::BAM_SIZEOF_INT);
241 // assign the BAM core data
242 uint32_t buffer[Constants::BAM_CORE_BUFFER_SIZE];
243 buffer[0] = al.RefID;
244 buffer[1] = al.Position;
245 buffer[2] = (alignmentBin << 16) | (al.MapQuality << 8) | nameLength;
246 buffer[3] = (al.AlignmentFlag << 16) | numCigarOperations;
247 buffer[4] = queryLength;
248 buffer[5] = al.MateRefID;
249 buffer[6] = al.MatePosition;
250 buffer[7] = al.InsertSize;
252 // swap BAM core endian-ness, if necessary
253 if ( m_isBigEndian ) {
254 for ( int i = 0; i < 8; ++i )
255 BamTools::SwapEndian_32(buffer[i]);
258 // write the BAM core
259 m_stream.Write((char*)&buffer, Constants::BAM_CORE_SIZE);
261 // write the query name
262 m_stream.Write(al.Name.c_str(), nameLength);
264 // write the packed cigar
265 if ( m_isBigEndian ) {
266 char* cigarData = new char[packedCigarLength]();
267 memcpy(cigarData, packedCigar.data(), packedCigarLength);
268 if ( m_isBigEndian ) {
269 for ( size_t i = 0; i < packedCigarLength; ++i )
270 BamTools::SwapEndian_32p(&cigarData[i]);
272 m_stream.Write(cigarData, packedCigarLength);
273 delete[] cigarData; // TODO: cleanup on Write exception thrown?
276 m_stream.Write(packedCigar.data(), packedCigarLength);
278 // write the encoded query sequence
279 m_stream.Write(encodedQuery.data(), encodedQueryLength);
281 // write the base qualities
282 char* pBaseQualities = (char*)al.Qualities.data();
283 for ( size_t i = 0; i < queryLength; ++i )
284 pBaseQualities[i] -= 33; // FASTQ conversion
285 m_stream.Write(pBaseQualities, queryLength);
287 // write the read group tag
288 if ( m_isBigEndian ) {
290 char* tagData = new char[tagDataLength]();
291 memcpy(tagData, al.TagData.data(), tagDataLength);
294 while ( i < tagDataLength ) {
296 i += Constants::BAM_TAG_TAGSIZE; // skip tag chars (e.g. "RG", "NM", etc.)
297 const char type = tagData[i]; // get tag type at position i
302 case(Constants::BAM_TAG_TYPE_ASCII) :
303 case(Constants::BAM_TAG_TYPE_INT8) :
304 case(Constants::BAM_TAG_TYPE_UINT8) :
308 case(Constants::BAM_TAG_TYPE_INT16) :
309 case(Constants::BAM_TAG_TYPE_UINT16) :
310 BamTools::SwapEndian_16p(&tagData[i]);
311 i += sizeof(uint16_t);
314 case(Constants::BAM_TAG_TYPE_FLOAT) :
315 case(Constants::BAM_TAG_TYPE_INT32) :
316 case(Constants::BAM_TAG_TYPE_UINT32) :
317 BamTools::SwapEndian_32p(&tagData[i]);
318 i += sizeof(uint32_t);
321 case(Constants::BAM_TAG_TYPE_HEX) :
322 case(Constants::BAM_TAG_TYPE_STRING) :
323 // no endian swapping necessary for hex-string/string data
326 // increment one more for null terminator
330 case(Constants::BAM_TAG_TYPE_ARRAY) :
334 const char arrayType = tagData[i];
337 // swap endian-ness of number of elements in place, then retrieve for loop
338 BamTools::SwapEndian_32p(&tagData[i]);
340 memcpy(&numElements, &tagData[i], sizeof(uint32_t));
341 i += sizeof(uint32_t);
343 // swap endian-ness of array elements
344 for ( int j = 0; j < numElements; ++j ) {
346 case (Constants::BAM_TAG_TYPE_INT8) :
347 case (Constants::BAM_TAG_TYPE_UINT8) :
348 // no endian-swapping necessary
351 case (Constants::BAM_TAG_TYPE_INT16) :
352 case (Constants::BAM_TAG_TYPE_UINT16) :
353 BamTools::SwapEndian_16p(&tagData[i]);
354 i += sizeof(uint16_t);
356 case (Constants::BAM_TAG_TYPE_FLOAT) :
357 case (Constants::BAM_TAG_TYPE_INT32) :
358 case (Constants::BAM_TAG_TYPE_UINT32) :
359 BamTools::SwapEndian_32p(&tagData[i]);
360 i += sizeof(uint32_t);
364 const string message = string("invalid binary array type: ") + arrayType;
365 throw BamException("BamWriter::SaveAlignment", message);
374 const string message = string("invalid tag type: ") + type;
375 throw BamException("BamWriter::SaveAlignment", message);
379 m_stream.Write(tagData, tagDataLength);
380 delete[] tagData; // TODO: cleanup on Write exception thrown?
383 m_stream.Write(al.TagData.data(), tagDataLength);
386 void BamWriterPrivate::WriteCoreAlignment(const BamAlignment& al) {
388 // write the block size
389 unsigned int blockSize = al.SupportData.BlockLength;
390 if ( m_isBigEndian ) BamTools::SwapEndian_32(blockSize);
391 m_stream.Write((char*)&blockSize, Constants::BAM_SIZEOF_INT);
393 // re-calculate bin (in case BamAlignment's position has been previously modified)
394 const uint32_t alignmentBin = CalculateMinimumBin(al.Position, al.GetEndPosition());
396 // assign the BAM core data
397 uint32_t buffer[Constants::BAM_CORE_BUFFER_SIZE];
398 buffer[0] = al.RefID;
399 buffer[1] = al.Position;
400 buffer[2] = (alignmentBin << 16) | (al.MapQuality << 8) | al.SupportData.QueryNameLength;
401 buffer[3] = (al.AlignmentFlag << 16) | al.SupportData.NumCigarOperations;
402 buffer[4] = al.SupportData.QuerySequenceLength;
403 buffer[5] = al.MateRefID;
404 buffer[6] = al.MatePosition;
405 buffer[7] = al.InsertSize;
407 // swap BAM core endian-ness, if necessary
408 if ( m_isBigEndian ) {
409 for ( int i = 0; i < 8; ++i )
410 BamTools::SwapEndian_32(buffer[i]);
413 // write the BAM core
414 m_stream.Write((char*)&buffer, Constants::BAM_CORE_SIZE);
416 // write the raw char data
417 m_stream.Write((char*)al.SupportData.AllCharData.data(),
418 al.SupportData.BlockLength-Constants::BAM_CORE_SIZE);
421 void BamWriterPrivate::WriteMagicNumber(void) {
422 // write BAM file 'magic number'
423 m_stream.Write(Constants::BAM_HEADER_MAGIC, Constants::BAM_HEADER_MAGIC_LENGTH);
426 void BamWriterPrivate::WriteReferences(const BamTools::RefVector& referenceSequences) {
428 // write the number of reference sequences
429 uint32_t numReferenceSequences = referenceSequences.size();
430 if ( m_isBigEndian ) BamTools::SwapEndian_32(numReferenceSequences);
431 m_stream.Write((char*)&numReferenceSequences, Constants::BAM_SIZEOF_INT);
433 // foreach reference sequence
434 RefVector::const_iterator rsIter = referenceSequences.begin();
435 RefVector::const_iterator rsEnd = referenceSequences.end();
436 for ( ; rsIter != rsEnd; ++rsIter ) {
438 // write the reference sequence name length
439 uint32_t referenceSequenceNameLen = rsIter->RefName.size() + 1;
440 if ( m_isBigEndian ) BamTools::SwapEndian_32(referenceSequenceNameLen);
441 m_stream.Write((char*)&referenceSequenceNameLen, Constants::BAM_SIZEOF_INT);
443 // write the reference sequence name
444 m_stream.Write(rsIter->RefName.c_str(), referenceSequenceNameLen);
446 // write the reference sequence length
447 int32_t referenceLength = rsIter->RefLength;
448 if ( m_isBigEndian ) BamTools::SwapEndian_32(referenceLength);
449 m_stream.Write((char*)&referenceLength, Constants::BAM_SIZEOF_INT);
453 void BamWriterPrivate::WriteSamHeaderText(const std::string& samHeaderText) {
455 // write the SAM header text length
456 uint32_t samHeaderLen = samHeaderText.size();
457 if ( m_isBigEndian ) BamTools::SwapEndian_32(samHeaderLen);
458 m_stream.Write((char*)&samHeaderLen, Constants::BAM_SIZEOF_INT);
460 // write the SAM header text
461 if ( samHeaderLen > 0 )
462 m_stream.Write(samHeaderText.data(), samHeaderLen);