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 /***********************************************************************/
196 inline int openOutputFileAppend(string fileName, ofstream& fileHandle){
198 fileHandle.open(fileName.c_str(), ios::app);
200 cout << "Error: Could not open " << fileName << endl;
208 /***********************************************************************/
210 inline void gobble(istream& f){
213 while(isspace(d=f.get())) {;}
217 /***********************************************************************/
219 inline string getline(ifstream& fileHandle) {
224 while (!fileHandle.eof()) {
226 char c = fileHandle.get();
228 //are you at the end of the line
229 if ((c == '\n') || (c == '\r') || (c == '\f')){ break; }
236 catch(exception& e) {
237 cout << "Error in mothur function getline" << endl;
242 /***********************************************************************/
244 inline bool isTrue(string f){
246 if ((f == "TRUE") || (f == "T") || (f == "true") || (f == "t")) { return true; }
247 else { return false; }
250 /***********************************************************************/
252 inline float roundDist(float dist, int precision){
254 return int(dist * precision + 0.5)/float(precision);
258 /***********************************************************************/
260 inline int getNumNames(string names){
266 for(int i=0;i<names.size();i++){
277 /**************************************************************************************************/
279 inline vector<vector<double> > binomial(int maxOrder){
281 vector<vector<double> > binomial(maxOrder+1);
283 for(int i=0;i<=maxOrder;i++){
284 binomial[i].resize(maxOrder+1);
293 for(int i=2;i<=maxOrder;i++){
297 for(int i=2;i<=maxOrder;i++){
298 for(int j=1;j<=maxOrder;j++){
299 if(i==j){ binomial[i][j]=1; }
300 if(j>i) { binomial[i][j]=0; }
301 else { binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j]; }
308 /***********************************************************************/
310 inline string getRootName(string longName){
312 string rootName = longName;
314 if(longName.find_last_of(".") != longName.npos){
315 int pos = longName.find_last_of('.')+1;
316 rootName = longName.substr(0, pos);
321 /***********************************************************************/
323 inline string getSimpleName(string longName){
325 string simpleName = longName;
328 found=longName.find_last_of("/\\");
330 if(found != longName.npos){
331 simpleName = longName.substr(found+1);
334 //if(longName.find_last_of("/") != longName.npos){
335 // int pos = longName.find_last_of('/')+1;
336 // simpleName = longName.substr(pos, longName.length());
342 /***********************************************************************/
344 inline int factorial(int num){
347 for (int i = 1; i <= num; i++) {
353 /**************************************************************************************************
355 double min(double x, double y)
361 /***********************************************************************/
363 inline string getPathName(string longName){
365 string rootPathName = longName;
367 if(longName.find_last_of("/\\") != longName.npos){
368 int pos = longName.find_last_of("/\\")+1;
369 rootPathName = longName.substr(0, pos);
374 /***********************************************************************/
376 inline string hasPath(string longName){
381 found=longName.find_last_of("/\\");
383 if(found != longName.npos){
384 path = longName.substr(0, found+1);
390 /***********************************************************************/
392 inline string getExtension(string longName){
394 string extension = longName;
396 if(longName.find_last_of('.') != longName.npos){
397 int pos = longName.find_last_of('.');
398 extension = longName.substr(pos, longName.length());
403 /***********************************************************************/
404 inline bool isBlank(string fileName){
407 fileHandle.open(fileName.c_str());
409 cout << "Error: Could not open " << fileName << endl;
412 //check for blank file
414 if (fileHandle.eof()) { fileHandle.close(); return true; }
418 /***********************************************************************/
420 inline string getFullPathName(string fileName){
423 string path = hasPath(fileName);
427 if (path == "") { return fileName; } //its a simple name
428 else { //we need to complete the pathname
429 // ex. ../../../filename
430 // cwd = /user/work/desktop
433 //get current working directory
434 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
435 if (path.rfind("./") == -1) { return fileName; } //already complete name
436 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
438 char* cwdpath = new char[1024];
441 cwdpath=getcwd(cwdpath,size);
447 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
449 //break apart the current working directory
451 while (simpleCWD.find_first_of('/') != -1) {
452 string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
453 simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
456 //get last one // ex. ../../../filename = /user/work/desktop/filename
457 dirs.push_back(simpleCWD); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
460 int index = dirs.size()-1;
462 while((pos = path.rfind("./")) != -1) { //while you don't have a complete path
463 if (path[(pos-1)] == '.') { //you want your parent directory ../
464 path = path.substr(0, pos-1);
466 if (index == 0) { break; }
467 }else if (path[(pos-1)] == '/') { //you want the current working dir ./
468 path = path.substr(0, pos);
469 }else if (pos == 1) { break;
470 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
473 for (int i = index; i >= 0; i--) {
474 newFileName = dirs[i] + "/" + newFileName;
477 newFileName = "/" + newFileName;
481 if (path.rfind(".\\") == -1) { return fileName; } //already complete name
482 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
484 char *cwdpath = NULL;
485 cwdpath = getcwd(NULL, 0); // or _getcwd
486 if ( cwdpath != NULL) { cwd = cwdpath; }
489 //break apart the current working directory
491 while (cwd.find_first_of('\\') != -1) {
492 string dir = cwd.substr(0,cwd.find_first_of('\\'));
493 cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
498 dirs.push_back(cwd); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
500 int index = dirs.size()-1;
502 while((pos = path.rfind(".\\")) != -1) { //while you don't have a complete path
503 if (path[(pos-1)] == '.') { //you want your parent directory ../
504 path = path.substr(0, pos-1);
506 if (index == 0) { break; }
507 }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
508 path = path.substr(0, pos);
509 }else if (pos == 1) { break;
510 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
513 for (int i = index; i >= 0; i--) {
514 newFileName = dirs[i] + "\\" + newFileName;
522 catch(exception& e) {
523 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function getFullPathName. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
527 /***********************************************************************/
529 inline int openInputFile(string fileName, ifstream& fileHandle, string m){
532 string completeFileName = getFullPathName(fileName);
534 fileHandle.open(completeFileName.c_str());
538 //check for blank file
543 /***********************************************************************/
545 inline int openInputFile(string fileName, ifstream& fileHandle){
548 string completeFileName = getFullPathName(fileName);
550 fileHandle.open(completeFileName.c_str());
552 cout << "Error: Could not open " << completeFileName << endl;
556 //check for blank file
558 if (fileHandle.eof()) { cout << completeFileName << " is blank. Please correct." << endl; return 1; }
564 /***********************************************************************/
566 inline int renameFile(string oldName, string newName){
569 int exist = openInputFile(newName, inTest, "");
571 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
572 if (exist == 0) { //you could open it so you want to delete it
574 string command = "rm " + newName;
575 system(command.c_str());
578 string command = "mv " + oldName + " " + newName;
579 system(command.c_str());
581 remove(newName.c_str());
582 int renameOk = rename(oldName.c_str(), newName.c_str());
587 /***********************************************************************/
589 inline int openOutputFile(string fileName, ofstream& fileHandle){
591 string completeFileName = getFullPathName(fileName);
593 fileHandle.open(completeFileName.c_str(), ios::trunc);
595 cout << "Error: Could not open " << completeFileName << endl;
604 /***********************************************************************/
606 inline int getNumSeqs(ifstream& file){
608 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
613 /***********************************************************************/
615 inline bool inVector(string member, vector<string> group){
617 for (int i = 0; i < group.size(); i++) {
618 if (group[i] == member) { return true; }
623 /***********************************************************************/
625 //This function parses the estimator options and puts them in a vector
626 inline void splitAtDash(string& estim, vector<string>& container) {
630 while (estim.find_first_of('-') != -1) {
631 individual = estim.substr(0,estim.find_first_of('-'));
632 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
633 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
634 container.push_back(individual);
638 container.push_back(estim);
640 catch(exception& e) {
641 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
646 /***********************************************************************/
647 //This function parses the label options and puts them in a set
648 inline void splitAtDash(string& estim, set<string>& container) {
652 while (estim.find_first_of('-') != -1) {
653 individual = estim.substr(0,estim.find_first_of('-'));
654 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
655 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
656 container.insert(individual);
660 container.insert(estim);
662 catch(exception& e) {
663 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
667 /***********************************************************************/
668 //This function parses the line options and puts them in a set
669 inline void splitAtDash(string& estim, set<int>& container) {
674 while (estim.find_first_of('-') != -1) {
675 individual = estim.substr(0,estim.find_first_of('-'));
676 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
677 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
678 convert(individual, lineNum); //convert the string to int
679 container.insert(lineNum);
683 convert(estim, lineNum); //convert the string to int
684 container.insert(lineNum);
686 catch(exception& e) {
687 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
691 /***********************************************************************/
692 //This function parses the a string and puts peices in a vector
693 inline void splitAtComma(string& estim, vector<string>& container) {
697 while (estim.find_first_of(',') != -1) {
698 individual = estim.substr(0,estim.find_first_of(','));
699 if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
700 estim = estim.substr(estim.find_first_of(',')+1, estim.length());
701 container.push_back(individual);
705 container.push_back(estim);
707 catch(exception& e) {
708 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtComma. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
712 /***********************************************************************/
714 //This function splits up the various option parameters
715 inline void splitAtComma(string& prefix, string& suffix){
717 prefix = suffix.substr(0,suffix.find_first_of(','));
718 if ((suffix.find_first_of(',')+2) <= suffix.length()) { //checks to make sure you don't have comma at end of string
719 suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
721 while(suffix.at(0) == ' ')
722 suffix = suffix.substr(1, suffix.length());
726 catch(exception& e) {
727 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtComma. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
731 /***********************************************************************/
733 //This function separates the key value from the option value i.e. dist=96_...
734 inline void splitAtEquals(string& key, string& value){
736 if(value.find_first_of('=') != -1){
737 key = value.substr(0,value.find_first_of('='));
738 if ((value.find_first_of('=')+1) <= value.length()) {
739 value = value.substr(value.find_first_of('=')+1, value.length());
746 catch(exception& e) {
747 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtEquals. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
751 /**************************************************************************************************/
753 inline bool inUsersGroups(string groupname, vector<string> Groups) {
755 for (int i = 0; i < Groups.size(); i++) {
756 if (groupname == Groups[i]) { return true; }
760 catch(exception& e) {
761 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function inUsersGroups. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
765 /**************************************************************************************************/
766 //returns true if any of the strings in first vector are in second vector
767 inline bool inUsersGroups(vector<string> groupnames, vector<string> Groups) {
770 for (int i = 0; i < groupnames.size(); i++) {
771 if (inUsersGroups(groupnames[i], Groups)) { return true; }
775 catch(exception& e) {
776 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function inUsersGroups. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
780 /***********************************************************************/
781 //this function determines if the user has given us labels that are smaller than the given label.
782 //if so then it returns true so that the calling function can run the previous valid distance.
783 //it's a "smart" distance function. It also checks for invalid labels.
784 inline bool anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
787 set<string>::iterator it;
788 vector<float> orderFloat;
789 map<string, float> userMap; //the conversion process removes trailing 0's which we need to put back
790 map<string, float>::iterator it2;
792 bool smaller = false;
794 //unique is the smallest line
795 if (label == "unique") { return false; }
796 else { convert(label, labelFloat); }
798 //go through users set and make them floats
799 for(it = userLabels.begin(); it != userLabels.end(); ++it) {
802 if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
804 orderFloat.push_back(temp);
806 }else if (*it == "unique") {
807 orderFloat.push_back(-1.0);
808 userMap["unique"] = -1.0;
810 if (errorOff == "") { cout << *it << " is not a valid label." << endl; }
811 userLabels.erase(*it);
817 sort(orderFloat.begin(), orderFloat.end());
819 /*************************************************/
820 //is this label bigger than any of the users labels
821 /*************************************************/
823 //loop through order until you find a label greater than label
824 for (int i = 0; i < orderFloat.size(); i++) {
825 if (orderFloat[i] < labelFloat) {
827 if (orderFloat[i] == -1) {
828 if (errorOff == "") { cout << "Your file does not include the label unique." << endl; }
829 userLabels.erase("unique");
832 if (errorOff == "") { cout << "Your file does not include the label " << endl; }
834 for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {
835 if (it2->second == orderFloat[i]) {
837 //remove small labels
842 if (errorOff == "") {cout << s << ". I will use the next smallest distance. " << endl; }
844 //since they are sorted once you find a bigger one stop looking
851 catch(exception& e) {
852 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function anyLabelsToProcess. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
857 /**************************************************************************************************/
858 inline void appendFiles(string temp, string filename) {
863 //open output file in append mode
864 openOutputFileAppend(filename, output);
865 openInputFile(temp, input);
867 while(char c = input.get()){
868 if(input.eof()) { break; }
869 else { output << c; }
875 catch(exception& e) {
876 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function appendFiles. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
881 /**************************************************************************************************/
882 inline string sortFile(string distFile){
884 string outfile = getRootName(distFile) + "sorted.dist";
886 //if you can, use the unix sort since its been optimized for years
887 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
888 string command = "sort -n -k +3 " + distFile + " -o " + outfile;
889 system(command.c_str());
890 #else //you are stuck with my best attempt...
891 //windows sort does not have a way to specify a column, only a character in the line
892 //since we cannot assume that the distance will always be at the the same character location on each line
893 //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
895 //read in file line by file and put distance first
896 string tempDistFile = distFile + ".temp";
899 openInputFile(distFile, input);
900 openOutputFile(tempDistFile, output);
902 string firstName, secondName;
905 input >> firstName >> secondName >> dist;
906 output << dist << '\t' << firstName << '\t' << secondName << endl;
913 //sort using windows sort
914 string tempOutfile = outfile + ".temp";
915 string command = "sort " + tempDistFile + " /O " + tempOutfile;
916 system(command.c_str());
918 //read in sorted file and put distance at end again
920 openInputFile(tempOutfile, input2);
921 openOutputFile(outfile, output);
924 input2 >> dist >> firstName >> secondName;
925 output << firstName << '\t' << secondName << '\t' << dist << endl;
932 remove(tempDistFile.c_str());
933 remove(tempOutfile.c_str());
938 catch(exception& e) {
939 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function sortfile. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
943 /**************************************************************************************************/