1 // ***************************************************************************
2 // bamtools_cpp (c) 2010 Derek Barnett, Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // All rights reserved.
5 // ---------------------------------------------------------------------------
6 // Last modified: 22 July 2010
7 // ---------------------------------------------------------------------------
8 // Prints general alignment statistics for BAM file(s).
9 // ***************************************************************************
19 #include "bamtools_stats.h"
20 #include "bamtools_options.h"
21 #include "BamMultiReader.h"
23 using namespace BamTools;
25 // ---------------------------------------------
26 // StatsSettings implementation
28 struct StatsTool::StatsSettings {
32 bool IsShowingInsertSizeSummary;
35 vector<string> InputFiles;
40 , IsShowingInsertSizeSummary(false)
44 // ---------------------------------------------
45 // StatsToolPrivate implementation
47 struct StatsTool::StatsToolPrivate {
51 StatsToolPrivate(StatsTool::StatsSettings* _settings);
52 ~StatsToolPrivate(void);
60 bool CalculateMedian(vector<int>& data, double& median);
61 void PrintStats(void);
62 void ProcessAlignment(const BamAlignment& al);
66 StatsTool::StatsSettings* settings;
67 unsigned int numReads;
68 unsigned int numPaired;
69 unsigned int numProperPair;
70 unsigned int numMapped;
71 unsigned int numBothMatesMapped;
72 unsigned int numForwardStrand;
73 unsigned int numReverseStrand;
74 unsigned int numFirstMate;
75 unsigned int numSecondMate;
76 unsigned int numSingletons;
77 unsigned int numFailedQC;
78 unsigned int numDuplicates;
79 vector<int> insertSizes;
82 StatsTool::StatsToolPrivate::StatsToolPrivate(StatsTool::StatsSettings* _settings)
88 , numBothMatesMapped(0)
97 insertSizes.reserve(100000);
100 StatsTool::StatsToolPrivate::~StatsToolPrivate(void) { }
102 bool StatsTool::StatsToolPrivate::CalculateMedian(vector<int>& data, double& median) { // median is double in case of even data size, need to return average of middle 2 elements
104 // check that data exists
105 if ( data.empty() ) return false;
107 size_t dataSize = data.size();
108 size_t middleIndex = dataSize / 2;
110 vector<int>::iterator target = data.begin() + middleIndex;
111 nth_element(data.begin(), target, data.end());
113 // odd number of elements
114 if ( (dataSize % 2) != 0) {
115 median = (double)(*target);
119 // even number of elements
121 double rightTarget = (double)(*target);
122 vector<int>::iterator leftTarget = target - 1;
123 nth_element(data.begin(), leftTarget, data.end());
124 median = (double)((rightTarget+*leftTarget)/2.0);
129 // print BAM file alignment stats
130 void StatsTool::StatsToolPrivate::PrintStats(void) {
133 cout << "**********************************************" << endl;
134 cout << "Stats for BAM file(s): " << endl;
135 cout << "**********************************************" << endl;
137 cout << "Total reads: " << numReads << endl;
138 cout << "Mapped reads: " << numMapped << "\t(" << ((float)numMapped/numReads)*100 << "%)" << endl;
139 cout << "Forward strand: " << numForwardStrand << "\t(" << ((float)numForwardStrand/numReads)*100 << "%)" << endl;
140 cout << "Reverse strand: " << numReverseStrand << "\t(" << ((float)numReverseStrand/numReads)*100 << "%)" << endl;
141 cout << "Failed QC: " << numFailedQC << "\t(" << ((float)numFailedQC/numReads)*100 << "%)" << endl;
142 cout << "Duplicates: " << numDuplicates << "\t(" << ((float)numDuplicates/numReads)*100 << "%)" << endl;
143 cout << "Paired-end reads: " << numPaired << "\t(" << ((float)numPaired/numReads)*100 << "%)" << endl;
145 if ( numPaired != 0 ) {
146 cout << "'Proper-pairs': " << numProperPair << "\t(" << ((float)numProperPair/numPaired)*100 << "%)" << endl;
147 cout << "Both pairs mapped: " << numBothMatesMapped << "\t(" << ((float)numBothMatesMapped/numPaired)*100 << "%)" << endl;
148 cout << "Read 1: " << numFirstMate << endl;
149 cout << "Read 2: " << numSecondMate << endl;
150 cout << "Singletons: " << numSingletons << "\t(" << ((float)numSingletons/numPaired)*100 << "%)" << endl;
153 if ( settings->IsShowingInsertSizeSummary ) {
155 double avgInsertSize = 0.0;
156 if ( !insertSizes.empty() ) {
157 avgInsertSize = ( accumulate(insertSizes.begin(), insertSizes.end(), 0.0) / (double)insertSizes.size() );
158 cout << "Average insert size (absolute value): " << avgInsertSize << endl;
161 double medianInsertSize = 0.0;
162 if ( CalculateMedian(insertSizes, medianInsertSize) )
163 cout << "Median insert size (absolute value): " << medianInsertSize << endl;
168 // use current input alignment to update BAM file alignment stats
169 void StatsTool::StatsToolPrivate::ProcessAlignment(const BamAlignment& al) {
171 // increment total alignment counter
174 // check the paired-independent flags
175 if ( al.IsDuplicate() ) ++numDuplicates;
176 if ( al.IsFailedQC() ) ++numFailedQC;
177 if ( al.IsMapped() ) ++numMapped;
179 // check forward/reverse strand
180 if ( al.IsReverseStrand() )
185 // if alignment is paired-end
186 if ( al.IsPaired() ) {
188 // increment PE counter
191 // increment first mate/second mate counters
192 if ( al.IsFirstMate() ) ++numFirstMate;
193 if ( al.IsSecondMate() ) ++numSecondMate;
195 // if alignment is mapped, check mate status
196 if ( al.IsMapped() ) {
198 if ( al.IsMateMapped() )
199 ++numBothMatesMapped;
205 // check for explicit proper pair flag
206 if ( al.IsProperPair() ) ++numProperPair;
208 // store insert size for first mate
209 if ( settings->IsShowingInsertSizeSummary && al.IsFirstMate() && (al.InsertSize != 0) ) {
210 int insertSize = abs(al.InsertSize);
211 insertSizes.push_back( insertSize );
216 bool StatsTool::StatsToolPrivate::Run() {
218 // opens the BAM files without checking for indexes
219 BamMultiReader reader;
220 if ( !reader.Open(settings->InputFiles, false, true) ) {
221 cerr << "Could not open input BAM file(s)... quitting." << endl;
226 // plow through file, keeping track of stats
228 while ( reader.GetNextAlignmentCore(al) ) {
229 ProcessAlignment(al);
240 // ---------------------------------------------
241 // StatsTool implementation
243 StatsTool::StatsTool(void)
245 , m_settings(new StatsSettings)
248 // set program details
249 Options::SetProgramInfo("bamtools stats", "prints general alignment statistics", "[-in <filename> -in <filename> ... ]");
252 OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
253 Options::AddValueOption("-in", "BAM filename", "the input BAM file", "", m_settings->HasInput, m_settings->InputFiles, IO_Opts, Options::StandardIn());
255 OptionGroup* AdditionalOpts = Options::CreateOptionGroup("Additional Stats");
256 Options::AddOption("-insert", "summarize insert size data", m_settings->IsShowingInsertSizeSummary, AdditionalOpts);
259 StatsTool::~StatsTool(void) {
267 int StatsTool::Help(void) {
268 Options::DisplayHelp();
272 int StatsTool::Run(int argc, char* argv[]) {
274 // parse command line arguments
275 Options::Parse(argc, argv, 1);
277 // set to default input if none provided
278 if ( !m_settings->HasInput )
279 m_settings->InputFiles.push_back(Options::StandardIn());
281 // run internal SortTool implementation, return success/fail
282 m_impl = new StatsToolPrivate(m_settings);
284 if ( m_impl->Run() ) return 0;