1 // ***************************************************************************
2 // bamtools_sort.cpp (c) 2010 Derek Barnett, Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 3 October 2011 (DB)
6 // ---------------------------------------------------------------------------
7 // Sorts an input BAM file
8 // ***************************************************************************
10 #include "bamtools_sort.h"
12 #include <api/SamConstants.h>
13 #include <api/BamMultiReader.h>
14 #include <api/BamWriter.h>
15 #include <utils/bamtools_options.h>
16 using namespace BamTools;
30 // ** These defaults should be tweaked & 'optimized' per testing ** //
32 // I say 'optimized' because each system will naturally perform
33 // differently. We will attempt to determine a sensible
34 // compromise that should perform well on average.
35 const unsigned int SORT_DEFAULT_MAX_BUFFER_COUNT = 500000; // max numberOfAlignments for buffer
36 const unsigned int SORT_DEFAULT_MAX_BUFFER_MEMORY = 1024; // Mb
38 // -----------------------------------
39 // comparison objects (for sorting)
41 struct SortLessThanPosition {
42 bool operator() (const BamAlignment& lhs, const BamAlignment& rhs) {
44 // force unmapped alignments to end
45 if ( lhs.RefID == -1 ) return false;
46 if ( rhs.RefID == -1 ) return true;
48 // sort first on RefID, then by Position
49 if ( lhs.RefID != rhs.RefID )
50 return lhs.RefID < rhs.RefID;
52 return lhs.Position < rhs.Position;
56 struct SortLessThanName {
57 bool operator() (const BamAlignment& lhs, const BamAlignment& rhs) {
58 return lhs.Name < rhs.Name;
62 } // namespace BamTools
64 // ---------------------------------------------
65 // SortSettings implementation
67 struct SortTool::SortSettings {
70 bool HasInputBamFilename;
71 bool HasMaxBufferCount;
72 bool HasMaxBufferMemory;
73 bool HasOutputBamFilename;
77 string InputBamFilename;
78 string OutputBamFilename;
81 unsigned int MaxBufferCount;
82 unsigned int MaxBufferMemory;
86 : HasInputBamFilename(false)
87 , HasMaxBufferCount(false)
88 , HasMaxBufferMemory(false)
89 , HasOutputBamFilename(false)
90 , IsSortingByName(false)
91 , InputBamFilename(Options::StandardIn())
92 , OutputBamFilename(Options::StandardOut())
93 , MaxBufferCount(SORT_DEFAULT_MAX_BUFFER_COUNT)
94 , MaxBufferMemory(SORT_DEFAULT_MAX_BUFFER_MEMORY)
98 // ---------------------------------------------
99 // SortToolPrivate implementation
101 class SortTool::SortToolPrivate {
105 SortToolPrivate(SortTool::SortSettings* settings);
106 ~SortToolPrivate(void) { }
108 // 'public' interface
114 bool CreateSortedTempFile(vector<BamAlignment>& buffer);
115 bool GenerateSortedRuns(void);
116 bool MergeSortedRuns(void);
117 bool WriteTempFile(const vector<BamAlignment>& buffer, const string& tempFilename);
118 void SortBuffer(vector<BamAlignment>& buffer);
122 SortTool::SortSettings* m_settings;
123 string m_tempFilenameStub;
126 RefVector m_references;
127 vector<string> m_tempFilenames;
131 SortTool::SortToolPrivate::SortToolPrivate(SortTool::SortSettings* settings)
132 : m_settings(settings)
135 // set filename stub depending on inputfile path
136 // that way multiple sort runs don't trip on each other's temp files
138 size_t extensionFound = m_settings->InputBamFilename.find(".bam");
139 if (extensionFound != string::npos )
140 m_tempFilenameStub = m_settings->InputBamFilename.substr(0,extensionFound);
141 m_tempFilenameStub.append(".sort.temp.");
145 // generates mutiple sorted temp BAM files from single unsorted BAM file
146 bool SortTool::SortToolPrivate::GenerateSortedRuns(void) {
148 // open input BAM file
150 if ( !reader.Open(m_settings->InputBamFilename) ) {
151 cerr << "bamtools sort ERROR: could not open " << m_settings->InputBamFilename
152 << " for reading... Aborting." << endl;
156 // get basic data that will be shared by all temp/output files
157 SamHeader header = reader.GetHeader();
158 header.SortOrder = ( m_settings->IsSortingByName
159 ? Constants::SAM_HD_SORTORDER_QUERYNAME
160 : Constants::SAM_HD_SORTORDER_COORDINATE );
161 m_headerText = header.ToString();
162 m_references = reader.GetReferenceData();
164 // set up alignments buffer
166 vector<BamAlignment> buffer;
167 buffer.reserve( (size_t)(m_settings->MaxBufferCount*1.1) );
168 bool bufferFull = false;
170 // if sorting by name, we need to generate full char data
171 // so can't use GetNextAlignmentCore()
172 if ( m_settings->IsSortingByName ) {
174 // iterate through file
175 while ( reader.GetNextAlignment(al)) {
177 // check buffer's usage
178 bufferFull = ( buffer.size() >= m_settings->MaxBufferCount );
180 // store alignments until buffer is "full"
182 buffer.push_back(al);
184 // if buffer is "full"
187 // push any unmapped reads into buffer,
188 // don't want to split these into a separate temp file
189 if ( !al.IsMapped() )
190 buffer.push_back(al);
192 // "al" is mapped, so create a sorted temp file with current buffer contents
193 // then push "al" into fresh buffer
195 CreateSortedTempFile(buffer);
196 buffer.push_back(al);
202 // sorting by position, can take advantage of GNACore() speedup
205 // iterate through file
206 while ( reader.GetNextAlignmentCore(al) ) {
208 // check buffer's usage
209 bufferFull = ( buffer.size() >= m_settings->MaxBufferCount );
211 // store alignments until buffer is "full"
213 buffer.push_back(al);
215 // if buffer is "full"
218 // push any unmapped reads into buffer,
219 // don't want to split these into a separate temp file
220 if ( !al.IsMapped() )
221 buffer.push_back(al);
223 // "al" is mapped, so create a sorted temp file with current buffer contents
224 // then push "al" into fresh buffer
226 CreateSortedTempFile(buffer);
227 buffer.push_back(al);
233 // handle any leftover buffer contents
234 if ( !buffer.empty() )
235 CreateSortedTempFile(buffer);
237 // close reader & return success
242 bool SortTool::SortToolPrivate::CreateSortedTempFile(vector<BamAlignment>& buffer) {
247 // write sorted contents to temp file, store success/fail
248 stringstream tempStr;
249 tempStr << m_tempFilenameStub << m_numberOfRuns;
250 bool success = WriteTempFile( buffer, tempStr.str() );
252 // save temp filename for merging later
253 m_tempFilenames.push_back(tempStr.str());
255 // clear buffer contents & update run counter
259 // return success/fail of writing to temp file
260 // TODO: a failure returned here is not actually caught and handled anywhere
264 // merges sorted temp BAM files into single sorted output BAM file
265 bool SortTool::SortToolPrivate::MergeSortedRuns(void) {
267 // open up multi reader for all of our temp files
268 // this might get broken up if we do a multi-pass system later ??
269 BamMultiReader multiReader;
270 if ( !multiReader.Open(m_tempFilenames) ) {
271 cerr << "bamtools sort ERROR: could not open BamMultiReader for merging temp files... Aborting."
276 // open writer for our completely sorted output BAM file
277 BamWriter mergedWriter;
278 if ( !mergedWriter.Open(m_settings->OutputBamFilename, m_headerText, m_references) ) {
279 cerr << "bamtools sort ERROR: could not open " << m_settings->OutputBamFilename
280 << " for writing... Aborting." << endl;
285 // while data available in temp files
287 while ( multiReader.GetNextAlignmentCore(al) )
288 mergedWriter.SaveAlignment(al);
292 mergedWriter.Close();
294 // delete all temp files
295 vector<string>::const_iterator tempIter = m_tempFilenames.begin();
296 vector<string>::const_iterator tempEnd = m_tempFilenames.end();
297 for ( ; tempIter != tempEnd; ++tempIter ) {
298 const string& tempFilename = (*tempIter);
299 remove(tempFilename.c_str());
306 bool SortTool::SortToolPrivate::Run(void) {
308 // this does a single pass, chunking up the input file into smaller sorted temp files,
309 // then write out using BamMultiReader to handle merging
311 if ( GenerateSortedRuns() )
312 return MergeSortedRuns();
317 void SortTool::SortToolPrivate::SortBuffer(vector<BamAlignment>& buffer) {
319 // ** add further custom sort options later ?? **
321 // sort buffer by desired method
322 if ( m_settings->IsSortingByName )
323 std::stable_sort ( buffer.begin(), buffer.end(), SortLessThanName() );
325 std::stable_sort ( buffer.begin(), buffer.end(), SortLessThanPosition() );
328 bool SortTool::SortToolPrivate::WriteTempFile(const vector<BamAlignment>& buffer,
329 const string& tempFilename)
331 // open temp file for writing
332 BamWriter tempWriter;
333 if ( !tempWriter.Open(tempFilename, m_headerText, m_references) ) {
334 cerr << "bamtools sort ERROR: could not open " << tempFilename
335 << " for writing." << endl;
340 vector<BamAlignment>::const_iterator buffIter = buffer.begin();
341 vector<BamAlignment>::const_iterator buffEnd = buffer.end();
342 for ( ; buffIter != buffEnd; ++buffIter ) {
343 const BamAlignment& al = (*buffIter);
344 tempWriter.SaveAlignment(al);
347 // close temp file & return success
352 // ---------------------------------------------
353 // SortTool implementation
355 SortTool::SortTool(void)
357 , m_settings(new SortSettings)
360 // set program details
361 Options::SetProgramInfo("bamtools sort", "sorts a BAM file", "[-in <filename>] [-out <filename>] [sortOptions]");
364 OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
365 Options::AddValueOption("-in", "BAM filename", "the input BAM file", "",
366 m_settings->HasInputBamFilename, m_settings->InputBamFilename,
367 IO_Opts, Options::StandardIn());
368 Options::AddValueOption("-out", "BAM filename", "the output BAM file", "",
369 m_settings->HasOutputBamFilename, m_settings->OutputBamFilename,
370 IO_Opts, Options::StandardOut());
372 OptionGroup* SortOpts = Options::CreateOptionGroup("Sorting Methods");
373 Options::AddOption("-byname", "sort by alignment name", m_settings->IsSortingByName, SortOpts);
375 OptionGroup* MemOpts = Options::CreateOptionGroup("Memory Settings");
376 Options::AddValueOption("-n", "count", "max number of alignments per tempfile", "",
377 m_settings->HasMaxBufferCount, m_settings->MaxBufferCount,
378 MemOpts, SORT_DEFAULT_MAX_BUFFER_COUNT);
379 Options::AddValueOption("-mem", "Mb", "max memory to use", "",
380 m_settings->HasMaxBufferMemory, m_settings->MaxBufferMemory,
381 MemOpts, SORT_DEFAULT_MAX_BUFFER_MEMORY);
384 SortTool::~SortTool(void) {
393 int SortTool::Help(void) {
394 Options::DisplayHelp();
398 int SortTool::Run(int argc, char* argv[]) {
400 // parse command line arguments
401 Options::Parse(argc, argv, 1);
403 // initialize SortTool with settings
404 m_impl = new SortToolPrivate(m_settings);
406 // run SortTool, return success/fail