// Marth Lab, Department of Biology, Boston College
// All rights reserved.
// ---------------------------------------------------------------------------
-// Last modified: 2 June 2010
+// Last modified: 7 April 2011
// ---------------------------------------------------------------------------
-// Prints alignment count for BAM file
-//
-// ** Expand to multiple??
-//
+// Prints alignment count for BAM file(s)
// ***************************************************************************
+#include "bamtools_count.h"
+
+#include <api/BamAlgorithms.h>
+#include <api/BamMultiReader.h>
+#include <utils/bamtools_options.h>
+#include <utils/bamtools_utilities.h>
+using namespace BamTools;
+
#include <iostream>
-#include <sstream>
#include <string>
#include <vector>
-
-#include "bamtools_count.h"
-#include "bamtools_options.h"
-#include "bamtools_utilities.h"
-#include "BamReader.h"
-#include "BamMultiReader.h"
-
using namespace std;
-using namespace BamTools;
-
+
// ---------------------------------------------
// CountSettings implementation
{ }
};
+// ---------------------------------------------
+// CountToolPrivate implementation
+
+struct CountTool::CountToolPrivate {
+
+ // ctor & dtro
+ public:
+ CountToolPrivate(CountTool::CountSettings* settings)
+ : m_settings(settings)
+ { }
+
+ ~CountToolPrivate(void) { }
+
+ // interface
+ public:
+ bool Run(void);
+
+ // data members
+ private:
+ CountTool::CountSettings* m_settings;
+};
+
+static
+void printAlignments(const vector<BamAlignment>& alignments) {
+
+ vector<BamAlignment>::const_iterator alIter = alignments.begin();
+ vector<BamAlignment>::const_iterator alEnd = alignments.end();
+ for ( ; alIter != alEnd; ++alIter ) {
+ const BamAlignment& a = (*alIter);
+
+ cerr << a.Name
+ << "\t" << a.RefID << ":" << a.Position;
+
+ int aqValue;
+ bool hasTag = a.GetTag("Aq", aqValue);
+ cerr << "\tAq=";
+ if ( hasTag ) cerr << aqValue;
+ else cerr << "?";
+ cerr << endl;
+ }
+}
+
+bool CountTool::CountToolPrivate::Run(void) {
+
+ // if no '-in' args supplied, default to stdin
+ if ( !m_settings->HasInput )
+ m_settings->InputFiles.push_back(Options::StandardIn());
+
+ // open reader without index
+ BamMultiReader reader;
+ if ( !reader.Open(m_settings->InputFiles) ) {
+ cerr << "bamtools count ERROR: could not open input BAM file(s)... Aborting." << endl;
+ return false;
+ }
+
+ // alignment counter
+ BamAlignment al;
+ int alignmentCount(0);
+
+ // if no region specified, count entire file
+ if ( !m_settings->HasRegion ) {
+
+
+ vector<BamAlignment> alignments;
+ while ( reader.GetNextAlignment(al) ) {
+ ++alignmentCount;
+
+ if ( alignments.size() < 100 )
+ alignments.push_back(al);
+ }
+
+ using namespace BamTools::Algorithms;
+
+ cerr << endl
+ << "------------------------------" << endl
+ << "Unsorted Alignments" << endl
+ << "------------------------------" << endl
+ << endl;
+ std::stable_sort(alignments.begin(), alignments.end(), Sort::Unsorted());
+ printAlignments(alignments);
+ cerr << "------------------------------" << endl
+ << endl;
+
+ cerr << endl
+ << "------------------------------" << endl
+ << "Sorted Alignments (by name)" << endl
+ << "------------------------------" << endl
+ << endl;
+// std::sort(alignments.begin(), alignments.end(), Sort::ByName());
+ Algorithms::SortAlignments(alignments, Sort::ByName());
+ printAlignments(alignments);
+ cerr << endl
+ << "------------------------------" << endl
+ << endl;
+
+ cerr << endl
+ << "------------------------------" << endl
+ << "Sorted Alignments (by tag Aq)" << endl
+ << "------------------------------" << endl
+ << endl;
+// std::sort(alignments.begin(), alignments.end(), Sort::ByTag<int>("Aq"));
+ Algorithms::SortAlignments(alignments, Sort::ByTag<int>("Aq"));
+ printAlignments(alignments);
+ cerr << endl
+ << "------------------------------" << endl
+ << endl;
+
+ cerr << endl
+ << "------------------------------" << endl
+ << "Sorted Alignments (by tag Aq) desc" << endl
+ << "------------------------------" << endl
+ << endl;
+ std::sort(alignments.begin(), alignments.end(), Sort::ByTag<int>("Aq", Sort::DescendingOrder));
+ printAlignments(alignments);
+ cerr << endl
+ << "------------------------------" << endl
+ << endl;
+
+
+
+
+// // ########################################
+// // original
+// // ########################################
+//
+// while ( reader.GetNextAlignmentCore(al) )
+// ++alignmentCount;
+//
+// //#########################################
+ }
+
+ // otherwise attempt to use region as constraint
+ else {
+
+ // if region string parses OK
+ BamRegion region;
+ if ( Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
+
+ // attempt to find index files
+ reader.LocateIndexes();
+
+ // if index data available for all BAM files, we can use SetRegion
+ if ( reader.HasIndexes() ) {
+
+ vector<BamAlignment> alignments;
+ using namespace BamTools::Algorithms;
+
+ alignments = GetSortedRegion(reader, region, Sort::ByName() );
+ printAlignments(alignments);
+
+ cerr << "################################" << endl;
+
+ alignments = GetSortedRegion(reader, region, Sort::ByTag<int>("Aq"));
+ printAlignments(alignments);
+
+// // attempt to set region on reader
+// if ( !reader.SetRegion(region.LeftRefID, region.LeftPosition, region.RightRefID, region.RightPosition) ) {
+// cerr << "bamtools count ERROR: set region failed. Check that REGION describes a valid range" << endl;
+// reader.Close();
+// return false;
+// }
+
+// // everything checks out, just iterate through specified region, counting alignments
+// while ( reader.GetNextAlignmentCore(al) )
+// ++alignmentCount;
+ }
+
+ // no index data available, we have to iterate through until we
+ // find overlapping alignments
+ else {
+ while ( reader.GetNextAlignmentCore(al) ) {
+ if ( (al.RefID >= region.LeftRefID) && ( (al.Position + al.Length) >= region.LeftPosition ) &&
+ (al.RefID <= region.RightRefID) && ( al.Position <= region.RightPosition) )
+ {
+ ++alignmentCount;
+ }
+ }
+ }
+ }
+
+ // error parsing REGION string
+ else {
+ cerr << "bamtools count ERROR: could not parse REGION - " << m_settings->Region << endl;
+ cerr << "Check that REGION is in valid format (see documentation) and that the coordinates are valid"
+ << endl;
+ reader.Close();
+ return false;
+ }
+ }
+
+ // print results
+ cout << alignmentCount << endl;
+
+ // clean up & exit
+ reader.Close();
+ return true;
+}
+
// ---------------------------------------------
// CountTool implementation
CountTool::CountTool(void)
: AbstractTool()
, m_settings(new CountSettings)
+ , m_impl(0)
{
// set program details
- Options::SetProgramInfo("bamtools count", "prints alignment counts for a BAM file", "-in <filename> [-region <REGION>]");
+ Options::SetProgramInfo("bamtools count", "prints number of alignments in BAM file(s)", "[-in <filename> -in <filename> ...] [-region <REGION>]");
// set up options
OptionGroup* IO_Opts = Options::CreateOptionGroup("Input & Output");
- Options::AddValueOption("-in", "BAM filename", "the input BAM file(s)", "", m_settings->HasInput, m_settings->InputFiles, IO_Opts);
- //Options::AddValueOption("-index", "BAM index filename", "the BAM index file", "", m_settings->HasBamIndexFilename, m_settings->BamIndexFilename, IO_Opts);
-
- OptionGroup* FilterOpts = Options::CreateOptionGroup("Filters");
- 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);
+ Options::AddValueOption("-in", "BAM filename", "the input BAM file(s)", "", m_settings->HasInput, m_settings->InputFiles, IO_Opts, Options::StandardIn());
+ Options::AddValueOption("-region", "REGION", "genomic region. Index file is recommended for better performance, and is used automatically if it exists. See \'bamtools help index\' for more details on creating one", "", m_settings->HasRegion, m_settings->Region, IO_Opts);
}
CountTool::~CountTool(void) {
+
delete m_settings;
m_settings = 0;
+
+ delete m_impl;
+ m_impl = 0;
}
int CountTool::Help(void) {
// parse command line arguments
Options::Parse(argc, argv, 1);
- if ( !m_settings->HasInput )
- m_settings->InputFiles.push_back(Options::StandardIn());
-
- BamMultiReader reader;
- reader.Open(m_settings->InputFiles, false, true);
+ // initialize CountTool with settings
+ m_impl = new CountToolPrivate(m_settings);
- // alignment counter
- int alignmentCount(0);
-
- // set up error handling
- ostringstream errorStream("");
- bool foundError(false);
-
- // if no region specified, count entire file
- if ( !m_settings->HasRegion ) {
- BamAlignment al;
- while ( reader.GetNextAlignmentCore(al) )
- ++alignmentCount;
- }
-
- // more complicated - region specified
- else {
-
- BamRegion region;
- if ( Utilities::ParseRegionString(m_settings->Region, reader, region) ) {
-
- // check if there are index files *.bai/*.bti corresponding to the input files
- bool hasDefaultIndex = false;
- bool hasBamtoolsIndex = false;
- bool hasNoIndex = false;
- int defaultIndexCount = 0;
- int bamtoolsIndexCount = 0;
- for (vector<string>::const_iterator f = m_settings->InputFiles.begin(); f != m_settings->InputFiles.end(); ++f) {
-
- if ( Utilities::FileExists(*f + ".bai") ) {
- hasDefaultIndex = true;
- ++defaultIndexCount;
- }
-
- if ( Utilities::FileExists(*f + ".bti") ) {
- hasBamtoolsIndex = true;
- ++bamtoolsIndexCount;
- }
-
- if ( !hasDefaultIndex && !hasBamtoolsIndex ) {
- hasNoIndex = true;
- cerr << "*WARNING - could not find index file for " << *f
- << ", parsing whole file(s) to get alignment counts for target region"
- << " (could be slow)" << endl;
- break;
- }
- }
-
- // determine if index file types are heterogeneous
- bool hasDifferentIndexTypes = false;
- if ( defaultIndexCount > 0 && bamtoolsIndexCount > 0 ) {
- hasDifferentIndexTypes = true;
- cerr << "*WARNING - different index file formats found"
- << ", parsing whole file(s) to get alignment counts for target region"
- << " (could be slow)" << endl;
- }
-
- // if any input file has no index, or if input files use different index formats
- // can't use BamMultiReader to jump directly (**for now**)
- if ( hasNoIndex || hasDifferentIndexTypes ) {
-
- // read through sequentially, counting all overlapping reads
- BamAlignment al;
- while( reader.GetNextAlignmentCore(al) ) {
- if ( (al.RefID >= region.LeftRefID) && ( (al.Position + al.Length) >= region.LeftPosition ) &&
- (al.RefID <= region.RightRefID) && ( al.Position <= region.RightPosition) )
- {
- ++alignmentCount;
- }
- }
- }
-
- // has index file for each input file (and same format)
- else {
-
- // this is kind of a hack...?
- BamMultiReader reader;
- reader.Open(m_settings->InputFiles, true, true, hasDefaultIndex );
-
- if ( !reader.SetRegion(region.LeftRefID, region.LeftPosition, region.RightRefID, region.RightPosition) ) {
- foundError = true;
- errorStream << "Could not set BamReader region to REGION: " << m_settings->Region << endl;
- } else {
- BamAlignment al;
- while ( reader.GetNextAlignmentCore(al) )
- ++alignmentCount;
- }
- }
-
- } else {
- foundError = true;
- errorStream << "Could not parse REGION: " << m_settings->Region << endl;
- errorStream << "Be sure REGION is in valid format (see README) and that coordinates are valid for selected references" << endl;
- }
- }
-
- // print errors OR results
- if ( foundError )
- cerr << errorStream.str() << endl;
+ // run CountTool, return success/fail
+ if ( m_impl->Run() )
+ return 0;
else
- cout << alignmentCount << endl;
-
- // clean & exit
- reader.Close();
- return (int)foundError;
+ return 1;
}