]> git.donarmstrong.com Git - bamtools.git/blob - bamtools_count.cpp
integration of SetRegion into BamMultiReader
[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. 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 corresponding to the input files
107             bool hasIndexes = true;
108             for (vector<string>::const_iterator f = m_settings->InputFiles.begin(); f != m_settings->InputFiles.end(); ++f) {
109                 if (!Utilities::FileExists(*f + ".bai")) {
110                     errorStream << "could not find index file " << *f + ".bai" 
111                         << ", parsing whole file(s) to get alignment counts for target region" << endl;
112                     hasIndexes = false;
113                     break;
114                 }
115             }
116             // has index, we can jump directly to 
117             if ( hasIndexes ) {
118               
119                 // this is kind of a hack...?
120                 BamMultiReader reader;
121                 reader.Open(m_settings->InputFiles, true, true);
122               
123                 if ( !reader.SetRegion(region.LeftRefID, region.LeftPosition, region.RightRefID, region.RightPosition) ) {
124                    foundError = true;
125                    errorStream << "Could not set BamReader region to REGION: " << m_settings->Region << endl;
126                 } else {
127                     BamAlignment al;
128                     while ( reader.GetNextAlignmentCore(al) )
129                         ++alignmentCount;
130                 }
131
132             } else {
133               
134                 // read through sequentially, until first overlapping read is found
135                 BamAlignment al;
136                 bool alignmentFound(false);
137                 //reader.Open(m_settings->InputFiles, false, true);
138                 while( reader.GetNextAlignmentCore(al) ) {
139                     if ( (al.RefID == region.LeftRefID) && ( (al.Position + al.Length) >= region.LeftPosition ) ) {
140                         alignmentFound = true;
141                         break;
142                     }
143                 }
144                 
145                 // if overlapping alignment found (not EOF), increment counter
146                 if ( alignmentFound ) ++ alignmentCount;
147             }
148             
149             // -----------------------------
150             // count alignments until stop hit
151             
152         } else {
153             foundError = true;
154             errorStream << "Could not parse REGION: " << m_settings->Region << endl;
155             errorStream << "Be sure REGION is in valid format (see README) and that coordinates are valid for selected references" << endl;
156         }
157     }
158      
159     // print errors OR results 
160     if ( foundError )
161         cerr << errorStream.str() << endl;
162     else
163         cout << alignmentCount << endl;
164     
165     // clean & exit
166     reader.Close();
167     return (int)foundError;
168 }