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. */
49 /***********************************************************************/
51 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
56 #include <readline/readline.h>
57 #include <readline/history.h>
60 //#include <readline/readline.h>
61 //#include <readline/history.h>
63 #include <conio.h> //allows unbuffered screen capture from stdin
68 #define exp(x) (exp((double) x))
69 #define sqrt(x) (sqrt((double) x))
70 #define log10(x) (log10((double) x))
71 #define log2(x) (log10(x)/log10(2))
72 #define isnan(x) ((x) != (x))
73 #define isinf(x) (fabs(x) == std::numeric_limits<double>::infinity())
76 typedef unsigned long ull;
86 IntNode(int lv, int rv, IntNode* l, IntNode* r) : lvalue(lv), rvalue(rv), left(l), right(r) {};
96 /************************************************************/
100 int smallChild; //used to make linkTable work with list and rabund. represents bin number of this cluster node
101 clusterNode(int num, int par, int kid) : numSeq(num), parent(par), smallChild(kid) {};
103 /************************************************************/
109 seqDist(int s1, int s2, float d) : seq1(s1), seq2(s2), dist(d) {}
112 /***********************************************************************/
114 // snagged from http://www.parashift.com/c++-faq-lite/misc-technical-issues.html#faq-39.2
115 // works for now, but there should be a way to do it without killing the whole program
117 class BadConversion : public runtime_error {
119 BadConversion(const string& s) : runtime_error(s){ }
122 //**********************************************************************************************************************
125 inline void convert(const string& s, T& x, bool failIfLeftoverChars = true){
128 if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
129 throw BadConversion(s);
132 //**********************************************************************************************************************
135 inline bool convertTestFloat(const string& s, T& x, bool failIfLeftoverChars = true){
138 if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
145 //**********************************************************************************************************************
148 inline bool convertTest(const string& s, T& x, bool failIfLeftoverChars = true){
151 if (!(i >> x) || (failIfLeftoverChars && i.get(c)))
153 cout << "unable to be converted into an integer.\n" << endl;
159 //**********************************************************************************************************************
162 string toString(const T&x){
168 //**********************************************************************************************************************
171 string toHex(const T&x){
178 //**********************************************************************************************************************
181 string toString(const T&x, int i){
185 output << fixed << x;
189 /***********************************************************************/
191 inline int openOutputFileAppend(string fileName, ofstream& fileHandle){
193 fileHandle.open(fileName.c_str(), ios::app);
195 cout << "Error: Could not open " << fileName << endl;
203 /***********************************************************************/
205 inline void gobble(istream& f){
208 while(isspace(d=f.get())) {;}
212 /***********************************************************************/
214 inline string getline(ifstream& fileHandle) {
219 while (!fileHandle.eof()) {
221 char c = fileHandle.get();
223 //are you at the end of the line
224 if ((c == '\n') || (c == '\r') || (c == '\f')){ break; }
231 catch(exception& e) {
232 cout << "Error in mothur function getline" << endl;
237 /**************************************************************************************************/
239 inline void mothurOut(string message) {
242 string logFileName = "mothur.logFile";
243 openOutputFileAppend(logFileName, out);
250 catch(exception& e) {
251 cout << "Error in mothur class mothurOut" << endl;
255 /**************************************************************************************************/
257 inline void mothurOut(string message, string precision) {
260 string logFileName = "mothur.logFile";
261 openOutputFileAppend(logFileName, out);
263 cout << precision << message;
264 out << precision << message;
268 catch(exception& e) {
269 cout << "Error in mothur class mothurOut" << endl;
274 /**************************************************************************************************/
276 inline void mothurOutEndLine() {
279 string logFileName = "mothur.logFile";
280 openOutputFileAppend(logFileName, out);
287 catch(exception& e) {
288 cout << "error in mothur mothurOutEndLine" << endl;
294 /**************************************************************************************************/
296 inline void errorOut(exception& e, string object, string function) {
298 mothurOut("Error: ");
299 mothurOut(toString(e.what()));
300 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.");
305 /***********************************************************************/
307 inline bool isTrue(string f){
309 if ((f == "TRUE") || (f == "T") || (f == "true") || (f == "t")) { return true; }
310 else { return false; }
313 /***********************************************************************/
315 inline float roundDist(float dist, int precision){
317 return int(dist * precision + 0.5)/float(precision);
321 /***********************************************************************/
323 inline int getNumNames(string names){
329 for(int i=0;i<names.size();i++){
340 /**************************************************************************************************/
342 inline vector<vector<double> > binomial(int maxOrder){
344 vector<vector<double> > binomial(maxOrder+1);
346 for(int i=0;i<=maxOrder;i++){
347 binomial[i].resize(maxOrder+1);
356 for(int i=2;i<=maxOrder;i++){
360 for(int i=2;i<=maxOrder;i++){
361 for(int j=1;j<=maxOrder;j++){
362 if(i==j){ binomial[i][j]=1; }
363 if(j>i) { binomial[i][j]=0; }
364 else { binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j]; }
371 /***********************************************************************/
373 inline string getRootName(string longName){
375 string rootName = longName;
377 if(longName.find_last_of(".") != longName.npos){
378 int pos = longName.find_last_of('.')+1;
379 rootName = longName.substr(0, pos);
384 /***********************************************************************/
386 inline string getSimpleName(string longName){
388 string simpleName = longName;
390 if(longName.find_last_of("/") != longName.npos){
391 int pos = longName.find_last_of('/')+1;
392 simpleName = longName.substr(pos, longName.length());
398 /***********************************************************************/
400 inline int factorial(int num){
403 for (int i = 1; i <= num; i++) {
409 /**************************************************************************************************
411 double min(double x, double y)
417 /***********************************************************************/
419 inline string getPathName(string longName){
421 string rootPathName = longName;
423 if(longName.find_last_of('/') != longName.npos){
424 int pos = longName.find_last_of('/')+1;
425 rootPathName = longName.substr(0, pos);
431 /***********************************************************************/
433 inline string getExtension(string longName){
435 string extension = longName;
437 if(longName.find_last_of('.') != longName.npos){
438 int pos = longName.find_last_of('.');
439 extension = longName.substr(pos, longName.length());
444 /***********************************************************************/
445 inline bool isBlank(string fileName){
448 fileHandle.open(fileName.c_str());
450 mothurOut("Error: Could not open " + fileName); mothurOutEndLine();
453 //check for blank file
455 if (fileHandle.eof()) { fileHandle.close(); return true; }
459 /***********************************************************************/
461 inline int openInputFile(string fileName, ifstream& fileHandle){
463 fileHandle.open(fileName.c_str());
465 mothurOut("Error: Could not open " + fileName); mothurOutEndLine();
469 //check for blank file
471 if (fileHandle.eof()) { mothurOut(fileName + " is blank. Please correct."); mothurOutEndLine(); return 1; }
478 /***********************************************************************/
480 inline int openOutputFile(string fileName, ofstream& fileHandle){
482 fileHandle.open(fileName.c_str(), ios::trunc);
484 mothurOut("Error: Could not open " + fileName); mothurOutEndLine();
493 /***********************************************************************/
495 inline int getNumSeqs(ifstream& file){
497 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
502 /***********************************************************************/
504 inline bool inVector(string member, vector<string> group){
506 for (int i = 0; i < group.size(); i++) {
507 if (group[i] == member) { return true; }
512 /***********************************************************************/
514 //This function parses the estimator options and puts them in a vector
515 inline void splitAtDash(string& estim, vector<string>& container) {
519 while (estim.find_first_of('-') != -1) {
520 individual = estim.substr(0,estim.find_first_of('-'));
521 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
522 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
523 container.push_back(individual);
527 container.push_back(estim);
529 catch(exception& e) {
530 errorOut(e, "mothur", "splitAtDash");
535 /***********************************************************************/
536 //This function parses the label options and puts them in a set
537 inline void splitAtDash(string& estim, set<string>& container) {
541 while (estim.find_first_of('-') != -1) {
542 individual = estim.substr(0,estim.find_first_of('-'));
543 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
544 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
545 container.insert(individual);
549 container.insert(estim);
551 catch(exception& e) {
552 errorOut(e, "mothur", "splitAtDash");
556 /***********************************************************************/
557 //This function parses the line options and puts them in a set
558 inline void splitAtDash(string& estim, set<int>& container) {
563 while (estim.find_first_of('-') != -1) {
564 individual = estim.substr(0,estim.find_first_of('-'));
565 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
566 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
567 convert(individual, lineNum); //convert the string to int
568 container.insert(lineNum);
572 convert(estim, lineNum); //convert the string to int
573 container.insert(lineNum);
575 catch(exception& e) {
576 errorOut(e, "mothur", "splitAtDash");
580 /***********************************************************************/
581 //This function parses the a string and puts peices in a vector
582 inline void splitAtComma(string& estim, vector<string>& container) {
586 while (estim.find_first_of(',') != -1) {
587 individual = estim.substr(0,estim.find_first_of(','));
588 if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
589 estim = estim.substr(estim.find_first_of(',')+1, estim.length());
590 container.push_back(individual);
594 container.push_back(estim);
596 catch(exception& e) {
597 errorOut(e, "mothur", "splitAtComma");
601 /***********************************************************************/
603 //This function splits up the various option parameters
604 inline void splitAtComma(string& prefix, string& suffix){
606 prefix = suffix.substr(0,suffix.find_first_of(','));
607 if ((suffix.find_first_of(',')+2) <= suffix.length()) { //checks to make sure you don't have comma at end of string
608 suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
610 while(suffix.at(0) == ' ')
611 suffix = suffix.substr(1, suffix.length());
615 catch(exception& e) {
616 errorOut(e, "mothur", "splitAtComma");
620 /***********************************************************************/
622 //This function separates the key value from the option value i.e. dist=96_...
623 inline void splitAtEquals(string& key, string& value){
625 if(value.find_first_of('=') != -1){
626 key = value.substr(0,value.find_first_of('='));
627 if ((value.find_first_of('=')+1) <= value.length()) {
628 value = value.substr(value.find_first_of('=')+1, value.length());
635 catch(exception& e) {
636 errorOut(e, "mothur", "splitAtEquals");
640 /**************************************************************************************************/
642 inline bool inUsersGroups(string groupname, vector<string> Groups) {
644 for (int i = 0; i < Groups.size(); i++) {
645 if (groupname == Groups[i]) { return true; }
649 catch(exception& e) {
650 errorOut(e, "mothur", "inUsersGroups");
655 /**************************************************************************************************/
657 inline void mothurOutJustToLog(string message) {
660 string logFileName = "mothur.logFile";
661 openOutputFileAppend(logFileName, out);
667 catch(exception& e) {
668 errorOut(e, "mothur", "mothurOutJustToLog");
674 /**************************************************************************************************/
676 inline void mothurOut(float num) {
679 string logFileName = "mothur.logFile";
680 openOutputFileAppend(logFileName, out);
687 catch(exception& e) {
688 cout << "Error in mothur class mothurOut float" << endl;
692 /***********************************************************************/
693 inline void mothurOut(double value) {
696 string logFileName = "mothur.logFile";
697 openOutputFileAppend(logFileName, out);
704 catch(exception& e) {
705 cout << "Error in mothur class mothurOut double" << endl;
710 /***********************************************************************/
711 //this function determines if the user has given us labels that are smaller than the given label.
712 //if so then it returns true so that the calling function can run the previous valid distance.
713 //it's a "smart" distance function. It also checks for invalid labels.
714 inline bool anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
716 set<string>::iterator it;
717 vector<float> orderFloat;
718 map<string, float> userMap; //the conversion process removes trailing 0's which we need to put back
719 map<string, float>::iterator it2;
721 bool smaller = false;
723 //unique is the smallest line
724 if (label == "unique") { return false; }
725 else { convert(label, labelFloat); }
727 //go through users set and make them floats
728 for(it = userLabels.begin(); it != userLabels.end(); ++it) {
731 if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
733 orderFloat.push_back(temp);
735 }else if (*it == "unique") {
736 orderFloat.push_back(-1.0);
737 userMap["unique"] = -1.0;
739 if (errorOff == "") { mothurOut(*it + " is not a valid label."); mothurOutEndLine(); }
740 userLabels.erase(*it);
746 sort(orderFloat.begin(), orderFloat.end());
748 /*************************************************/
749 //is this label bigger than any of the users labels
750 /*************************************************/
752 //loop through order until you find a label greater than label
753 for (int i = 0; i < orderFloat.size(); i++) {
754 if (orderFloat[i] < labelFloat) {
756 if (orderFloat[i] == -1) {
757 if (errorOff == "") { mothurOut("Your file does not include the label unique."); mothurOutEndLine(); }
758 userLabels.erase("unique");
761 if (errorOff == "") { mothurOut("Your file does not include the label "); mothurOutEndLine(); }
763 for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {
764 if (it2->second == orderFloat[i]) {
766 //remove small labels
771 if (errorOff == "") { mothurOut(s + ". I will use the next smallest distance. "); mothurOutEndLine(); }
773 //since they are sorted once you find a bigger one stop looking
780 catch(exception& e) {
781 errorOut(e, "mothur", "anyLabelsToProcess");
786 /**************************************************************************************************/
787 inline void appendFiles(string temp, string filename) {
792 //open output file in append mode
793 openOutputFileAppend(filename, output);
794 openInputFile(temp, input);
796 while(char c = input.get()){
797 if(input.eof()) { break; }
798 else { output << c; }
804 catch(exception& e) {
805 errorOut(e, "mothur", "appendFiles");
810 /**************************************************************************************************/
811 inline string sortFile(string distFile){
813 string outfile = getRootName(distFile) + "sorted.dist";
815 //if you can, use the unix sort since its been optimized for years
816 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
817 string command = "sort -n -k +3 " + distFile + " -o " + outfile;
818 system(command.c_str());
819 #else //you are stuck with my best attempt...
820 //windows sort does not have a way to specify a column, only a character in the line
821 //since we cannot assume that the distance will always be at the the same character location on each line
822 //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
824 //read in file line by file and put distance first
825 string tempDistFile = distFile + ".temp";
828 openInputFile(distFile, input);
829 openOutputFile(tempDistFile, output);
831 string firstName, secondName;
834 input >> firstName >> secondName >> dist;
835 output << dist << '\t' << firstName << '\t' << secondName << endl;
842 //sort using windows sort
843 string tempOutfile = outfile + ".temp";
844 string command = "sort " + tempDistFile + " /O " + tempOutfile;
845 system(command.c_str());
847 //read in sorted file and put distance at end again
849 openInputFile(tempOutfile, input2);
850 openOutputFile(outfile, output);
853 input2 >> dist >> firstName >> secondName;
854 output << firstName << '\t' << secondName << '\t' << dist << endl;
861 remove(tempDistFile.c_str());
862 remove(tempOutfile.c_str());
867 catch(exception& e) {
868 errorOut(e, "mothur", "sortFile");
872 /**************************************************************************************************/