1 // ***************************************************************************
2 // bamtools_convert.cpp (c) 2010 Derek Barnett, Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // All rights reserved.
5 // ---------------------------------------------------------------------------
6 // Last modified: 9 July 2010
7 // ---------------------------------------------------------------------------
8 // Converts between BAM and a number of other formats
9 // ***************************************************************************
17 #include "bamtools_convert.h"
18 #include "bamtools_options.h"
19 #include "bamtools_pileup.h"
20 #include "bamtools_utilities.h"
22 #include "BamReader.h"
23 #include "BamMultiReader.h"
26 using namespace BamTools;
31 static const string FORMAT_BED = "bed";
32 static const string FORMAT_BEDGRAPH = "bedgraph";
33 static const string FORMAT_FASTA = "fasta";
34 static const string FORMAT_FASTQ = "fastq";
35 static const string FORMAT_JSON = "json";
36 static const string FORMAT_SAM = "sam";
37 static const string FORMAT_PILEUP = "pileup";
38 static const string FORMAT_WIGGLE = "wig";
41 static const unsigned int FASTA_LINE_MAX = 50;
43 } // namespace BamTools
45 struct ConvertTool::ConvertToolPrivate {
49 ConvertToolPrivate(ConvertTool::ConvertSettings* settings);
50 ~ConvertToolPrivate(void);
58 void PrintBed(const BamAlignment& a);
59 void PrintBedGraph(const BamAlignment& a);
60 void PrintFasta(const BamAlignment& a);
61 void PrintFastq(const BamAlignment& a);
62 void PrintJson(const BamAlignment& a);
63 void PrintSam(const BamAlignment& a);
64 void PrintWiggle(const BamAlignment& a);
68 ConvertTool::ConvertSettings* m_settings;
69 RefVector m_references;
73 // ---------------------------------------------
74 // ConvertSettings implementation
76 struct ConvertTool::ConvertSettings {
79 bool HasInputFilenames;
80 bool HasOutputFilename;
85 bool HasFastaFilename;
86 bool IsPrintingPileupMapQualities;
89 vector<string> InputFiles;
90 string OutputFilename;
99 : HasInputFilenames(false)
100 , HasOutputFilename(false)
103 , HasFastaFilename(false)
104 , IsPrintingPileupMapQualities(false)
105 , OutputFilename(Options::StandardOut())
109 // ---------------------------------------------
110 // ConvertTool implementation
112 ConvertTool::ConvertTool(void)
114 , m_settings(new ConvertSettings)
117 // set program details
118 Options::SetProgramInfo("bamtools convert", "converts between BAM and a number of other formats", "-in <filename> -out <filename> -format <FORMAT>");
121 OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
122 Options::AddValueOption("-in", "BAM filename", "the input BAM file(s)", "", m_settings->HasInputFilenames, m_settings->InputFiles, IO_Opts, Options::StandardIn());
123 Options::AddValueOption("-out", "BAM filename", "the output BAM file", "", m_settings->HasOutputFilename, m_settings->OutputFilename, IO_Opts, Options::StandardOut());
124 Options::AddValueOption("-format", "FORMAT", "the output file format - see README for recognized formats", "", m_settings->HasFormat, m_settings->Format, IO_Opts);
126 OptionGroup* FilterOpts = Options::CreateOptionGroup("Filters");
127 Options::AddValueOption("-region", "REGION", "genomic region. Index file is recommended for better performance, and is read automatically if it exists as <filename>.bai. See \'bamtools help index\' for more details on creating one", "", m_settings->HasRegion, m_settings->Region, FilterOpts);
129 OptionGroup* PileupOpts = Options::CreateOptionGroup("Pileup Options");
130 Options::AddValueOption("-fasta", "FASTA filename", "FASTA reference file", "", m_settings->HasFastaFilename, m_settings->FastaFilename, PileupOpts, "");
131 Options::AddOption("-mapqual", "print the mapping qualities", m_settings->IsPrintingPileupMapQualities, PileupOpts);
134 ConvertTool::~ConvertTool(void) {
142 int ConvertTool::Help(void) {
143 Options::DisplayHelp();
147 int ConvertTool::Run(int argc, char* argv[]) {
149 // parse command line arguments
150 Options::Parse(argc, argv, 1);
152 // run internal ConvertTool implementation, return success/fail
153 m_impl = new ConvertToolPrivate(m_settings);
161 // ---------------------------------------------
162 // ConvertToolPrivate implementation
164 ConvertTool::ConvertToolPrivate::ConvertToolPrivate(ConvertTool::ConvertSettings* settings)
165 : m_settings(settings)
166 , m_out(cout.rdbuf()) // default output to cout
169 ConvertTool::ConvertToolPrivate::~ConvertToolPrivate(void) { }
171 bool ConvertTool::ConvertToolPrivate::Run(void) {
173 bool convertedOk = true;
175 // ------------------------------------
176 // initialize conversion input/output
178 // set to default input if none provided
179 if ( !m_settings->HasInputFilenames )
180 m_settings->InputFiles.push_back(Options::StandardIn());
183 BamMultiReader reader;
184 reader.Open(m_settings->InputFiles);
185 m_references = reader.GetReferenceData();
187 // set region if specified
189 if ( m_settings->HasRegion ) {
190 if ( Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
191 if ( !reader.SetRegion(region) )
192 cerr << "Could not set BamReader region to REGION: " << m_settings->Region << endl;
196 // if output file given
198 if ( m_settings->HasOutputFilename ) {
200 // open output file stream
201 outFile.open(m_settings->OutputFilename.c_str());
203 cerr << "Could not open " << m_settings->OutputFilename << " for output" << endl;
207 // set m_out to file's streambuf
208 m_out.rdbuf(outFile.rdbuf());
211 // ------------------------
212 // pileup is special case
213 if ( m_settings->Format == FORMAT_PILEUP ) {
215 // initialize pileup input/output
216 Pileup pileup(&reader, &m_out);
218 // ---------------------------
219 // configure pileup settings
221 if ( m_settings->HasRegion )
222 pileup.SetRegion(region);
224 if ( m_settings->HasFastaFilename )
225 pileup.SetFastaFilename(m_settings->FastaFilename);
227 pileup.SetIsPrintingMapQualities( m_settings->IsPrintingPileupMapQualities );
230 convertedOk = pileup.Run();
233 // -------------------------------------
234 // else determine 'simpler' format type
237 bool formatError = false;
238 void (BamTools::ConvertTool::ConvertToolPrivate::*pFunction)(const BamAlignment&) = 0;
239 if ( m_settings->Format == FORMAT_BED ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintBed;
240 else if ( m_settings->Format == FORMAT_BEDGRAPH ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintBedGraph;
241 else if ( m_settings->Format == FORMAT_FASTA ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintFasta;
242 else if ( m_settings->Format == FORMAT_FASTQ ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintFastq;
243 else if ( m_settings->Format == FORMAT_JSON ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintJson;
244 else if ( m_settings->Format == FORMAT_SAM ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintSam;
245 else if ( m_settings->Format == FORMAT_WIGGLE ) pFunction = &BamTools::ConvertTool::ConvertToolPrivate::PrintWiggle;
247 cerr << "Unrecognized format: " << m_settings->Format << endl;
248 cerr << "Please see help|README (?) for details on supported formats " << endl;
253 // ------------------------
255 if ( !formatError ) {
257 while ( reader.GetNextAlignment(a) ) {
258 (this->*pFunction)(a);
263 // ------------------------
266 if ( m_settings->HasOutputFilename ) outFile.close();
270 // ----------------------------------------------------------
271 // Conversion/output methods
272 // ----------------------------------------------------------
274 void ConvertTool::ConvertToolPrivate::PrintBed(const BamAlignment& a) {
276 // tab-delimited, 0-based half-open
277 // (e.g. a 50-base read aligned to pos 10 could have BED coordinates (10, 60) instead of BAM coordinates (10, 59) )
278 // <chromName> <chromStart> <chromEnd> <readName> <score> <strand>
280 m_out << m_references.at(a.RefID).RefName << "\t"
281 << a.Position << "\t"
282 << a.GetEndPosition() + 1 << "\t"
284 << a.MapQuality << "\t"
285 << (a.IsReverseStrand() ? "-" : "+") << endl;
288 void ConvertTool::ConvertToolPrivate::PrintBedGraph(const BamAlignment& a) {
292 // print BamAlignment in FASTA format
293 // N.B. - uses QueryBases NOT AlignedBases
294 void ConvertTool::ConvertToolPrivate::PrintFasta(const BamAlignment& a) {
296 // >BamAlignment.Name
297 // BamAlignment.QueryBases (up to FASTA_LINE_MAX bases per line)
301 m_out << "> " << a.Name << endl;
303 // if sequence fits on single line
304 if ( a.QueryBases.length() <= FASTA_LINE_MAX )
305 m_out << a.QueryBases << endl;
307 // else split over multiple lines
311 size_t seqLength = a.QueryBases.length();
313 // write subsequences to each line
314 while ( position < (seqLength - FASTA_LINE_MAX) ) {
315 m_out << a.QueryBases.substr(position, FASTA_LINE_MAX) << endl;
316 position += FASTA_LINE_MAX;
319 // write final subsequence
320 m_out << a.QueryBases.substr(position) << endl;
324 // print BamAlignment in FASTQ format
325 // N.B. - uses QueryBases NOT AlignedBases
326 void ConvertTool::ConvertToolPrivate::PrintFastq(const BamAlignment& a) {
328 // @BamAlignment.Name
329 // BamAlignment.QueryBases
331 // BamAlignment.Qualities
333 m_out << "@" << a.Name << endl
334 << a.QueryBases << endl
336 << a.Qualities << endl;
339 // print BamAlignment in JSON format
340 void ConvertTool::ConvertToolPrivate::PrintJson(const BamAlignment& a) {
342 // write name & alignment flag
343 m_out << "{\"name\":\"" << a.Name << "\",\"alignmentFlag\":\"" << a.AlignmentFlag << "\",";
345 // write reference name
346 if ( (a.RefID >= 0) && (a.RefID < (int)m_references.size()) )
347 m_out << "\"reference\":\"" << m_references[a.RefID].RefName << "\",";
349 // write position & map quality
350 m_out << "\"position\":" << a.Position+1 << ",\"mapQuality\":" << a.MapQuality << ",";
353 const vector<CigarOp>& cigarData = a.CigarData;
354 if ( !cigarData.empty() ) {
355 m_out << "\"cigar\":[";
356 vector<CigarOp>::const_iterator cigarBegin = cigarData.begin();
357 vector<CigarOp>::const_iterator cigarIter = cigarBegin;
358 vector<CigarOp>::const_iterator cigarEnd = cigarData.end();
359 for ( ; cigarIter != cigarEnd; ++cigarIter ) {
360 const CigarOp& op = (*cigarIter);
361 if (cigarIter != cigarBegin) m_out << ",";
362 m_out << "\"" << op.Length << op.Type << "\"";
367 // write mate reference name, mate position, & insert size
368 if ( a.IsPaired() && (a.MateRefID >= 0) && (a.MateRefID < (int)m_references.size()) ) {
369 m_out << "\"mate\":{"
370 << "\"reference\":\"" << m_references[a.MateRefID].RefName << "\","
371 << "\"position\":" << a.MatePosition+1
372 << ",\"insertSize\":" << a.InsertSize << "},";
376 if ( !a.QueryBases.empty() )
377 m_out << "\"queryBases\":\"" << a.QueryBases << "\",";
380 if ( !a.Qualities.empty() )
381 m_out << "\"qualities\":\"" << a.Qualities << "\",";
384 const char* tagData = a.TagData.c_str();
385 const size_t tagDataLength = a.TagData.length();
387 if (index < tagDataLength) {
389 m_out << "\"tags\":{";
391 while ( index < tagDataLength ) {
397 m_out << "\"" << a.TagData.substr(index, 2) << "\":";
401 char type = a.TagData.at(index);
406 m_out << "\"" << tagData[index] << "\"";
411 m_out << (int)tagData[index];
416 m_out << (int)tagData[index];
421 m_out << BgzfData::UnpackUnsignedShort(&tagData[index]);
426 m_out << BgzfData::UnpackSignedShort(&tagData[index]);
431 m_out << BgzfData::UnpackUnsignedInt(&tagData[index]);
436 m_out << BgzfData::UnpackSignedInt(&tagData[index]);
441 m_out << BgzfData::UnpackFloat(&tagData[index]);
446 m_out << BgzfData::UnpackDouble(&tagData[index]);
453 while (tagData[index]) {
454 m_out << tagData[index];
462 if ( tagData[index] == '\0')
469 m_out << "}" << endl;
473 // print BamAlignment in SAM format
474 void ConvertTool::ConvertToolPrivate::PrintSam(const BamAlignment& a) {
477 // <QNAME> <FLAG> <RNAME> <POS> <MAPQ> <CIGAR> <MRNM> <MPOS> <ISIZE> <SEQ> <QUAL> [ <TAG>:<VTYPE>:<VALUE> [...] ]
479 // write name & alignment flag
480 m_out << a.Name << "\t" << a.AlignmentFlag << "\t";
482 // write reference name
483 if ( (a.RefID >= 0) && (a.RefID < (int)m_references.size()) )
484 m_out << m_references[a.RefID].RefName << "\t";
488 // write position & map quality
489 m_out << a.Position+1 << "\t" << a.MapQuality << "\t";
492 const vector<CigarOp>& cigarData = a.CigarData;
493 if ( cigarData.empty() ) m_out << "*\t";
495 vector<CigarOp>::const_iterator cigarIter = cigarData.begin();
496 vector<CigarOp>::const_iterator cigarEnd = cigarData.end();
497 for ( ; cigarIter != cigarEnd; ++cigarIter ) {
498 const CigarOp& op = (*cigarIter);
499 m_out << op.Length << op.Type;
504 // write mate reference name, mate position, & insert size
505 if ( a.IsPaired() && (a.MateRefID >= 0) && (a.MateRefID < (int)m_references.size()) ) {
506 if ( a.MateRefID == a.RefID ) m_out << "=\t";
507 else m_out << m_references[a.MateRefID].RefName << "\t";
508 m_out << a.MatePosition+1 << "\t" << a.InsertSize << "\t";
510 else m_out << "*\t0\t0\t";
513 if ( a.QueryBases.empty() ) m_out << "*\t";
514 else m_out << a.QueryBases << "\t";
517 if ( a.Qualities.empty() ) m_out << "*";
518 else m_out << a.Qualities;
521 const char* tagData = a.TagData.c_str();
522 const size_t tagDataLength = a.TagData.length();
525 while ( index < tagDataLength ) {
528 m_out << "\t" << a.TagData.substr(index, 2) << ":";
532 char type = a.TagData.at(index);
537 m_out << "A:" << tagData[index];
542 m_out << "i:" << (int)tagData[index];
547 m_out << "i:" << (int)tagData[index];
552 m_out << "i:" << BgzfData::UnpackUnsignedShort(&tagData[index]);
557 m_out << "i:" << BgzfData::UnpackSignedShort(&tagData[index]);
562 m_out << "i:" << BgzfData::UnpackUnsignedInt(&tagData[index]);
567 m_out << "i:" << BgzfData::UnpackSignedInt(&tagData[index]);
572 m_out << "f:" << BgzfData::UnpackFloat(&tagData[index]);
577 m_out << "d:" << BgzfData::UnpackDouble(&tagData[index]);
583 m_out << type << ":";
584 while (tagData[index]) {
585 m_out << tagData[index];
592 if ( tagData[index] == '\0')
599 void ConvertTool::ConvertToolPrivate::PrintWiggle(const BamAlignment& a) {