]> git.donarmstrong.com Git - mothur.git/blobdiff - preclustercommand.cpp
added citation function to commands
[mothur.git] / preclustercommand.cpp
index 479a862935430545757ef48c6da660913782cfa2..9299a6c6fc26e222869d515eb3fc362d0671bced 100644 (file)
 
 //**********************************************************************************************************************
 inline bool comparePriority(seqPNode first, seqPNode second) {  return (first.numIdentical > second.numIdentical); }
+
+//**********************************************************************************************************************
+vector<string> PreClusterCommand::setParameters(){     
+       try {
+               CommandParameter pfasta("fasta", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(pfasta);
+               CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
+               CommandParameter pdiffs("diffs", "Number", "", "0", "", "", "",false,false); parameters.push_back(pdiffs);
+               CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
+               CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
+               
+               vector<string> myArray;
+               for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
+               return myArray;
+       }
+       catch(exception& e) {
+               m->errorOut(e, "PreClusterCommand", "setParameters");
+               exit(1);
+       }
+}
 //**********************************************************************************************************************
+string PreClusterCommand::getHelpString(){     
+       try {
+               string helpString = "";
+               helpString += "The pre.cluster command groups sequences that are within a given number of base mismatches.\n";
+               helpString += "The pre.cluster command outputs a new fasta and name file.\n";
+               helpString += "The pre.cluster command parameters are fasta, names and diffs. The fasta parameter is required. \n";
+               helpString += "The names parameter allows you to give a list of seqs that are identical. This file is 2 columns, first column is name or representative sequence, second column is a list of its identical sequences separated by commas.\n";
+               helpString += "The diffs parameter allows you to specify maximum number of mismatched bases allowed between sequences in a grouping. The default is 1.\n";
+               helpString += "The pre.cluster command should be in the following format: \n";
+               helpString += "pre.cluster(fasta=yourFastaFile, names=yourNamesFile, diffs=yourMaxDiffs) \n";
+               helpString += "Example pre.cluster(fasta=amazon.fasta, diffs=2).\n";
+               helpString += "Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n";
+               return helpString;
+       }
+       catch(exception& e) {
+               m->errorOut(e, "PreClusterCommand", "getHelpString");
+               exit(1);
+       }
+}
 
-PreClusterCommand::PreClusterCommand(string option){
+//**********************************************************************************************************************
+PreClusterCommand::PreClusterCommand(){        
        try {
-               abort = false;
+               abort = true; calledHelp = true; 
+               setParameters();
+               vector<string> tempOutNames;
+               outputTypes["fasta"] = tempOutNames;
+               outputTypes["name"] = tempOutNames;
+       }
+       catch(exception& e) {
+               m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
+               exit(1);
+       }
+}
+//**********************************************************************************************************************
+
+PreClusterCommand::PreClusterCommand(string option) {
+       try {
+               abort = false; calledHelp = false;   
                
                //allow user to run help
-               if(option == "help") { help(); abort = true; }
+               if(option == "help") { help(); abort = true; calledHelp = true; }
+               else if(option == "citation") { citation(); abort = true; calledHelp = true;}
                
                else {
-                       //valid paramters for this command
-                       string Array[] =  {"fasta", "name", "diffs"};
-                       vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
+                       vector<string> myArray = setParameters();
                        
                        OptionParser parser(option);
                        map<string, string> parameters = parser.getParameters();
                        
                        ValidParameters validParameter;
+                       map<string, string>::iterator it;
                
                        //check to make sure all parameters are valid for command
                        for (map<string, string>::iterator it2 = parameters.begin(); it2 != parameters.end(); it2++) { 
                                if (validParameter.isValidParameter(it2->first, myArray, it2->second) != true) {  abort = true;  }
                        }
                        
+                       //initialize outputTypes
+                       vector<string> tempOutNames;
+                       outputTypes["fasta"] = tempOutNames;
+                       outputTypes["name"] = tempOutNames;
+               
+                       //if the user changes the input directory command factory will send this info to us in the output parameter 
+                       string inputDir = validParameter.validFile(parameters, "inputdir", false);              
+                       if (inputDir == "not found"){   inputDir = "";          }
+                       else {
+                               string path;
+                               it = parameters.find("fasta");
+                               //user has given a template file
+                               if(it != parameters.end()){ 
+                                       path = m->hasPath(it->second);
+                                       //if the user has not given a path then, add inputdir. else leave path alone.
+                                       if (path == "") {       parameters["fasta"] = inputDir + it->second;            }
+                               }
+                               
+                               it = parameters.find("name");
+                               //user has given a template file
+                               if(it != parameters.end()){ 
+                                       path = m->hasPath(it->second);
+                                       //if the user has not given a path then, add inputdir. else leave path alone.
+                                       if (path == "") {       parameters["name"] = inputDir + it->second;             }
+                               }
+                       }
+
                        //check for required parameters
                        fastafile = validParameter.validFile(parameters, "fasta", true);
-                       if (fastafile == "not found") { mothurOut("fasta is a required parameter for the pre.cluster command."); mothurOutEndLine(); abort = true; }
+                       if (fastafile == "not found") {                                 
+                               fastafile = m->getFastaFile(); 
+                               if (fastafile != "") { m->mothurOut("Using " + fastafile + " as input file for the fasta parameter."); m->mothurOutEndLine(); }
+                               else {  m->mothurOut("You have no current fastafile and the fasta parameter is required."); m->mothurOutEndLine(); abort = true; }
+                       }
                        else if (fastafile == "not open") { abort = true; }     
                        
+                       //if the user changes the output directory command factory will send this info to us in the output parameter 
+                       outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
+                               outputDir = ""; 
+                               outputDir += m->hasPath(fastafile); //if user entered a file with a path then preserve it       
+                       }
+
                        //check for optional parameter and set defaults
                        // ...at some point should added some additional type checking...
                        namefile = validParameter.validFile(parameters, "name", true);
@@ -53,29 +144,7 @@ PreClusterCommand::PreClusterCommand(string option){
                                
        }
        catch(exception& e) {
-               errorOut(e, "PreClusterCommand", "PreClusterCommand");
-               exit(1);
-       }
-}
-
-//**********************************************************************************************************************
-PreClusterCommand::~PreClusterCommand(){}      
-//**********************************************************************************************************************
-
-void PreClusterCommand::help(){
-       try {
-               mothurOut("The pre.cluster command groups sequences that are within a given number of base mismatches.\n");
-               mothurOut("The pre.cluster command outputs a new fasta and name file.\n");
-               mothurOut("The pre.cluster command parameters are fasta, names and diffs. The fasta parameter is required. \n");
-               mothurOut("The names parameter allows you to give a list of seqs that are identical. This file is 2 columns, first column is name or representative sequence, second column is a list of its identical sequences separated by commas.\n");
-               mothurOut("The diffs parameter allows you to specify maximum number of mismatched bases allowed between sequences in a grouping. The default is 1.\n");
-               mothurOut("The pre.cluster command should be in the following format: \n");
-               mothurOut("pre.cluster(fasta=yourFastaFile, names=yourNamesFile, diffs=yourMaxDiffs) \n");
-               mothurOut("Example pre.cluster(fasta=amazon.fasta, diffs=2).\n");
-               mothurOut("Note: No spaces between parameter labels (i.e. fasta), '=' and parameters (i.e.yourFasta).\n\n");
-       }
-       catch(exception& e) {
-               errorOut(e, "PreClusterCommand", "help");
+               m->errorOut(e, "PreClusterCommand", "PreClusterCommand");
                exit(1);
        }
 }
@@ -84,139 +153,168 @@ void PreClusterCommand::help(){
 int PreClusterCommand::execute(){
        try {
                
-               if (abort == true) { return 0; }
+               if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
+               
+               int start = time(NULL);
                
                //reads fasta file and return number of seqs
-               int numSeqs = readSeqs(); //fills alignSeqs and makes all seqs active
+               int numSeqs = readFASTA(); //fills alignSeqs and makes all seqs active
+               
+               if (m->control_pressed) { return 0; }
        
-               if (numSeqs == 0) { mothurOut("Error reading fasta file...please correct."); mothurOutEndLine(); return 0;  }
-               if (diffs > length) { mothurOut("Error: diffs is greater than your sequence length."); mothurOutEndLine(); return 0;  }
+               if (numSeqs == 0) { m->mothurOut("Error reading fasta file...please correct."); m->mothurOutEndLine(); return 0;  }
+               if (diffs > length) { m->mothurOut("Error: diffs is greater than your sequence length."); m->mothurOutEndLine(); return 0;  }
                
                //clear sizes since you only needed this info to build the alignSeqs seqPNode structs
-               sizes.clear();
+//             sizes.clear();
        
                //sort seqs by number of identical seqs
                sort(alignSeqs.begin(), alignSeqs.end(), comparePriority);
        
-               //go through active list and cluster everthing you can, until all nodes are inactive
-               //taking advantage of the fact that maps are already sorted
-               map<string, bool>::iterator itActive;
-               map<string, bool>::iterator it2Active;
                int count = 0;
-               
-               for (int i = 0; i < alignSeqs.size(); i++) {
-               
-                       //are you active
-                       itActive = active.find(alignSeqs[i].seq.getName());
+
+               //think about running through twice...
+               for (int i = 0; i < numSeqs; i++) {
                        
-                       if (itActive != active.end()) {  //this sequence has not been merged yet
+                       //are you active
+                       //                      itActive = active.find(alignSeqs[i].seq.getName());
                        
+                       if (alignSeqs[i].active) {  //this sequence has not been merged yet
+                               
                                //try to merge it with all smaller seqs
-                               for (int j = i; j < alignSeqs.size(); j++) {
+                               for (int j = i+1; j < numSeqs; j++) {
+                                       
+                                       if (m->control_pressed) { return 0; }
                                        
-                                       if (i != j) {
-                                               //are you active
-                                               it2Active = active.find(alignSeqs[j].seq.getName());
-                                               if (it2Active != active.end()) {  //this sequence has not been merged yet
-                                                       //are you within "diff" bases
-                                                       int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
-                                                       
-                                                       if (mismatch <= diffs) {
-                                                               //merge
-                                                               names[alignSeqs[i].seq.getName()] += "," + names[alignSeqs[j].seq.getName()];
-                                                       
-                                                               //remove from active list
-                                                               active.erase(it2Active);
-                                                               
-                                                               //set numIdentical to 0, so you only print the representative seqs in the fasta file
-                                                               alignSeqs[j].numIdentical = 0;
-                                                               count++;
-                                                       }
-                                               }//end if j active
-                                       }//end if i != j
-                               }//end for loop
+                                       if (alignSeqs[j].active) {  //this sequence has not been merged yet
+                                               //are you within "diff" bases
+                                               int mismatch = calcMisMatches(alignSeqs[i].seq.getAligned(), alignSeqs[j].seq.getAligned());
+                                               
+                                               if (mismatch <= diffs) {
+                                                       //merge
+                                                       alignSeqs[i].names += ',' + alignSeqs[j].names;
+                                                       alignSeqs[i].numIdentical += alignSeqs[j].numIdentical;
+
+                                                       alignSeqs[j].active = 0;
+                                                       alignSeqs[j].numIdentical = 0;
+                                                       count++;
+                                               }
+                                       }//end if j active
+                               }//end if i != j
+                       
+                       //remove from active list 
+                               alignSeqs[i].active = 0;
                                
-                               //remove from active list 
-                               active.erase(itActive);
                        }//end if active i
+                       if(i % 100 == 0)        { m->mothurOut(toString(i) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine(); }
                }
+               
+               if(numSeqs % 100 != 0)  { m->mothurOut(toString(numSeqs) + "\t" + toString(numSeqs - count) + "\t" + toString(count)); m->mothurOutEndLine();   }
        
-               string newFastaFile = getRootName(fastafile) + "precluster" + getExtension(fastafile);
-               string newNamesFile = getRootName(fastafile) + "precluster.names";
                
+               string fileroot = outputDir + m->getRootName(m->getSimpleName(fastafile));
+               
+               string newFastaFile = fileroot + "precluster" + m->getExtension(fastafile);
+               string newNamesFile = fileroot + "precluster.names";
+               
+               if (m->control_pressed) { return 0; }
+               
+               m->mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); m->mothurOutEndLine();
+               m->mothurOut("pre.cluster removed " + toString(count) + " sequences."); m->mothurOutEndLine(); m->mothurOutEndLine(); 
                printData(newFastaFile, newNamesFile);
                
-               mothurOut("Total number of sequences before precluster was " + toString(alignSeqs.size()) + "."); mothurOutEndLine();
-               mothurOut("pre.cluster removed " + toString(count) + " sequences."); mothurOutEndLine(); 
+               m->mothurOut("It took " + toString(time(NULL) - start) + " secs to cluster " + toString(numSeqs) + " sequences."); m->mothurOutEndLine(); 
+               
+               if (m->control_pressed) { remove(newFastaFile.c_str()); remove(newNamesFile.c_str()); return 0; }
+               
+               m->mothurOutEndLine();
+               m->mothurOut("Output File Names: "); m->mothurOutEndLine();
+               m->mothurOut(newFastaFile); m->mothurOutEndLine();      outputNames.push_back(newFastaFile); outputTypes["fasta"].push_back(newFastaFile);
+               m->mothurOut(newNamesFile); m->mothurOutEndLine();      outputNames.push_back(newNamesFile); outputTypes["name"].push_back(newNamesFile);
+               m->mothurOutEndLine();
+               
+               //set fasta file as new current fastafile
+               string current = "";
+               itTypes = outputTypes.find("fasta");
+               if (itTypes != outputTypes.end()) {
+                       if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setFastaFile(current); }
+               }
+               
+               itTypes = outputTypes.find("name");
+               if (itTypes != outputTypes.end()) {
+                       if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setNameFile(current); }
+               }
                
                return 0;
                
        }
        catch(exception& e) {
-               errorOut(e, "PreClusterCommand", "execute");
+               m->errorOut(e, "PreClusterCommand", "execute");
                exit(1);
        }
 }
+
 /**************************************************************************************************/
-int PreClusterCommand::readSeqs(){
+
+//this requires the names and fasta file to be in the same order
+
+int PreClusterCommand::readFASTA(){
        try {
+               //ifstream inNames;
                ifstream inFasta;
-               openInputFile(fastafile, inFasta);
+               
+               //m->openInputFile(namefile, inNames);
+               m->openInputFile(fastafile, inFasta);
+               
+               //string firstCol, secondCol, nameString;
                length = 0;
-               map<string, string>::iterator it;
-                               
+               
                while (!inFasta.eof()) {
-                       Sequence temp(inFasta);  //read seq
                        
-                       if (temp.getName() != "") {  
+                       if (m->control_pressed) { inFasta.close(); return 0; }
+                       
+                       //inNames >> firstCol >> secondCol;
+                       //nameString = secondCol;
+                       
+                       //m->gobble(inNames);
+                       //int size = 1;
+                       //while (secondCol.find_first_of(',') != -1) { 
+                       //      size++;
+                       //      secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
+                       //}
+                       
+                       Sequence seq(inFasta);  m->gobble(inFasta);
+                       
+                       if (seq.getName() != "") {  //can get "" if commented line is at end of fasta file
                                if (namefile != "") {
-                                       //make sure fasta and name files match
-                                       it = names.find(temp.getName());
-                                       if (it == names.end()) { mothurOut(temp.getName() + " is not in your names file, please correct."); mothurOutEndLine(); exit(1); }
-                               }else { sizes[temp.getName()] = 1; }
-                               
-                               seqPNode tempNode(sizes[temp.getName()], temp);
-                               alignSeqs.push_back(tempNode); 
-                               active[temp.getName()] = true;
+                                       itSize = sizes.find(seq.getName());
+                                       
+                                       if (itSize == sizes.end()) { m->mothurOut(seq.getName() + " is not in your names file, please correct."); m->mothurOutEndLine(); exit(1); }
+                                       else{
+                                               seqPNode tempNode(itSize->second, seq, names[seq.getName()]);
+                                               alignSeqs.push_back(tempNode);
+                                               if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
+                                       }       
+                               }else { //no names file, you are identical to yourself 
+                                       seqPNode tempNode(1, seq, seq.getName());
+                                       alignSeqs.push_back(tempNode);
+                                       if (seq.getAligned().length() > length) {  length = seq.getAligned().length();  }
+                               }
                        }
-                       gobble(inFasta);
                }
                inFasta.close();
-               
-               if (alignSeqs.size() != 0) {  length = alignSeqs[0].seq.getAligned().length();  }
-               
+               //inNames.close();
                return alignSeqs.size();
        }
+       
        catch(exception& e) {
-               errorOut(e, "PreClusterCommand", "readSeqs");
-               exit(1);
-       }
-}
-/**************************************************************************************************/
-void PreClusterCommand::readNameFile(){
-       try {
-               ifstream in;
-               openInputFile(namefile, in);
-               string firstCol, secondCol;
-                               
-               while (!in.eof()) {
-                       in >> firstCol >> secondCol; gobble(in);
-                       names[firstCol] = secondCol;
-                       int size = 1;
-                       while (secondCol.find_first_of(',') != -1) { 
-                               size++;
-                               secondCol = secondCol.substr(secondCol.find_first_of(',')+1, secondCol.length());
-                       }
-                       sizes[firstCol] = size;
-               }
-               in.close();
-       }
-       catch(exception& e) {
-               errorOut(e, "PreClusterCommand", "readNameFile");
+               m->errorOut(e, "PreClusterCommand", "readFASTA");
                exit(1);
        }
 }
+
 /**************************************************************************************************/
+
 int PreClusterCommand::calcMisMatches(string seq1, string seq2){
        try {
                int numBad = 0;
@@ -230,27 +328,26 @@ int PreClusterCommand::calcMisMatches(string seq1, string seq2){
                return numBad;
        }
        catch(exception& e) {
-               errorOut(e, "PreClusterCommand", "calcMisMatches");
+               m->errorOut(e, "PreClusterCommand", "calcMisMatches");
                exit(1);
        }
 }
+
 /**************************************************************************************************/
+
 void PreClusterCommand::printData(string newfasta, string newname){
        try {
                ofstream outFasta;
                ofstream outNames;
-               openOutputFile(newfasta, outFasta);
-               openOutputFile(newname, outNames);
+               
+               m->openOutputFile(newfasta, outFasta);
+               m->openOutputFile(newname, outNames);
                                
-               map<string, string>::iterator itNames;
                
                for (int i = 0; i < alignSeqs.size(); i++) {
                        if (alignSeqs[i].numIdentical != 0) {
                                alignSeqs[i].seq.printSequence(outFasta); 
-                               
-                               itNames = names.find(alignSeqs[i].seq.getName());
-                               
-                               outNames << itNames->first << '\t' << itNames->second << endl;
+                               outNames << alignSeqs[i].seq.getName() << '\t' << alignSeqs[i].names << endl;
                        }
                }
                
@@ -259,7 +356,32 @@ void PreClusterCommand::printData(string newfasta, string newname){
                
        }
        catch(exception& e) {
-               errorOut(e, "PreClusterCommand", "printData");
+               m->errorOut(e, "PreClusterCommand", "printData");
+               exit(1);
+       }
+}
+/**************************************************************************************************/
+
+void PreClusterCommand::readNameFile(){
+       try {
+               ifstream in;
+               m->openInputFile(namefile, in);
+               string firstCol, secondCol;
+                               
+               while (!in.eof()) {
+                       in >> firstCol >> secondCol; m->gobble(in);
+                       names[firstCol] = secondCol;
+                       int size = 1;
+
+                       for(int i=0;i<secondCol.size();i++){
+                               if(secondCol[i] == ','){        size++; }
+                       }
+                       sizes[firstCol] = size;
+               }
+               in.close();
+       }
+       catch(exception& e) {
+               m->errorOut(e, "PreClusterCommand", "readNameFile");
                exit(1);
        }
 }