1 // ***************************************************************************
2 // bamtools_cpp (c) 2010 Derek Barnett, Erik Garrison
3 // Marth Lab, Department of Biology, Boston College
4 // ---------------------------------------------------------------------------
5 // Last modified: 7 April 2011
6 // ---------------------------------------------------------------------------
7 // Prints general alignment statistics for BAM file(s).
8 // ***************************************************************************
10 #include "bamtools_stats.h"
12 #include <api/BamMultiReader.h>
13 #include <utils/bamtools_options.h>
14 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* m_settings;
67 unsigned int m_numReads;
68 unsigned int m_numPaired;
69 unsigned int m_numProperPair;
70 unsigned int m_numMapped;
71 unsigned int m_numBothMatesMapped;
72 unsigned int m_numForwardStrand;
73 unsigned int m_numReverseStrand;
74 unsigned int m_numFirstMate;
75 unsigned int m_numSecondMate;
76 unsigned int m_numSingletons;
77 unsigned int m_numFailedQC;
78 unsigned int m_numDuplicates;
79 vector<int> m_insertSizes;
82 StatsTool::StatsToolPrivate::StatsToolPrivate(StatsTool::StatsSettings* settings)
83 : m_settings(settings)
88 , m_numBothMatesMapped(0)
89 , m_numForwardStrand(0)
90 , m_numReverseStrand(0)
97 m_insertSizes.reserve(100000);
100 // median is of type double because in the case of even number of data elements,
101 // we need to return the average of middle 2 elements
102 bool StatsTool::StatsToolPrivate::CalculateMedian(vector<int>& data, double& median) {
104 // skip if data empty
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: " << m_numReads << endl;
137 cout << "Mapped reads: " << m_numMapped << "\t(" << ((float)m_numMapped/m_numReads)*100 << "%)" << endl;
138 cout << "Forward strand: " << m_numForwardStrand << "\t(" << ((float)m_numForwardStrand/m_numReads)*100 << "%)" << endl;
139 cout << "Reverse strand: " << m_numReverseStrand << "\t(" << ((float)m_numReverseStrand/m_numReads)*100 << "%)" << endl;
140 cout << "Failed QC: " << m_numFailedQC << "\t(" << ((float)m_numFailedQC/m_numReads)*100 << "%)" << endl;
141 cout << "Duplicates: " << m_numDuplicates << "\t(" << ((float)m_numDuplicates/m_numReads)*100 << "%)" << endl;
142 cout << "Paired-end reads: " << m_numPaired << "\t(" << ((float)m_numPaired/m_numReads)*100 << "%)" << endl;
144 if ( m_numPaired != 0 ) {
145 cout << "'Proper-pairs': " << m_numProperPair << "\t(" << ((float)m_numProperPair/m_numPaired)*100 << "%)" << endl;
146 cout << "Both pairs mapped: " << m_numBothMatesMapped << "\t(" << ((float)m_numBothMatesMapped/m_numPaired)*100 << "%)" << endl;
147 cout << "Read 1: " << m_numFirstMate << endl;
148 cout << "Read 2: " << m_numSecondMate << endl;
149 cout << "Singletons: " << m_numSingletons << "\t(" << ((float)m_numSingletons/m_numPaired)*100 << "%)" << endl;
152 if ( m_settings->IsShowingInsertSizeSummary ) {
154 double avgInsertSize = 0.0;
155 if ( !m_insertSizes.empty() ) {
156 avgInsertSize = ( accumulate(m_insertSizes.begin(), m_insertSizes.end(), 0.0) / (double)m_insertSizes.size() );
157 cout << "Average insert size (absolute value): " << avgInsertSize << endl;
160 double medianInsertSize = 0.0;
161 if ( CalculateMedian(m_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 // incrememt counters for pairing-independent flags
174 if ( al.IsDuplicate() ) ++m_numDuplicates;
175 if ( al.IsFailedQC() ) ++m_numFailedQC;
176 if ( al.IsMapped() ) ++m_numMapped;
178 // increment strand counters
179 if ( al.IsReverseStrand() )
180 ++m_numReverseStrand;
182 ++m_numForwardStrand;
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() ) ++m_numFirstMate;
192 if ( al.IsSecondMate() ) ++m_numSecondMate;
194 // if alignment is mapped, check mate status
195 if ( al.IsMapped() ) {
197 if ( al.IsMateMapped() )
198 ++m_numBothMatesMapped;
204 // check for explicit proper pair flag
205 if ( al.IsProperPair() ) ++m_numProperPair;
207 // store insert size for first mate
208 if ( m_settings->IsShowingInsertSizeSummary && al.IsFirstMate() && (al.InsertSize != 0) ) {
209 int insertSize = abs(al.InsertSize);
210 m_insertSizes.push_back( insertSize );
215 bool StatsTool::StatsToolPrivate::Run() {
217 // set to default input if none provided
218 if ( !m_settings->HasInput )
219 m_settings->InputFiles.push_back(Options::StandardIn());
221 // open the BAM files
222 BamMultiReader reader;
223 if ( !reader.Open(m_settings->InputFiles) ) {
224 cerr << "bamtools stats ERROR: could not open input BAM file(s)... Aborting." << endl;
229 // plow through alignments, keeping track of stats
231 while ( reader.GetNextAlignmentCore(al) )
232 ProcessAlignment(al);
235 // print stats & exit
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> ...] [statsOptions]");
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) {
268 int StatsTool::Help(void) {
269 Options::DisplayHelp();
273 int StatsTool::Run(int argc, char* argv[]) {
275 // parse command line arguments
276 Options::Parse(argc, argv, 1);
278 // initialize StatsTool with settings
279 m_impl = new StatsToolPrivate(m_settings);
281 // run StatsTool, return success/fail