]> git.donarmstrong.com Git - bamtools.git/blob - src/toolkit/bamtools_count.cpp
Minor formatting & commenting update
[bamtools.git] / src / toolkit / bamtools_count.cpp
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
9 //
10 // ** Expand to multiple?? 
11 //
12 // ***************************************************************************
13
14 #include <iostream>
15 #include <sstream>
16 #include <string>
17 #include <vector>
18
19 #include "bamtools_count.h"
20 #include "bamtools_options.h"
21 #include "bamtools_utilities.h"
22 #include "BamReader.h"
23 #include "BamMultiReader.h"
24
25 using namespace std;
26 using namespace BamTools;
27   
28 // ---------------------------------------------  
29 // CountSettings implementation
30
31 struct CountTool::CountSettings {
32
33     // flags
34     bool HasInput;
35     bool HasRegion;
36
37     // filenames
38     vector<string> InputFiles;
39     string Region;
40     
41     // constructor
42     CountSettings(void)
43         : HasInput(false)
44         , HasRegion(false)
45     { }  
46 }; 
47   
48 // ---------------------------------------------
49 // CountTool implementation
50
51 CountTool::CountTool(void) 
52     : AbstractTool()
53     , m_settings(new CountSettings)
54
55     // set program details
56     Options::SetProgramInfo("bamtools count", "prints alignment counts for a BAM file", "-in <filename> [-region <REGION>]");
57     
58     // set up options 
59     OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
60     Options::AddValueOption("-in",  "BAM filename", "the input BAM file(s)", "", m_settings->HasInput,  m_settings->InputFiles, IO_Opts);
61     //Options::AddValueOption("-index", "BAM index filename", "the BAM index file",  "", m_settings->HasBamIndexFilename, m_settings->BamIndexFilename, IO_Opts);
62     
63     OptionGroup* FilterOpts = Options::CreateOptionGroup("Filters");
64     Options::AddValueOption("-region", "REGION", "genomic region. Index file is recommended for better performance, and is read automatically if it exists as <filename>.bai or <filename>.bti. See \'bamtools help index\' for more details on creating one", "", m_settings->HasRegion, m_settings->Region, FilterOpts);
65 }
66
67 CountTool::~CountTool(void) { 
68     delete m_settings;
69     m_settings = 0;
70 }
71
72 int CountTool::Help(void) { 
73     Options::DisplayHelp();
74     return 0;
75
76
77 int CountTool::Run(int argc, char* argv[]) { 
78
79     // parse command line arguments
80     Options::Parse(argc, argv, 1);
81
82     if ( !m_settings->HasInput ) 
83         m_settings->InputFiles.push_back(Options::StandardIn());
84     
85     // open reader without index
86     BamMultiReader reader;
87     reader.Open(m_settings->InputFiles, false, true);
88
89     // alignment counter
90     int alignmentCount(0);
91     
92     // set up error handling
93     ostringstream errorStream("");
94     bool foundError(false);
95     
96     // if no region specified, count entire file 
97     if ( !m_settings->HasRegion ) {
98         BamAlignment al;
99         while ( reader.GetNextAlignmentCore(al) ) 
100             ++alignmentCount;
101     }
102     
103     // more complicated - region specified
104     else {
105         
106         BamRegion region;
107         if ( Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
108
109             // check if there are index files *.bai/*.bti corresponding to the input files
110             bool hasDefaultIndex   = false;
111             bool hasBamtoolsIndex  = false;
112             bool hasNoIndex        = false;
113             int defaultIndexCount   = 0;
114             int bamtoolsIndexCount = 0;
115             for (vector<string>::const_iterator f = m_settings->InputFiles.begin(); f != m_settings->InputFiles.end(); ++f) {
116               
117                 if ( Utilities::FileExists(*f + ".bai") ) {
118                     hasDefaultIndex = true;
119                     ++defaultIndexCount;
120                 }       
121                 
122                 if ( Utilities::FileExists(*f + ".bti") ) {
123                     hasBamtoolsIndex = true;
124                     ++bamtoolsIndexCount;
125                 }
126                   
127                 if ( !hasDefaultIndex && !hasBamtoolsIndex ) {
128                     hasNoIndex = true;
129                     cerr << "*WARNING - could not find index file for " << *f  
130                          << ", parsing whole file(s) to get alignment counts for target region" 
131                          << " (could be slow)" << endl;
132                     break;
133                 }
134             }
135             
136             // determine if index file types are heterogeneous
137             bool hasDifferentIndexTypes = false;
138             if ( defaultIndexCount > 0 && bamtoolsIndexCount > 0 ) {
139                 hasDifferentIndexTypes = true;
140                 cerr << "*WARNING - different index file formats found"  
141                          << ", parsing whole file(s) to get alignment counts for target region" 
142                          << " (could be slow)" << endl;
143             }
144             
145             // if any input file has no index, or if input files use different index formats
146             // can't use BamMultiReader to jump directly (**for now**)
147             if ( hasNoIndex || hasDifferentIndexTypes ) {
148                 
149                 // read through sequentially, counting all overlapping reads
150                 BamAlignment al;
151                 while( reader.GetNextAlignmentCore(al) ) {
152                     if ( (al.RefID >= region.LeftRefID)  && ( (al.Position + al.Length) >= region.LeftPosition ) &&
153                          (al.RefID <= region.RightRefID) && ( al.Position <= region.RightPosition) ) 
154                     {
155                         ++alignmentCount;
156                     }
157                 }
158             }
159             
160             // has index file for each input file (and same format)
161             else {
162               
163                 // this is kind of a hack...?
164                 BamMultiReader reader;
165                 reader.Open(m_settings->InputFiles, true, true, hasDefaultIndex );
166               
167                 if ( !reader.SetRegion(region.LeftRefID, region.LeftPosition, region.RightRefID, region.RightPosition) ) {
168                    foundError = true;
169                    errorStream << "Could not set BamReader region to REGION: " << m_settings->Region << endl;
170                 } else {
171                     BamAlignment al;
172                     while ( reader.GetNextAlignmentCore(al) )
173                         ++alignmentCount;
174                 }
175             }
176             
177         } else {
178             foundError = true;
179             errorStream << "Could not parse REGION: " << m_settings->Region << endl;
180             errorStream << "Be sure REGION is in valid format (see README) and that coordinates are valid for selected references" << endl;
181         }
182     }
183      
184     // print errors OR results 
185     if ( foundError )
186         cerr << errorStream.str() << endl;
187     else
188         cout << alignmentCount << endl;
189     
190     // clean & exit
191     reader.Close();
192     return (int)foundError;
193 }