1 // ***************************************************************************
2 // bamtools_count.cpp (c) 2010 Derek Barnett, Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // All rights reserved.
5 // ---------------------------------------------------------------------------
6 // Last modified: 2 June 2010
7 // ---------------------------------------------------------------------------
8 // Prints alignment count for BAM file
10 // ** Expand to multiple??
12 // ***************************************************************************
19 #include "bamtools_count.h"
20 #include "bamtools_options.h"
21 #include "bamtools_utilities.h"
22 #include "BamReader.h"
25 using namespace BamTools;
27 // ---------------------------------------------
28 // CountSettings implementation
30 struct CountTool::CountSettings {
33 bool HasBamIndexFilename;
34 bool HasInputBamFilename;
38 string BamIndexFilename;
39 string InputBamFilename;
44 : HasBamIndexFilename(false)
45 , HasInputBamFilename(false)
47 , InputBamFilename(Options::StandardIn())
51 // ---------------------------------------------
52 // CountTool implementation
54 CountTool::CountTool(void)
56 , m_settings(new CountSettings)
58 // set program details
59 Options::SetProgramInfo("bamtools count", "prints alignment counts for a BAM file", "-in <filename> [-region <REGION> [-index <filename>]]");
62 OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
63 Options::AddValueOption("-in", "BAM filename", "the input BAM file", "", m_settings->HasInputBamFilename, m_settings->InputBamFilename, IO_Opts, Options::StandardIn());
64 Options::AddValueOption("-index", "BAM index filename", "the BAM index file", "", m_settings->HasBamIndexFilename, m_settings->BamIndexFilename, IO_Opts);
66 OptionGroup* FilterOpts = Options::CreateOptionGroup("Filters");
67 Options::AddValueOption("-region", "REGION", "genomic region. Index file is recommended for better performance. See \'bamtools help index\' for more details on creating one", "", m_settings->HasRegion, m_settings->Region, FilterOpts);
70 CountTool::~CountTool(void) {
75 int CountTool::Help(void) {
76 Options::DisplayHelp();
80 int CountTool::Run(int argc, char* argv[]) {
82 // parse command line arguments
83 Options::Parse(argc, argv, 1);
87 reader.Open(m_settings->InputBamFilename);
90 int alignmentCount(0);
92 // set up error handling
93 ostringstream errorStream("");
94 bool foundError(false);
96 // if no region specified, count entire file
97 if ( !m_settings->HasRegion ) {
99 while ( reader.GetNextAlignment(al) )
103 // more complicated - region specified
106 // parse region string for desired region
111 if ( Utilities::ParseRegionString(m_settings->Region, startChrom, startPos, stopChrom, stopPos) ) {
113 const RefVector references = reader.GetReferenceData();
115 // -------------------------------
116 // validate start ref & position
118 int startRefID = reader.GetReferenceID(startChrom);
120 // startRefID not found
121 if ( startRefID == (int)references.size() ) {
123 errorStream << "Start chrom: " << startChrom << " not found in BAM file." << endl;
126 // valid startRefID, check startPos
128 const RefData& reference = references.at(startRefID);
130 // startPos too large
131 if ( startPos > reference.RefLength ) {
133 errorStream << "Start pos: " << startPos << " is larger than expected." << endl;
137 // -------------------------------
138 // validate stop ref & position
140 int stopRefID = reader.GetReferenceID(stopChrom);
142 // skip if error already found
145 // stopRefID not found
146 if ( stopRefID == (int)references.size() ) {
148 errorStream << "Stop chrom: " << stopChrom << " not found in BAM file." << endl;
151 // valid stopRefID, check stopPos
153 const RefData& reference = references.at(stopRefID);
156 if ( stopPos > reference.RefLength ) {
158 errorStream << "Stop pos: " << stopPos << " is larger than expected." << endl;
161 // no stopPos specified, set to reference end
162 else if ( stopPos == -1 ) {
163 stopPos = reference.RefLength;
168 // -------------------------------
169 // if refs & positions valid, retrieve data
173 // has index, we can jump directly to
174 if ( m_settings->HasBamIndexFilename ) {
176 // this is kind of a hack...?
177 // re-open BamReader, this time with the index file
179 reader.Open(m_settings->InputBamFilename, m_settings->BamIndexFilename);
181 // attempt Jump(), catch error
182 if ( !reader.Jump(startRefID, startPos) ) {
184 errorStream << "Could not jump to desired REGION: " << m_settings->Region << endl;
190 // read through sequentially, until first overlapping read is found
192 bool alignmentFound(false);
193 while( reader.GetNextAlignment(al) ) {
194 if ( (al.RefID == startRefID ) && ( (al.Position + al.Length) >= startPos) ) {
195 alignmentFound = true;
200 // if overlapping alignment found (not EOF), increment counter
201 if ( alignmentFound) ++ alignmentCount;
204 // -----------------------------
205 // count alignments until stop hit
208 // while valid alignment AND
209 // ( either current ref is before stopRefID OR
210 // current ref stopRefID but we're before stopPos )
212 while ( reader.GetNextAlignment(al) && ((al.RefID < stopRefID ) || (al.RefID == stopRefID && al.Position <= stopPos)) )
218 // could not parse REGION string, set error
221 errorStream << "Could not parse desired REGION: " << m_settings->Region << endl;
222 errorStream << "Please see README for details on accepted REGION formats" << endl;
226 // print errors OR results
228 cerr << errorStream.str() << endl;
230 cout << alignmentCount << endl;
234 return (int)foundError;