]> git.donarmstrong.com Git - bamtools.git/blobdiff - src/toolkit/bamtools_count.cpp
merge master 2.3.0
[bamtools.git] / src / toolkit / bamtools_count.cpp
index 9d6623b3604cb79bb4dc54fa375c50660f67114e..5a7c0a7e2f31a9ce15c180d84e46584f8cf430f7 100644 (file)
@@ -1,26 +1,26 @@
 // ***************************************************************************
 // bamtools_count.cpp (c) 2010 Derek Barnett, Erik Garrison
 // Marth Lab, Department of Biology, Boston College
-// All rights reserved.
 // ---------------------------------------------------------------------------
-// Last modified: 3 September 2010
+// Last modified: 10 December 2012
 // ---------------------------------------------------------------------------
 // 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 <fstream>
 #include <iostream>
 #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
 
@@ -28,131 +28,183 @@ struct CountTool::CountSettings {
 
     // flags
     bool HasInput;
+    bool HasInputFilelist;
     bool HasRegion;
 
     // filenames
     vector<string> InputFiles;
+    string InputFilelist;
     string Region;
     
     // constructor
     CountSettings(void)
         : HasInput(false)
+        , HasInputFilelist(false)
         , HasRegion(false)
     { }  
 }; 
   
 // ---------------------------------------------
-// CountTool implementation
+// CountToolPrivate implementation
 
-CountTool::CountTool(void) 
-    : AbstractTool()
-    , m_settings(new CountSettings)
-{ 
-    // set program details
-    Options::SetProgramInfo("bamtools count", "prints alignment counts for a BAM file", "[-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::StandardIn());
-    
-    OptionGroup* FilterOpts = Options::CreateOptionGroup("Filters");
-    Options::AddValueOption("-region", "REGION", "genomic region. Index file is required 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);
-}
+struct CountTool::CountToolPrivate {
 
-CountTool::~CountTool(void) { 
-    delete m_settings;
-    m_settings = 0;
-}
+    // ctor & dtro
+    public:
+        CountToolPrivate(CountTool::CountSettings* settings)
+            : m_settings(settings)
+        { }
 
-int CountTool::Help(void) { 
-    Options::DisplayHelp();
-    return 0;
-} 
+        ~CountToolPrivate(void) { }
 
-int CountTool::Run(int argc, char* argv[]) { 
+    // interface
+    public:
+        bool Run(void);
 
-    // parse command line arguments
-    Options::Parse(argc, argv, 1);
+    // data members
+    private:
+        CountTool::CountSettings* m_settings;
+};
+
+bool CountTool::CountToolPrivate::Run(void) {
 
-    // if no '-in' args supplied, default to stdin
-    if ( !m_settings->HasInput 
+    // set to default input if none provided
+    if ( !m_settings->HasInput && !m_settings->HasInputFilelist )
         m_settings->InputFiles.push_back(Options::StandardIn());
-    
+
+    // add files in the filelist to the input file list
+    if ( m_settings->HasInputFilelist ) {
+
+        ifstream filelist(m_settings->InputFilelist.c_str(), ios::in);
+        if ( !filelist.is_open() ) {
+            cerr << "bamtools count ERROR: could not open input BAM file list... Aborting." << endl;
+            return false;
+        }
+
+        string line;
+        while ( getline(filelist, line) )
+            m_settings->InputFiles.push_back(line);
+    }
+
     // open reader without index
     BamMultiReader reader;
-    if (!reader.Open(m_settings->InputFiles, false, true)) {
-        cerr << "ERROR: Could not open input BAM file(s)... Aborting." << endl;
-        return 1;
+    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 no region specified, count entire file
     if ( !m_settings->HasRegion ) {
-        while ( reader.GetNextAlignmentCore(al) ) 
+        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 re-open reader with index files
-            reader.Close();
-            bool openedOK = reader.Open(m_settings->InputFiles, true, true );
-            
-            // if error
-            if ( !openedOK ) {
-                cerr << "ERROR: Could not open input BAM file(s)... Aborting." << endl;
-                return 1;
-            }
-            
-            // if index data available, we can use SetRegion
-            if ( reader.IsIndexLoaded() ) {
-              
-                // attempt to use SetRegion(), if failed report error
+            // attempt to find index files
+            reader.LocateIndexes();
+
+            // if index data available for all BAM files, we can use SetRegion
+            if ( reader.HasIndexes() ) {
+
+                // attempt to set region on reader
                 if ( !reader.SetRegion(region.LeftRefID, region.LeftPosition, region.RightRefID, region.RightPosition) ) {
-                    cerr << "ERROR: Region requested, but could not set BamReader region to REGION: " << m_settings->Region << " Aborting." << endl;
+                    cerr << "bamtools count ERROR: set region failed. Check that REGION describes a valid range" << endl;
                     reader.Close();
-                    return 1;
-                } 
-              
+                    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) ) {
+                while ( reader.GetNextAlignmentCore(al) ) {
                     if ( (al.RefID >= region.LeftRefID)  && ( (al.Position + al.Length) >= region.LeftPosition ) &&
-                          (al.RefID <= region.RightRefID) && ( al.Position <= region.RightPosition) ) 
+                          (al.RefID <= region.RightRefID) && ( al.Position <= region.RightPosition) )
                     {
                         ++alignmentCount;
                     }
                 }
             }
-        } 
-        
+        }
+
         // error parsing REGION string
         else {
-            cerr << "ERROR: Could not parse REGION - " << m_settings->Region << endl;
-            cerr << "Be sure REGION is in valid format (see README) and that coordinates are valid for selected references" << endl;
+            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 1;
+            return false;
         }
     }
-    
-    // print results 
+
+    // print results
     cout << alignmentCount << endl;
-    
-    // clean & exit
+
+    // 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 number of alignments in BAM file(s)",
+                            "[-in <filename> -in <filename> ... | -list <filelist>] [-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::StandardIn());
+    Options::AddValueOption("-list",   "filename", "the input BAM file list, one line per file", "", m_settings->HasInputFilelist,  m_settings->InputFilelist, IO_Opts);
+    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) { 
+    Options::DisplayHelp();
     return 0;
+} 
+
+int CountTool::Run(int argc, char* argv[]) { 
+
+    // parse command line arguments
+    Options::Parse(argc, argv, 1);
+
+    // initialize CountTool with settings
+    m_impl = new CountToolPrivate(m_settings);
+
+    // run CountTool, return success/fail
+    if ( m_impl->Run() )
+        return 0;
+    else
+        return 1;
 }