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. */
53 /***********************************************************************/
55 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
60 #include <readline/readline.h>
61 #include <readline/history.h>
65 #include <conio.h> //allows unbuffered screen capture from stdin
66 #include <direct.h> //get cwd
71 #define exp(x) (exp((double) x))
72 #define sqrt(x) (sqrt((double) x))
73 #define log10(x) (log10((double) x))
74 #define log2(x) (log10(x)/log10(2))
75 #define isnan(x) ((x) != (x))
76 #define isinf(x) (fabs(x) == std::numeric_limits<double>::infinity())
78 typedef unsigned long ull;
88 IntNode(int lv, int rv, IntNode* l, IntNode* r) : lvalue(lv), rvalue(rv), left(l), right(r) {};
98 /************************************************************/
102 int smallChild; //used to make linkTable work with list and rabund. represents bin number of this cluster node
103 clusterNode(int num, int par, int kid) : numSeq(num), parent(par), smallChild(kid) {};
105 /************************************************************/
111 seqDist(int s1, int s2, float d) : seq1(s1), seq2(s2), dist(d) {}
114 //********************************************************************************************************************
115 //sorts lowest to highest
116 inline bool compareSequenceDistance(seqDist left, seqDist right){
117 return (left.dist < right.dist);
119 /***********************************************************************/
121 // snagged from http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
122 // works for now, but there should be a way to do it without killing the whole program
124 class BadConversion : public runtime_error {
126 BadConversion(const string& s) : runtime_error(s){ }
129 //**********************************************************************************************************************
132 inline void convert(const string& s, T& x, bool failIfLeftoverChars = true){
135 if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
136 throw BadConversion(s);
139 //**********************************************************************************************************************
142 inline bool convertTestFloat(const string& s, T& x, bool failIfLeftoverChars = true){
145 if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
152 //**********************************************************************************************************************
155 inline bool convertTest(const string& s, T& x, bool failIfLeftoverChars = true){
158 if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
160 cout << "unable to be converted into an integer.\n" << endl;
166 //**********************************************************************************************************************
169 string toString(const T&x){
175 //**********************************************************************************************************************
178 string toHex(const T&x){
185 //**********************************************************************************************************************
188 string toString(const T&x, int i){
192 output << fixed << x;
196 /***********************************************************************/
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 bool isTrue(string f){
247 if ((f == "TRUE") || (f == "T") || (f == "true") || (f == "t")) { return true; }
248 else { return false; }
251 /***********************************************************************/
253 inline float roundDist(float dist, int precision){
255 return int(dist * precision + 0.5)/float(precision);
258 /***********************************************************************/
260 inline float ceilDist(float dist, int precision){
262 return int(ceil(dist * precision))/float(precision);
266 /***********************************************************************/
268 inline int getNumNames(string names){
274 for(int i=0;i<names.size();i++){
285 /**************************************************************************************************/
287 inline vector<vector<double> > binomial(int maxOrder){
289 vector<vector<double> > binomial(maxOrder+1);
291 for(int i=0;i<=maxOrder;i++){
292 binomial[i].resize(maxOrder+1);
301 for(int i=2;i<=maxOrder;i++){
305 for(int i=2;i<=maxOrder;i++){
306 for(int j=1;j<=maxOrder;j++){
307 if(i==j){ binomial[i][j]=1; }
308 if(j>i) { binomial[i][j]=0; }
309 else { binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j]; }
316 /***********************************************************************/
318 inline string getRootName(string longName){
320 string rootName = longName;
322 if(longName.find_last_of(".") != longName.npos){
323 int pos = longName.find_last_of('.')+1;
324 rootName = longName.substr(0, pos);
329 /***********************************************************************/
331 inline string getSimpleName(string longName){
333 string simpleName = longName;
336 found=longName.find_last_of("/\\");
338 if(found != longName.npos){
339 simpleName = longName.substr(found+1);
342 //if(longName.find_last_of("/") != longName.npos){
343 // int pos = longName.find_last_of('/')+1;
344 // simpleName = longName.substr(pos, longName.length());
350 /***********************************************************************/
352 inline int factorial(int num){
355 for (int i = 1; i <= num; i++) {
361 /**************************************************************************************************
363 double min(double x, double y)
369 /***********************************************************************/
371 inline string getPathName(string longName){
373 string rootPathName = longName;
375 if(longName.find_last_of("/\\") != longName.npos){
376 int pos = longName.find_last_of("/\\")+1;
377 rootPathName = longName.substr(0, pos);
382 /***********************************************************************/
384 inline string hasPath(string longName){
389 found=longName.find_last_of("~/\\");
391 if(found != longName.npos){
392 path = longName.substr(0, found+1);
398 /***********************************************************************/
400 inline string getExtension(string longName){
402 string extension = longName;
404 if(longName.find_last_of('.') != longName.npos){
405 int pos = longName.find_last_of('.');
406 extension = longName.substr(pos, longName.length());
411 /***********************************************************************/
412 inline bool isBlank(string fileName){
415 fileHandle.open(fileName.c_str());
417 cout << "Error: Could not open " << fileName << endl;
420 //check for blank file
422 if (fileHandle.eof()) { fileHandle.close(); return true; }
426 /***********************************************************************/
428 inline string getFullPathName(string fileName){
431 string path = hasPath(fileName);
435 if (path == "") { return fileName; } //its a simple name
436 else { //we need to complete the pathname
437 // ex. ../../../filename
438 // cwd = /user/work/desktop
441 //get current working directory
442 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
444 if (path.find("~") != -1) { //go to home directory
445 string homeDir = getenv ("HOME");
446 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
449 if (path.rfind("./") == -1) { return fileName; } //already complete name
450 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
452 char* cwdpath = new char[1024];
455 cwdpath=getcwd(cwdpath,size);
461 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
463 //break apart the current working directory
465 while (simpleCWD.find_first_of('/') != -1) {
466 string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
467 simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
470 //get last one // ex. ../../../filename = /user/work/desktop/filename
471 dirs.push_back(simpleCWD); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
474 int index = dirs.size()-1;
476 while((pos = path.rfind("./")) != -1) { //while you don't have a complete path
477 if (pos == 0) { break; //you are at the end
478 }else if (path[(pos-1)] == '.') { //you want your parent directory ../
479 path = path.substr(0, pos-1);
481 if (index == 0) { break; }
482 }else if (path[(pos-1)] == '/') { //you want the current working dir ./
483 path = path.substr(0, pos);
484 }else if (pos == 1) { break; //you are at the end
485 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
488 for (int i = index; i >= 0; i--) {
489 newFileName = dirs[i] + "/" + newFileName;
492 newFileName = "/" + newFileName;
496 if (path.find("~") != -1) { //go to home directory
497 string homeDir = getenv ("HOMEPATH");
498 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
501 if (path.rfind(".\\") == -1) { return fileName; } //already complete name
502 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
504 char *cwdpath = NULL;
505 cwdpath = getcwd(NULL, 0); // or _getcwd
506 if ( cwdpath != NULL) { cwd = cwdpath; }
509 //break apart the current working directory
511 while (cwd.find_first_of('\\') != -1) {
512 string dir = cwd.substr(0,cwd.find_first_of('\\'));
513 cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
518 dirs.push_back(cwd); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
520 int index = dirs.size()-1;
522 while((pos = path.rfind(".\\")) != -1) { //while you don't have a complete path
523 if (pos == 0) { break; //you are at the end
524 }else if (path[(pos-1)] == '.') { //you want your parent directory ../
525 path = path.substr(0, pos-1);
527 if (index == 0) { break; }
528 }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
529 path = path.substr(0, pos);
530 }else if (pos == 1) { break; //you are at the end
531 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
534 for (int i = index; i >= 0; i--) {
535 newFileName = dirs[i] + "\\" + newFileName;
544 catch(exception& e) {
545 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function getFullPathName. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
549 /***********************************************************************/
551 inline int openInputFile(string fileName, ifstream& fileHandle, string m){
554 string completeFileName = getFullPathName(fileName);
556 fileHandle.open(completeFileName.c_str());
560 //check for blank file
565 /***********************************************************************/
567 inline int openInputFile(string fileName, ifstream& fileHandle){
570 string completeFileName = getFullPathName(fileName);
572 fileHandle.open(completeFileName.c_str());
574 cout << "Error: Could not open " << completeFileName << endl;
578 //check for blank file
580 if (fileHandle.eof()) { cout << completeFileName << " is blank. Please correct." << endl; return 1; }
586 /***********************************************************************/
588 inline int renameFile(string oldName, string newName){
591 int exist = openInputFile(newName, inTest, "");
593 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
594 if (exist == 0) { //you could open it so you want to delete it
596 string command = "rm " + newName;
597 system(command.c_str());
600 string command = "mv " + oldName + " " + newName;
601 system(command.c_str());
603 remove(newName.c_str());
604 int renameOk = rename(oldName.c_str(), newName.c_str());
609 /***********************************************************************/
611 inline int openOutputFile(string fileName, ofstream& fileHandle){
613 string completeFileName = getFullPathName(fileName);
615 fileHandle.open(completeFileName.c_str(), ios::trunc);
617 cout << "Error: Could not open " << completeFileName << endl;
626 /***********************************************************************/
628 inline int getNumSeqs(ifstream& file){
630 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
635 /***********************************************************************/
637 inline bool inVector(string member, vector<string> group){
639 for (int i = 0; i < group.size(); i++) {
640 if (group[i] == member) { return true; }
645 /***********************************************************************/
647 //This function parses the estimator options and puts them in a vector
648 inline void splitAtDash(string& estim, vector<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.push_back(individual);
660 container.push_back(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";
668 /***********************************************************************/
669 //This function parses the label options and puts them in a set
670 inline void splitAtDash(string& estim, set<string>& 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 container.insert(individual);
682 container.insert(estim);
684 catch(exception& e) {
685 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
689 /***********************************************************************/
690 //This function parses the line options and puts them in a set
691 inline void splitAtDash(string& estim, set<int>& container) {
696 while (estim.find_first_of('-') != -1) {
697 individual = estim.substr(0,estim.find_first_of('-'));
698 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
699 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
700 convert(individual, lineNum); //convert the string to int
701 container.insert(lineNum);
705 convert(estim, lineNum); //convert the string to int
706 container.insert(lineNum);
708 catch(exception& e) {
709 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtDash. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
713 /***********************************************************************/
714 //This function parses the a string and puts peices in a vector
715 inline void splitAtComma(string& estim, vector<string>& container) {
719 while (estim.find_first_of(',') != -1) {
720 individual = estim.substr(0,estim.find_first_of(','));
721 if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
722 estim = estim.substr(estim.find_first_of(',')+1, estim.length());
723 container.push_back(individual);
727 container.push_back(estim);
729 catch(exception& e) {
730 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtComma. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
734 /***********************************************************************/
736 //This function splits up the various option parameters
737 inline void splitAtComma(string& prefix, string& suffix){
739 prefix = suffix.substr(0,suffix.find_first_of(','));
740 if ((suffix.find_first_of(',')+2) <= suffix.length()) { //checks to make sure you don't have comma at end of string
741 suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
743 while(suffix.at(0) == ' ')
744 suffix = suffix.substr(1, suffix.length());
748 catch(exception& e) {
749 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtComma. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
753 /***********************************************************************/
755 //This function separates the key value from the option value i.e. dist=96_...
756 inline void splitAtEquals(string& key, string& value){
758 if(value.find_first_of('=') != -1){
759 key = value.substr(0,value.find_first_of('='));
760 if ((value.find_first_of('=')+1) <= value.length()) {
761 value = value.substr(value.find_first_of('=')+1, value.length());
768 catch(exception& e) {
769 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function splitAtEquals. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
773 /**************************************************************************************************/
775 inline bool inUsersGroups(string groupname, vector<string> Groups) {
777 for (int i = 0; i < Groups.size(); i++) {
778 if (groupname == Groups[i]) { return true; }
782 catch(exception& e) {
783 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function inUsersGroups. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
787 /**************************************************************************************************/
788 //returns true if any of the strings in first vector are in second vector
789 inline bool inUsersGroups(vector<string> groupnames, vector<string> Groups) {
792 for (int i = 0; i < groupnames.size(); i++) {
793 if (inUsersGroups(groupnames[i], Groups)) { return true; }
797 catch(exception& e) {
798 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function inUsersGroups. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
802 /***********************************************************************/
803 //this function determines if the user has given us labels that are smaller than the given label.
804 //if so then it returns true so that the calling function can run the previous valid distance.
805 //it's a "smart" distance function. It also checks for invalid labels.
806 inline bool anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
809 set<string>::iterator it;
810 vector<float> orderFloat;
811 map<string, float> userMap; //the conversion process removes trailing 0's which we need to put back
812 map<string, float>::iterator it2;
814 bool smaller = false;
816 //unique is the smallest line
817 if (label == "unique") { return false; }
818 else { convert(label, labelFloat); }
820 //go through users set and make them floats
821 for(it = userLabels.begin(); it != userLabels.end(); ++it) {
824 if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
826 orderFloat.push_back(temp);
828 }else if (*it == "unique") {
829 orderFloat.push_back(-1.0);
830 userMap["unique"] = -1.0;
832 if (errorOff == "") { cout << *it << " is not a valid label." << endl; }
833 userLabels.erase(*it);
839 sort(orderFloat.begin(), orderFloat.end());
841 /*************************************************/
842 //is this label bigger than any of the users labels
843 /*************************************************/
845 //loop through order until you find a label greater than label
846 for (int i = 0; i < orderFloat.size(); i++) {
847 if (orderFloat[i] < labelFloat) {
849 if (orderFloat[i] == -1) {
850 if (errorOff == "") { cout << "Your file does not include the label unique." << endl; }
851 userLabels.erase("unique");
854 if (errorOff == "") { cout << "Your file does not include the label " << endl; }
856 for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {
857 if (it2->second == orderFloat[i]) {
859 //remove small labels
864 if (errorOff == "") {cout << s << ". I will use the next smallest distance. " << endl; }
866 //since they are sorted once you find a bigger one stop looking
873 catch(exception& e) {
874 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function anyLabelsToProcess. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
879 /**************************************************************************************************/
880 inline void appendFiles(string temp, string filename) {
885 //open output file in append mode
886 openOutputFileAppend(filename, output);
887 int ableToOpen = openInputFile(temp, input, "no error");
889 if (ableToOpen == 0) { //you opened it
890 while(char c = input.get()){
891 if(input.eof()) { break; }
892 else { output << c; }
899 catch(exception& e) {
900 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function appendFiles. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
905 /**************************************************************************************************/
906 inline string sortFile(string distFile, string outputDir){
909 //if (outputDir == "") { outputDir += hasPath(distFile); }
910 string outfile = getRootName(distFile) + "sorted.dist";
913 //if you can, use the unix sort since its been optimized for years
914 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
915 string command = "sort -n -k +3 " + distFile + " -o " + outfile;
916 system(command.c_str());
917 #else //you are stuck with my best attempt...
918 //windows sort does not have a way to specify a column, only a character in the line
919 //since we cannot assume that the distance will always be at the the same character location on each line
920 //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
922 //read in file line by file and put distance first
923 string tempDistFile = distFile + ".temp";
926 openInputFile(distFile, input);
927 openOutputFile(tempDistFile, output);
929 string firstName, secondName;
932 input >> firstName >> secondName >> dist;
933 output << dist << '\t' << firstName << '\t' << secondName << endl;
940 //sort using windows sort
941 string tempOutfile = outfile + ".temp";
942 string command = "sort " + tempDistFile + " /O " + tempOutfile;
943 system(command.c_str());
945 //read in sorted file and put distance at end again
947 openInputFile(tempOutfile, input2);
948 openOutputFile(outfile, output);
951 input2 >> dist >> firstName >> secondName;
952 output << firstName << '\t' << secondName << '\t' << dist << endl;
959 remove(tempDistFile.c_str());
960 remove(tempOutfile.c_str());
965 catch(exception& e) {
966 cout << "Standard Error: " << e.what() << " has occurred in the mothur.h function sortfile. Please contact Pat Schloss at mothur.bugs@gmail.com." << "\n";
970 /**************************************************************************************************/
971 inline vector<long> setFilePosFasta(string filename, int& num) {
973 vector<long> positions;
975 openInputFile(filename, inFASTA);
978 while(!inFASTA.eof()){
979 input = getline(inFASTA); gobble(inFASTA);
980 if (input.length() != 0) {
981 if(input[0] == '>'){ long pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
986 num = positions.size();
991 //get num bytes in file
992 pFile = fopen (filename.c_str(),"rb");
993 if (pFile==NULL) perror ("Error opening file");
995 fseek (pFile, 0, SEEK_END);
1000 long size = positions[(positions.size()-1)];
1002 openInputFile(filename, in);
1006 while(char c = in.get()){
1007 if(in.eof()) { break; }
1012 positions.push_back(size);
1016 /**************************************************************************************************/
1017 inline vector<long> setFilePosEachLine(string filename, int& num) {
1019 vector<long> positions;
1021 openInputFile(filename, in);
1025 long lastpos = in.tellg();
1026 input = getline(in); gobble(in);
1027 if (input.length() != 0) {
1028 long pos = in.tellg();
1029 if (pos != -1) { positions.push_back(pos - input.length() - 1); }
1030 else { positions.push_back(lastpos); }
1035 num = positions.size();
1040 //get num bytes in file
1041 pFile = fopen (filename.c_str(),"rb");
1042 if (pFile==NULL) perror ("Error opening file");
1044 fseek (pFile, 0, SEEK_END);
1049 positions.push_back(size);
1054 /**************************************************************************************************/