10 * Created by Sarah Westcott on 2/19/09.
11 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
15 /* This file contains all the standard incudes we use in the project as well as some common utilities. */
50 /***********************************************************************/
52 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
57 #include <readline/readline.h>
58 #include <readline/history.h>
61 //#include <readline/readline.h>
62 //#include <readline/history.h>
64 #include <conio.h> //allows unbuffered screen capture from stdin
65 #include <direct.h> //get cwd
70 #define exp(x) (exp((double) x))
71 #define sqrt(x) (sqrt((double) x))
72 #define log10(x) (log10((double) x))
73 #define log2(x) (log10(x)/log10(2))
74 #define isnan(x) ((x) != (x))
75 #define isinf(x) (fabs(x) == std::numeric_limits<double>::infinity())
77 typedef unsigned long ull;
87 IntNode(int lv, int rv, IntNode* l, IntNode* r) : lvalue(lv), rvalue(rv), left(l), right(r) {};
97 /************************************************************/
101 int smallChild; //used to make linkTable work with list and rabund. represents bin number of this cluster node
102 clusterNode(int num, int par, int kid) : numSeq(num), parent(par), smallChild(kid) {};
104 /************************************************************/
110 seqDist(int s1, int s2, float d) : seq1(s1), seq2(s2), dist(d) {}
113 //********************************************************************************************************************
114 //sorts lowest to highest
115 inline bool compareSequenceDistance(seqDist left, seqDist right){
116 return (left.dist < right.dist);
118 /***********************************************************************/
120 // snagged from http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
121 // works for now, but there should be a way to do it without killing the whole program
123 class BadConversion : public runtime_error {
125 BadConversion(const string& s) : runtime_error(s){ }
128 //**********************************************************************************************************************
131 inline void convert(const string& s, T& x, bool failIfLeftoverChars = true){
134 if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
135 throw BadConversion(s);
138 //**********************************************************************************************************************
141 inline bool convertTestFloat(const string& s, T& x, bool failIfLeftoverChars = true){
144 if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
151 //**********************************************************************************************************************
154 inline bool convertTest(const string& s, T& x, bool failIfLeftoverChars = true){
157 if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
159 cout << "unable to be converted into an integer.\n" << endl;
165 //**********************************************************************************************************************
168 string toString(const T&x){
174 //**********************************************************************************************************************
177 string toHex(const T&x){
184 //**********************************************************************************************************************
187 string toString(const T&x, int i){
191 output << fixed << x;
195 /***********************************************************************/
197 inline int openOutputFileAppend(string fileName, ofstream& fileHandle){
199 fileHandle.open(fileName.c_str(), ios::app);
201 cout << "Error: Could not open " << fileName << endl;
209 /***********************************************************************/
211 inline void gobble(istream& f){
214 while(isspace(d=f.get())) {;}
218 /***********************************************************************/
220 inline string getline(ifstream& fileHandle) {
225 while (!fileHandle.eof()) {
227 char c = fileHandle.get();
229 //are you at the end of the line
230 if ((c == '\n') || (c == '\r') || (c == '\f')){ break; }
237 catch(exception& e) {
238 cout << "Error in mothur function getline" << endl;
243 /**************************************************************************************************/
245 inline void mothurOut(string message) {
248 string logFileName = "mothur.logFile";
249 openOutputFileAppend(logFileName, out);
256 catch(exception& e) {
257 cout << "Error in mothur class mothurOut" << endl;
261 /**************************************************************************************************/
263 inline void mothurOut(string message, string precision) {
266 string logFileName = "mothur.logFile";
267 openOutputFileAppend(logFileName, out);
269 cout << precision << message;
270 out << precision << message;
274 catch(exception& e) {
275 cout << "Error in mothur class mothurOut" << endl;
280 /**************************************************************************************************/
282 inline void mothurOutEndLine() {
285 string logFileName = "mothur.logFile";
286 openOutputFileAppend(logFileName, out);
293 catch(exception& e) {
294 cout << "error in mothur mothurOutEndLine" << endl;
300 /**************************************************************************************************/
302 inline void errorOut(exception& e, string object, string function) {
304 mothurOut("Error: ");
305 mothurOut(toString(e.what()));
306 mothurOut(" has occurred in the " + object + " class function " + function + ". Please contact Pat Schloss at mothur.bugs@gmail.com, and be sure to include the mothur.logFile with your inquiry.");
311 /***********************************************************************/
313 inline bool isTrue(string f){
315 if ((f == "TRUE") || (f == "T") || (f == "true") || (f == "t")) { return true; }
316 else { return false; }
319 /***********************************************************************/
321 inline float roundDist(float dist, int precision){
323 return int(dist * precision + 0.5)/float(precision);
327 /***********************************************************************/
329 inline int getNumNames(string names){
335 for(int i=0;i<names.size();i++){
346 /**************************************************************************************************/
348 inline vector<vector<double> > binomial(int maxOrder){
350 vector<vector<double> > binomial(maxOrder+1);
352 for(int i=0;i<=maxOrder;i++){
353 binomial[i].resize(maxOrder+1);
362 for(int i=2;i<=maxOrder;i++){
366 for(int i=2;i<=maxOrder;i++){
367 for(int j=1;j<=maxOrder;j++){
368 if(i==j){ binomial[i][j]=1; }
369 if(j>i) { binomial[i][j]=0; }
370 else { binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j]; }
377 /***********************************************************************/
379 inline string getRootName(string longName){
381 string rootName = longName;
383 if(longName.find_last_of(".") != longName.npos){
384 int pos = longName.find_last_of('.')+1;
385 rootName = longName.substr(0, pos);
390 /***********************************************************************/
392 inline string getSimpleName(string longName){
394 string simpleName = longName;
397 found=longName.find_last_of("/\\");
399 if(found != longName.npos){
400 simpleName = longName.substr(found+1);
403 //if(longName.find_last_of("/") != longName.npos){
404 // int pos = longName.find_last_of('/')+1;
405 // simpleName = longName.substr(pos, longName.length());
411 /***********************************************************************/
413 inline int factorial(int num){
416 for (int i = 1; i <= num; i++) {
422 /**************************************************************************************************
424 double min(double x, double y)
430 /***********************************************************************/
432 inline string getPathName(string longName){
434 string rootPathName = longName;
436 if(longName.find_last_of("/\\") != longName.npos){
437 int pos = longName.find_last_of("/\\")+1;
438 rootPathName = longName.substr(0, pos);
443 /***********************************************************************/
445 inline string hasPath(string longName){
450 found=longName.find_last_of("/\\");
452 if(found != longName.npos){
453 path = longName.substr(0, found+1);
459 /***********************************************************************/
461 inline string getExtension(string longName){
463 string extension = longName;
465 if(longName.find_last_of('.') != longName.npos){
466 int pos = longName.find_last_of('.');
467 extension = longName.substr(pos, longName.length());
472 /***********************************************************************/
473 inline bool isBlank(string fileName){
476 fileHandle.open(fileName.c_str());
478 mothurOut("Error: Could not open " + fileName); mothurOutEndLine();
481 //check for blank file
483 if (fileHandle.eof()) { fileHandle.close(); return true; }
487 /***********************************************************************/
489 inline string getFullPathName(string fileName){
491 string path = hasPath(fileName);
495 if (path == "") { return fileName; } //its a simple name
496 else { //we need to complete the pathname
497 // ex. ../../../filename
498 // cwd = /user/work/desktop
501 //get current working directory
502 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
503 if (path.rfind("./") == -1) { return fileName; } //already complete name
504 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
506 char* cwdpath = new char[1024];
509 cwdpath=getcwd(cwdpath,size);
515 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
517 //break apart the current working directory
519 while (simpleCWD.find_first_of('/') != -1) {
520 string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
521 simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
524 //get last one // ex. ../../../filename = /user/work/desktop/filename
525 dirs.push_back(simpleCWD); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
528 int index = dirs.size()-1;
530 while((pos = path.rfind("./")) != -1) { //while you don't have a complete path
531 if (path[(pos-1)] == '.') { //you want your parent directory ../
532 path = path.substr(0, pos-1);
534 if (index == 0) { break; }
535 }else if (path[(pos-1)] == '/') { //you want the current working dir ./
536 path = path.substr(0, pos);
537 }else if (pos == 1) { break;
538 }else { mothurOut("cannot resolve path for " + fileName); mothurOutEndLine(); return fileName; }
541 for (int i = index; i >= 0; i--) {
542 newFileName = dirs[i] + "/" + newFileName;
545 newFileName = "/" + newFileName;
549 if (path.rfind(".\\") == -1) { return fileName; } //already complete name
550 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
552 char *cwdpath = NULL;
553 cwdpath = getcwd(NULL, 0); // or _getcwd
554 if ( cwdpath != NULL) { cwd = cwdpath; }
557 //break apart the current working directory
559 while (cwd.find_first_of('\\') != -1) {
560 string dir = cwd.substr(0,cwd.find_first_of('\\'));
561 cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
566 dirs.push_back(cwd); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
568 int index = dirs.size()-1;
570 while((pos = path.rfind(".\\")) != -1) { //while you don't have a complete path
571 if (path[(pos-1)] == '.') { //you want your parent directory ../
572 path = path.substr(0, pos-1);
574 if (index == 0) { break; }
575 }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
576 path = path.substr(0, pos);
577 }else if (pos == 1) { break;
578 }else { mothurOut("cannot resolve path for " + fileName); mothurOutEndLine(); return fileName; }
581 for (int i = index; i >= 0; i--) {
582 newFileName = dirs[i] + "\\" + newFileName;
590 catch(exception& e) {
591 errorOut(e, "getFullPathName", "getFullPathName");
597 /***********************************************************************/
599 inline int openInputFile(string fileName, ifstream& fileHandle, string m){
602 string completeFileName = getFullPathName(fileName);
604 fileHandle.open(completeFileName.c_str());
608 //check for blank file
613 /***********************************************************************/
615 inline int openInputFile(string fileName, ifstream& fileHandle){
617 string completeFileName = getFullPathName(fileName);
619 fileHandle.open(completeFileName.c_str());
621 mothurOut("Error: Could not open " + completeFileName); mothurOutEndLine();
625 //check for blank file
627 if (fileHandle.eof()) { mothurOut(completeFileName + " is blank. Please correct."); mothurOutEndLine(); return 1; }
633 /***********************************************************************/
635 inline int renameFile(string oldName, string newName){
638 int exist = openInputFile(newName, inTest, "");
640 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
641 if (exist == 0) { //you could open it so you want to delete it
643 string command = "rm " + newName;
644 system(command.c_str());
647 string command = "mv " + oldName + " " + newName;
648 system(command.c_str());
650 remove(newName.c_str());
651 int renameOk = rename(oldName.c_str(), newName.c_str());
656 /***********************************************************************/
658 inline int openOutputFile(string fileName, ofstream& fileHandle){
660 string completeFileName = getFullPathName(fileName);
662 fileHandle.open(completeFileName.c_str(), ios::trunc);
664 mothurOut("Error: Could not open " + completeFileName); mothurOutEndLine();
673 /***********************************************************************/
675 inline int getNumSeqs(ifstream& file){
677 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
682 /***********************************************************************/
684 inline bool inVector(string member, vector<string> group){
686 for (int i = 0; i < group.size(); i++) {
687 if (group[i] == member) { return true; }
692 /***********************************************************************/
694 //This function parses the estimator options and puts them in a vector
695 inline void splitAtDash(string& estim, vector<string>& container) {
699 while (estim.find_first_of('-') != -1) {
700 individual = estim.substr(0,estim.find_first_of('-'));
701 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
702 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
703 container.push_back(individual);
707 container.push_back(estim);
709 catch(exception& e) {
710 errorOut(e, "mothur", "splitAtDash");
715 /***********************************************************************/
716 //This function parses the label options and puts them in a set
717 inline void splitAtDash(string& estim, set<string>& container) {
721 while (estim.find_first_of('-') != -1) {
722 individual = estim.substr(0,estim.find_first_of('-'));
723 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
724 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
725 container.insert(individual);
729 container.insert(estim);
731 catch(exception& e) {
732 errorOut(e, "mothur", "splitAtDash");
736 /***********************************************************************/
737 //This function parses the line options and puts them in a set
738 inline void splitAtDash(string& estim, set<int>& container) {
743 while (estim.find_first_of('-') != -1) {
744 individual = estim.substr(0,estim.find_first_of('-'));
745 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
746 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
747 convert(individual, lineNum); //convert the string to int
748 container.insert(lineNum);
752 convert(estim, lineNum); //convert the string to int
753 container.insert(lineNum);
755 catch(exception& e) {
756 errorOut(e, "mothur", "splitAtDash");
760 /***********************************************************************/
761 //This function parses the a string and puts peices in a vector
762 inline void splitAtComma(string& estim, vector<string>& container) {
766 while (estim.find_first_of(',') != -1) {
767 individual = estim.substr(0,estim.find_first_of(','));
768 if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
769 estim = estim.substr(estim.find_first_of(',')+1, estim.length());
770 container.push_back(individual);
774 container.push_back(estim);
776 catch(exception& e) {
777 errorOut(e, "mothur", "splitAtComma");
781 /***********************************************************************/
783 //This function splits up the various option parameters
784 inline void splitAtComma(string& prefix, string& suffix){
786 prefix = suffix.substr(0,suffix.find_first_of(','));
787 if ((suffix.find_first_of(',')+2) <= suffix.length()) { //checks to make sure you don't have comma at end of string
788 suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
790 while(suffix.at(0) == ' ')
791 suffix = suffix.substr(1, suffix.length());
795 catch(exception& e) {
796 errorOut(e, "mothur", "splitAtComma");
800 /***********************************************************************/
802 //This function separates the key value from the option value i.e. dist=96_...
803 inline void splitAtEquals(string& key, string& value){
805 if(value.find_first_of('=') != -1){
806 key = value.substr(0,value.find_first_of('='));
807 if ((value.find_first_of('=')+1) <= value.length()) {
808 value = value.substr(value.find_first_of('=')+1, value.length());
815 catch(exception& e) {
816 errorOut(e, "mothur", "splitAtEquals");
820 /**************************************************************************************************/
822 inline bool inUsersGroups(string groupname, vector<string> Groups) {
824 for (int i = 0; i < Groups.size(); i++) {
825 if (groupname == Groups[i]) { return true; }
829 catch(exception& e) {
830 errorOut(e, "mothur", "inUsersGroups");
835 /**************************************************************************************************/
837 inline void mothurOutJustToLog(string message) {
840 string logFileName = "mothur.logFile";
841 openOutputFileAppend(logFileName, out);
847 catch(exception& e) {
848 errorOut(e, "mothur", "mothurOutJustToLog");
854 /**************************************************************************************************/
856 inline void mothurOut(float num) {
859 string logFileName = "mothur.logFile";
860 openOutputFileAppend(logFileName, out);
867 catch(exception& e) {
868 cout << "Error in mothur class mothurOut float" << endl;
872 /***********************************************************************/
873 inline void mothurOut(double value) {
876 string logFileName = "mothur.logFile";
877 openOutputFileAppend(logFileName, out);
884 catch(exception& e) {
885 cout << "Error in mothur class mothurOut double" << endl;
890 /***********************************************************************/
891 //this function determines if the user has given us labels that are smaller than the given label.
892 //if so then it returns true so that the calling function can run the previous valid distance.
893 //it's a "smart" distance function. It also checks for invalid labels.
894 inline bool anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
896 set<string>::iterator it;
897 vector<float> orderFloat;
898 map<string, float> userMap; //the conversion process removes trailing 0's which we need to put back
899 map<string, float>::iterator it2;
901 bool smaller = false;
903 //unique is the smallest line
904 if (label == "unique") { return false; }
905 else { convert(label, labelFloat); }
907 //go through users set and make them floats
908 for(it = userLabels.begin(); it != userLabels.end(); ++it) {
911 if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
913 orderFloat.push_back(temp);
915 }else if (*it == "unique") {
916 orderFloat.push_back(-1.0);
917 userMap["unique"] = -1.0;
919 if (errorOff == "") { mothurOut(*it + " is not a valid label."); mothurOutEndLine(); }
920 userLabels.erase(*it);
926 sort(orderFloat.begin(), orderFloat.end());
928 /*************************************************/
929 //is this label bigger than any of the users labels
930 /*************************************************/
932 //loop through order until you find a label greater than label
933 for (int i = 0; i < orderFloat.size(); i++) {
934 if (orderFloat[i] < labelFloat) {
936 if (orderFloat[i] == -1) {
937 if (errorOff == "") { mothurOut("Your file does not include the label unique."); mothurOutEndLine(); }
938 userLabels.erase("unique");
941 if (errorOff == "") { mothurOut("Your file does not include the label "); mothurOutEndLine(); }
943 for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {
944 if (it2->second == orderFloat[i]) {
946 //remove small labels
951 if (errorOff == "") { mothurOut(s + ". I will use the next smallest distance. "); mothurOutEndLine(); }
953 //since they are sorted once you find a bigger one stop looking
960 catch(exception& e) {
961 errorOut(e, "mothur", "anyLabelsToProcess");
966 /**************************************************************************************************/
967 inline void appendFiles(string temp, string filename) {
972 //open output file in append mode
973 openOutputFileAppend(filename, output);
974 openInputFile(temp, input);
976 while(char c = input.get()){
977 if(input.eof()) { break; }
978 else { output << c; }
984 catch(exception& e) {
985 errorOut(e, "mothur", "appendFiles");
990 /**************************************************************************************************/
991 inline string sortFile(string distFile){
993 string outfile = getRootName(distFile) + "sorted.dist";
995 //if you can, use the unix sort since its been optimized for years
996 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
997 string command = "sort -n -k +3 " + distFile + " -o " + outfile;
998 system(command.c_str());
999 #else //you are stuck with my best attempt...
1000 //windows sort does not have a way to specify a column, only a character in the line
1001 //since we cannot assume that the distance will always be at the the same character location on each line
1002 //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
1004 //read in file line by file and put distance first
1005 string tempDistFile = distFile + ".temp";
1008 openInputFile(distFile, input);
1009 openOutputFile(tempDistFile, output);
1011 string firstName, secondName;
1014 input >> firstName >> secondName >> dist;
1015 output << dist << '\t' << firstName << '\t' << secondName << endl;
1022 //sort using windows sort
1023 string tempOutfile = outfile + ".temp";
1024 string command = "sort " + tempDistFile + " /O " + tempOutfile;
1025 system(command.c_str());
1027 //read in sorted file and put distance at end again
1029 openInputFile(tempOutfile, input2);
1030 openOutputFile(outfile, output);
1033 input2 >> dist >> firstName >> secondName;
1034 output << firstName << '\t' << secondName << '\t' << dist << endl;
1041 remove(tempDistFile.c_str());
1042 remove(tempOutfile.c_str());
1047 catch(exception& e) {
1048 errorOut(e, "mothur", "sortFile");
1052 /**************************************************************************************************/