]> git.donarmstrong.com Git - bamtools.git/blob - bamtools_count.cpp
Added support for reading FASTA sequences, as well as generating FASTA index (.fai...
[bamtools.git] / 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", "", m_settings->HasInputBamFilename, m_settings->InputBamFilename, IO_Opts, Options::StandardIn());
61     Options::AddValueOption("-in",  "BAM filename", "the input BAM file(s)", "", m_settings->HasInput,  m_settings->InputFiles, IO_Opts);
62     //Options::AddValueOption("-index", "BAM index filename", "the BAM index file",  "", m_settings->HasBamIndexFilename, m_settings->BamIndexFilename, IO_Opts);
63     
64     OptionGroup* FilterOpts = Options::CreateOptionGroup("Filters");
65     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);
66 }
67
68 CountTool::~CountTool(void) { 
69     delete m_settings;
70     m_settings = 0;
71 }
72
73 int CountTool::Help(void) { 
74     Options::DisplayHelp();
75     return 0;
76
77
78 int CountTool::Run(int argc, char* argv[]) { 
79
80     // parse command line arguments
81     Options::Parse(argc, argv, 1);
82
83     BamMultiReader reader;
84     reader.Open(m_settings->InputFiles, false, true);
85
86     // alignment counter
87     int alignmentCount(0);
88     
89     // set up error handling
90     ostringstream errorStream("");
91     bool foundError(false);
92     
93     // if no region specified, count entire file 
94     if ( !m_settings->HasRegion ) {
95         BamAlignment al;
96         while ( reader.GetNextAlignmentCore(al) ) 
97             ++alignmentCount;
98     }
99     
100     // more complicated - region specified
101     else {
102         
103         BamRegion region;
104         if ( Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
105
106             // check if there are index files *.bai/*.bti corresponding to the input files
107             bool hasDefaultIndex   = false;
108             bool hasBamtoolsIndex  = false;
109             bool hasNoIndex        = false;
110             int defaultIndexCount   = 0;
111             int bamtoolsIndexCount = 0;
112             for (vector<string>::const_iterator f = m_settings->InputFiles.begin(); f != m_settings->InputFiles.end(); ++f) {
113               
114                 if ( Utilities::FileExists(*f + ".bai") ) {
115                     hasDefaultIndex = true;
116                     ++defaultIndexCount;
117                 }       
118                 
119                 if ( Utilities::FileExists(*f + ".bti") ) {
120                     hasBamtoolsIndex = true;
121                     ++bamtoolsIndexCount;
122                 }
123                   
124                 if ( !hasDefaultIndex && !hasBamtoolsIndex ) {
125                     hasNoIndex = true;
126                     cerr << "*WARNING - could not find index file for " << *f  
127                          << ", parsing whole file(s) to get alignment counts for target region" 
128                          << " (could be slow)" << endl;
129                     break;
130                 }
131             }
132             
133             // determine if index file types are heterogeneous
134             bool hasDifferentIndexTypes = false;
135             if ( defaultIndexCount > 0 && bamtoolsIndexCount > 0 ) {
136                 hasDifferentIndexTypes = true;
137                 cerr << "*WARNING - different index file formats found"  
138                          << ", parsing whole file(s) to get alignment counts for target region" 
139                          << " (could be slow)" << endl;
140             }
141             
142             // if any input file has no index, or if input files use different index formats
143             // can't use BamMultiReader to jump directly (**for now**)
144             if ( hasNoIndex || hasDifferentIndexTypes ) {
145                 
146                 // read through sequentially, counting all overlapping reads
147                 BamAlignment al;
148                 while( reader.GetNextAlignmentCore(al) ) {
149                     if ( (al.RefID >= region.LeftRefID)  && ( (al.Position + al.Length) >= region.LeftPosition ) &&
150                          (al.RefID <= region.RightRefID) && ( al.Position <= region.RightPosition) ) 
151                     {
152                         ++alignmentCount;
153                     }
154                 }
155             }
156             
157             // has index file for each input file (and same format)
158             else {
159               
160                 // this is kind of a hack...?
161                 BamMultiReader reader;
162                 reader.Open(m_settings->InputFiles, true, true, hasDefaultIndex );
163               
164                 if ( !reader.SetRegion(region.LeftRefID, region.LeftPosition, region.RightRefID, region.RightPosition) ) {
165                    foundError = true;
166                    errorStream << "Could not set BamReader region to REGION: " << m_settings->Region << endl;
167                 } else {
168                     BamAlignment al;
169                     while ( reader.GetNextAlignmentCore(al) )
170                         ++alignmentCount;
171                 }
172             }
173             
174         } else {
175             foundError = true;
176             errorStream << "Could not parse REGION: " << m_settings->Region << endl;
177             errorStream << "Be sure REGION is in valid format (see README) and that coordinates are valid for selected references" << endl;
178         }
179     }
180      
181     // print errors OR results 
182     if ( foundError )
183         cerr << errorStream.str() << endl;
184     else
185         cout << alignmentCount << endl;
186     
187     // clean & exit
188     reader.Close();
189     return (int)foundError;
190 }