1 // ***************************************************************************
\r
2 // BamWriter.cpp (c) 2009 Michael Str�mberg, Derek Barnett
\r
3 // Marth Lab, Department of Biology, Boston College
\r
4 // All rights reserved.
\r
5 // ---------------------------------------------------------------------------
\r
6 // Last modified: 30 March 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 producing BAM files
\r
12 // ***************************************************************************
\r
16 #include "BamWriter.h"
\r
17 using namespace BamTools;
\r
18 using namespace std;
\r
20 struct BamWriter::BamWriterPrivate {
\r
26 // constructor / destructor
\r
27 BamWriterPrivate(void) {
\r
28 IsBigEndian = SystemIsBigEndian();
\r
31 ~BamWriterPrivate(void) {
\r
35 // "public" interface
\r
37 void Open(const string& filename, const string& samHeader, const RefVector& referenceSequences);
\r
38 void SaveAlignment(const BamAlignment& al);
\r
41 void CreatePackedCigar(const vector<CigarOp>& cigarOperations, string& packedCigar);
\r
42 void EncodeQuerySequence(const string& query, string& encodedQuery);
\r
45 // -----------------------------------------------------
\r
46 // BamWriter implementation
\r
47 // -----------------------------------------------------
\r
50 BamWriter::BamWriter(void) {
\r
51 d = new BamWriterPrivate;
\r
55 BamWriter::~BamWriter(void) {
\r
60 // closes the alignment archive
\r
61 void BamWriter::Close(void) {
\r
65 // opens the alignment archive
\r
66 void BamWriter::Open(const string& filename, const string& samHeader, const RefVector& referenceSequences) {
\r
67 d->Open(filename, samHeader, referenceSequences);
\r
70 // saves the alignment to the alignment archive
\r
71 void BamWriter::SaveAlignment(const BamAlignment& al) {
\r
72 d->SaveAlignment(al);
\r
75 // -----------------------------------------------------
\r
76 // BamWriterPrivate implementation
\r
77 // -----------------------------------------------------
\r
79 // closes the alignment archive
\r
80 void BamWriter::BamWriterPrivate::Close(void) {
\r
84 // creates a cigar string from the supplied alignment
\r
85 void BamWriter::BamWriterPrivate::CreatePackedCigar(const vector<CigarOp>& cigarOperations, string& packedCigar) {
\r
88 const unsigned int numCigarOperations = cigarOperations.size();
\r
89 packedCigar.resize(numCigarOperations * BT_SIZEOF_INT);
\r
91 // pack the cigar data into the string
\r
92 unsigned int* pPackedCigar = (unsigned int*)packedCigar.data();
\r
94 unsigned int cigarOp;
\r
95 vector<CigarOp>::const_iterator coIter;
\r
96 for(coIter = cigarOperations.begin(); coIter != cigarOperations.end(); ++coIter) {
\r
98 switch(coIter->Type) {
\r
100 cigarOp = BAM_CMATCH;
\r
103 cigarOp = BAM_CINS;
\r
106 cigarOp = BAM_CDEL;
\r
109 cigarOp = BAM_CREF_SKIP;
\r
112 cigarOp = BAM_CSOFT_CLIP;
\r
115 cigarOp = BAM_CHARD_CLIP;
\r
118 cigarOp = BAM_CPAD;
\r
121 printf("ERROR: Unknown cigar operation found: %c\n", coIter->Type);
\r
125 *pPackedCigar = coIter->Length << BAM_CIGAR_SHIFT | cigarOp;
\r
130 // encodes the supplied query sequence into 4-bit notation
\r
131 void BamWriter::BamWriterPrivate::EncodeQuerySequence(const string& query, string& encodedQuery) {
\r
133 // prepare the encoded query string
\r
134 const unsigned int queryLen = query.size();
\r
135 const unsigned int encodedQueryLen = (unsigned int)((queryLen / 2.0) + 0.5);
\r
136 encodedQuery.resize(encodedQueryLen);
\r
137 char* pEncodedQuery = (char*)encodedQuery.data();
\r
138 const char* pQuery = (const char*)query.data();
\r
140 unsigned char nucleotideCode;
\r
141 bool useHighWord = true;
\r
148 nucleotideCode = 0;
\r
152 nucleotideCode = 1;
\r
156 nucleotideCode = 2;
\r
160 nucleotideCode = 4;
\r
164 nucleotideCode = 8;
\r
168 nucleotideCode = 15;
\r
172 printf("ERROR: Only the following bases are supported in the BAM format: {=, A, C, G, T, N}. Found [%c]\n", *pQuery);
\r
176 // pack the nucleotide code
\r
178 *pEncodedQuery = nucleotideCode << 4;
\r
179 useHighWord = false;
\r
181 *pEncodedQuery |= nucleotideCode;
\r
183 useHighWord = true;
\r
186 // increment the query position
\r
191 // opens the alignment archive
\r
192 void BamWriter::BamWriterPrivate::Open(const string& filename, const string& samHeader, const RefVector& referenceSequences) {
\r
194 // open the BGZF file for writing
\r
195 mBGZF.Open(filename, "wb");
\r
197 // ================
\r
198 // write the header
\r
199 // ================
\r
201 // write the BAM signature
\r
202 const unsigned char SIGNATURE_LENGTH = 4;
\r
203 const char* BAM_SIGNATURE = "BAM\1";
\r
204 mBGZF.Write(BAM_SIGNATURE, SIGNATURE_LENGTH);
\r
206 // write the SAM header text length
\r
207 uint32_t samHeaderLen = samHeader.size();
\r
208 if (IsBigEndian) SwapEndian_32(samHeaderLen);
\r
209 mBGZF.Write((char*)&samHeaderLen, BT_SIZEOF_INT);
\r
211 // write the SAM header text
\r
212 if(samHeaderLen > 0)
\r
213 mBGZF.Write(samHeader.data(), samHeaderLen);
\r
215 // write the number of reference sequences
\r
216 uint32_t numReferenceSequences = referenceSequences.size();
\r
217 if (IsBigEndian) SwapEndian_32(numReferenceSequences);
\r
218 mBGZF.Write((char*)&numReferenceSequences, BT_SIZEOF_INT);
\r
220 // =============================
\r
221 // write the sequence dictionary
\r
222 // =============================
\r
224 RefVector::const_iterator rsIter;
\r
225 for(rsIter = referenceSequences.begin(); rsIter != referenceSequences.end(); rsIter++) {
\r
227 // write the reference sequence name length
\r
228 uint32_t referenceSequenceNameLen = rsIter->RefName.size() + 1;
\r
229 if (IsBigEndian) SwapEndian_32(referenceSequenceNameLen);
\r
230 mBGZF.Write((char*)&referenceSequenceNameLen, BT_SIZEOF_INT);
\r
232 // write the reference sequence name
\r
233 mBGZF.Write(rsIter->RefName.c_str(), referenceSequenceNameLen);
\r
235 // write the reference sequence length
\r
236 int32_t referenceLength = rsIter->RefLength;
\r
237 if (IsBigEndian) SwapEndian_32(referenceLength);
\r
238 mBGZF.Write((char*)&referenceLength, BT_SIZEOF_INT);
\r
242 // saves the alignment to the alignment archive
\r
243 void BamWriter::BamWriterPrivate::SaveAlignment(const BamAlignment& al) {
\r
245 // assign the BAM core data
\r
246 uint32_t buffer[8];
\r
247 buffer[0] = al.RefID;
\r
248 buffer[1] = al.Position;
\r
249 buffer[2] = (al.Bin << 16) | (al.MapQuality << 8) | al.SupportData.QueryNameLength;
\r
250 buffer[3] = (al.AlignmentFlag << 16) | al.SupportData.NumCigarOperations;
\r
251 buffer[4] = al.SupportData.QuerySequenceLength;
\r
252 buffer[5] = al.MateRefID;
\r
253 buffer[6] = al.MatePosition;
\r
254 buffer[7] = al.InsertSize;
\r
256 // write the block size
\r
257 unsigned int blockSize = al.SupportData.BlockLength;
\r
258 if (IsBigEndian) SwapEndian_32(blockSize);
\r
259 mBGZF.Write((char*)&blockSize, BT_SIZEOF_INT);
\r
261 // swap BAM core endian-ness, if necessary
\r
262 if ( IsBigEndian ) {
\r
263 for ( int i = 0; i < 8; ++i )
\r
264 SwapEndian_32(buffer[i]);
\r
267 // write the BAM core
\r
268 mBGZF.Write((char*)&buffer, BAM_CORE_SIZE);
\r
270 // if support data, not parsed out (resulted from BamReader::GetNextAlignmentCore()
\r
271 // write the raw char data
\r
272 if ( !al.SupportData.IsParsed )
\r
273 mBGZF.Write((char*)al.SupportData.AllCharData.data(), al.SupportData.BlockLength-BAM_CORE_SIZE);
\r
275 // re-pack (as needed) & write the parsed char data
\r
279 const unsigned int nameLen = al.Name.size() + 1;
\r
280 const unsigned int queryLen = al.QueryBases.size();
\r
281 const unsigned int tagDataLength = al.TagData.size();
\r
283 // create our packed cigar string
\r
284 string packedCigar;
\r
285 CreatePackedCigar(al.CigarData, packedCigar);
\r
286 const unsigned int packedCigarLen = packedCigar.size();
\r
288 // encode the query
\r
289 string encodedQuery;
\r
290 EncodeQuerySequence(al.QueryBases, encodedQuery);
\r
291 const unsigned int encodedQueryLen = encodedQuery.size();
\r
293 // write the query name
\r
294 mBGZF.Write(al.Name.c_str(), nameLen);
\r
296 // write the packed cigar
\r
297 if ( IsBigEndian ) {
\r
299 char* cigarData = (char*)calloc(sizeof(char), packedCigarLen);
\r
300 memcpy(cigarData, packedCigar.data(), packedCigarLen);
\r
302 for (unsigned int i = 0; i < packedCigarLen; ++i) {
\r
304 SwapEndian_32p(&cigarData[i]);
\r
307 mBGZF.Write(cigarData, packedCigarLen);
\r
311 mBGZF.Write(packedCigar.data(), packedCigarLen);
\r
313 // write the encoded query sequence
\r
314 mBGZF.Write(encodedQuery.data(), encodedQueryLen);
\r
316 // write the base qualities
\r
317 string baseQualities(al.Qualities);
\r
318 char* pBaseQualities = (char*)al.Qualities.data();
\r
319 for(unsigned int i = 0; i < queryLen; i++) {
\r
320 pBaseQualities[i] -= 33;
\r
322 mBGZF.Write(pBaseQualities, queryLen);
\r
324 // write the read group tag
\r
325 if ( IsBigEndian ) {
\r
327 char* tagData = (char*)calloc(sizeof(char), tagDataLength);
\r
328 memcpy(tagData, al.TagData.data(), tagDataLength);
\r
331 while ( (unsigned int)i < tagDataLength ) {
\r
333 i += 2; // skip tag type (e.g. "RG", "NM", etc)
\r
334 uint8_t type = toupper(tagData[i]); // lower & upper case letters have same meaning
\r
335 ++i; // skip value type
\r
345 SwapEndian_16p(&tagData[i]);
\r
346 i+=2; // sizeof(uint16_t)
\r
351 SwapEndian_32p(&tagData[i]);
\r
352 i+=4; // sizeof(uint32_t)
\r
356 SwapEndian_64p(&tagData[i]);
\r
357 i+=8; // sizeof(uint64_t)
\r
362 while (tagData[i]) { ++i; }
\r
363 ++i; // increment one more for null terminator
\r
367 printf("ERROR: Invalid tag value type\n"); // shouldn't get here
\r
373 mBGZF.Write(tagData, tagDataLength);
\r
377 mBGZF.Write(al.TagData.data(), tagDataLength);
\r