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: 12 October 2010
7 // ---------------------------------------------------------------------------
8 // Prints general alignment statistics for BAM file(s).
9 // ***************************************************************************
18 #include "bamtools_stats.h"
19 #include "bamtools_options.h"
20 #include "BamMultiReader.h"
22 using namespace BamTools;
24 // ---------------------------------------------
25 // StatsSettings implementation
27 struct StatsTool::StatsSettings {
31 bool IsShowingInsertSizeSummary;
34 vector<string> InputFiles;
39 , IsShowingInsertSizeSummary(false)
43 // ---------------------------------------------
44 // StatsToolPrivate implementation
46 struct StatsTool::StatsToolPrivate {
50 StatsToolPrivate(StatsTool::StatsSettings* _settings);
51 ~StatsToolPrivate(void);
59 bool CalculateMedian(vector<int>& data, double& median);
60 void PrintStats(void);
61 void ProcessAlignment(const BamAlignment& al);
65 StatsTool::StatsSettings* settings;
66 unsigned int numReads;
67 unsigned int numPaired;
68 unsigned int numProperPair;
69 unsigned int numMapped;
70 unsigned int numBothMatesMapped;
71 unsigned int numForwardStrand;
72 unsigned int numReverseStrand;
73 unsigned int numFirstMate;
74 unsigned int numSecondMate;
75 unsigned int numSingletons;
76 unsigned int numFailedQC;
77 unsigned int numDuplicates;
78 vector<int> insertSizes;
81 StatsTool::StatsToolPrivate::StatsToolPrivate(StatsTool::StatsSettings* _settings)
87 , numBothMatesMapped(0)
96 insertSizes.reserve(100000);
99 StatsTool::StatsToolPrivate::~StatsToolPrivate(void) { }
101 // median is of type double because in the case of even number of data elements, we need to return the average of middle 2 elements
102 bool StatsTool::StatsToolPrivate::CalculateMedian(vector<int>& data, double& median) {
104 // check that data exists
105 if ( data.empty() ) return false;
107 // find middle element
108 size_t middleIndex = data.size() / 2;
109 vector<int>::iterator target = data.begin() + middleIndex;
110 nth_element(data.begin(), target, data.end());
112 // odd number of elements
113 if ( (data.size() % 2) != 0) {
114 median = (double)(*target);
118 // even number of elements
120 double rightTarget = (double)(*target);
121 vector<int>::iterator leftTarget = target - 1;
122 nth_element(data.begin(), leftTarget, data.end());
123 median = (double)((rightTarget+*leftTarget)/2.0);
128 // print BAM file alignment stats
129 void StatsTool::StatsToolPrivate::PrintStats(void) {
132 cout << "**********************************************" << endl;
133 cout << "Stats for BAM file(s): " << endl;
134 cout << "**********************************************" << endl;
136 cout << "Total reads: " << numReads << endl;
137 cout << "Mapped reads: " << numMapped << "\t(" << ((float)numMapped/numReads)*100 << "%)" << endl;
138 cout << "Forward strand: " << numForwardStrand << "\t(" << ((float)numForwardStrand/numReads)*100 << "%)" << endl;
139 cout << "Reverse strand: " << numReverseStrand << "\t(" << ((float)numReverseStrand/numReads)*100 << "%)" << endl;
140 cout << "Failed QC: " << numFailedQC << "\t(" << ((float)numFailedQC/numReads)*100 << "%)" << endl;
141 cout << "Duplicates: " << numDuplicates << "\t(" << ((float)numDuplicates/numReads)*100 << "%)" << endl;
142 cout << "Paired-end reads: " << numPaired << "\t(" << ((float)numPaired/numReads)*100 << "%)" << endl;
144 if ( numPaired != 0 ) {
145 cout << "'Proper-pairs': " << numProperPair << "\t(" << ((float)numProperPair/numPaired)*100 << "%)" << endl;
146 cout << "Both pairs mapped: " << numBothMatesMapped << "\t(" << ((float)numBothMatesMapped/numPaired)*100 << "%)" << endl;
147 cout << "Read 1: " << numFirstMate << endl;
148 cout << "Read 2: " << numSecondMate << endl;
149 cout << "Singletons: " << numSingletons << "\t(" << ((float)numSingletons/numPaired)*100 << "%)" << endl;
152 if ( settings->IsShowingInsertSizeSummary ) {
154 double avgInsertSize = 0.0;
155 if ( !insertSizes.empty() ) {
156 avgInsertSize = ( accumulate(insertSizes.begin(), insertSizes.end(), 0.0) / (double)insertSizes.size() );
157 cout << "Average insert size (absolute value): " << avgInsertSize << endl;
160 double medianInsertSize = 0.0;
161 if ( CalculateMedian(insertSizes, medianInsertSize) )
162 cout << "Median insert size (absolute value): " << medianInsertSize << endl;
167 // use current input alignment to update BAM file alignment stats
168 void StatsTool::StatsToolPrivate::ProcessAlignment(const BamAlignment& al) {
170 // increment total alignment counter
173 // check the paired-independent flags
174 if ( al.IsDuplicate() ) ++numDuplicates;
175 if ( al.IsFailedQC() ) ++numFailedQC;
176 if ( al.IsMapped() ) ++numMapped;
178 // check forward/reverse strand
179 if ( al.IsReverseStrand() )
184 // if alignment is paired-end
185 if ( al.IsPaired() ) {
187 // increment PE counter
190 // increment first mate/second mate counters
191 if ( al.IsFirstMate() ) ++numFirstMate;
192 if ( al.IsSecondMate() ) ++numSecondMate;
194 // if alignment is mapped, check mate status
195 if ( al.IsMapped() ) {
197 if ( al.IsMateMapped() )
198 ++numBothMatesMapped;
204 // check for explicit proper pair flag
205 if ( al.IsProperPair() ) ++numProperPair;
207 // store insert size for first mate
208 if ( settings->IsShowingInsertSizeSummary && al.IsFirstMate() && (al.InsertSize != 0) ) {
209 int insertSize = abs(al.InsertSize);
210 insertSizes.push_back( insertSize );
215 bool StatsTool::StatsToolPrivate::Run() {
217 // opens the BAM files without checking for indexes
218 BamMultiReader reader;
219 if ( !reader.Open(settings->InputFiles, false, true) ) {
220 cerr << "Could not open input BAM file(s)... quitting." << endl;
225 // plow through file, keeping track of stats
227 while ( reader.GetNextAlignmentCore(al) )
228 ProcessAlignment(al);
238 // ---------------------------------------------
239 // StatsTool implementation
241 StatsTool::StatsTool(void)
243 , m_settings(new StatsSettings)
246 // set program details
247 Options::SetProgramInfo("bamtools stats", "prints general alignment statistics", "[-in <filename> -in <filename> ...] [statsOptions]");
250 OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
251 Options::AddValueOption("-in", "BAM filename", "the input BAM file", "", m_settings->HasInput, m_settings->InputFiles, IO_Opts, Options::StandardIn());
253 OptionGroup* AdditionalOpts = Options::CreateOptionGroup("Additional Stats");
254 Options::AddOption("-insert", "summarize insert size data", m_settings->IsShowingInsertSizeSummary, AdditionalOpts);
257 StatsTool::~StatsTool(void) {
265 int StatsTool::Help(void) {
266 Options::DisplayHelp();
270 int StatsTool::Run(int argc, char* argv[]) {
272 // parse command line arguments
273 Options::Parse(argc, argv, 1);
275 // set to default input if none provided
276 if ( !m_settings->HasInput )
277 m_settings->InputFiles.push_back(Options::StandardIn());
279 // run internal StatsTool implementation, return success/fail
280 m_impl = new StatsToolPrivate(m_settings);
282 if ( m_impl->Run() ) return 0;