5 * Created by westcott on 2/25/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "mothurout.h"
12 /******************************************************/
13 MothurOut* MothurOut::getInstance() {
14 if( _uniqueInstance == 0) {
15 _uniqueInstance = new MothurOut();
17 return _uniqueInstance;
19 /*********************************************************************************************/
20 void MothurOut::setFileName(string filename) {
22 logFileName = filename;
26 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
28 if (pid == 0) { //only one process should output to screen
31 openOutputFile(filename, out);
38 errorOut(e, "MothurOut", "setFileName");
42 /*********************************************************************************************/
43 void MothurOut::setDefaultPath(string pathname) {
46 //add / to name if needed
47 string lastChar = pathname.substr(pathname.length()-1);
48 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
49 if (lastChar != "/") { pathname += "/"; }
51 if (lastChar != "\\") { pathname += "\\"; }
54 defaultPath = pathname;
58 errorOut(e, "MothurOut", "setDefaultPath");
62 /*********************************************************************************************/
63 void MothurOut::closeLog() {
68 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
70 if (pid == 0) { //only one process should output to screen
80 errorOut(e, "MothurOut", "closeLog");
85 /*********************************************************************************************/
86 MothurOut::~MothurOut() {
92 errorOut(e, "MothurOut", "MothurOut");
96 /*********************************************************************************************/
97 void MothurOut::mothurOut(string output) {
102 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
104 if (pid == 0) { //only one process should output to screen
114 catch(exception& e) {
115 errorOut(e, "MothurOut", "MothurOut");
119 /*********************************************************************************************/
120 void MothurOut::mothurOutEndLine() {
124 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
126 if (pid == 0) { //only one process should output to screen
136 catch(exception& e) {
137 errorOut(e, "MothurOut", "MothurOutEndLine");
141 /*********************************************************************************************/
142 void MothurOut::mothurOutJustToLog(string output) {
146 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
148 if (pid == 0) { //only one process should output to screen
157 catch(exception& e) {
158 errorOut(e, "MothurOut", "MothurOutJustToLog");
162 /*********************************************************************************************/
163 void MothurOut::errorOut(exception& e, string object, string function) {
165 //mem_usage(vm, rss);
167 mothurOut("[ERROR]: ");
168 mothurOut(toString(e.what()));
169 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.");
172 /*********************************************************************************************/
173 //The following was originally from http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c
174 // process_mem_usage(double &, double &) - takes two doubles by reference,
175 // attempts to read the system-dependent data for a process' virtual memory
176 // size and resident set size, and return the results in KB.
178 // On failure, returns 0.0, 0.0
179 int MothurOut::mem_usage(double& vm_usage, double& resident_set) {
180 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
185 // 'file' stat seems to give the most reliable results
187 ifstream stat_stream("/proc/self/stat",ios_base::in);
189 // dummy vars for leading entries in stat that we don't care about
191 string pid, comm, state, ppid, pgrp, session, tty_nr;
192 string tpgid, flags, minflt, cminflt, majflt, cmajflt;
193 string utime, stime, cutime, cstime, priority, nice;
194 string O, itrealvalue, starttime;
196 // the two fields we want
201 stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
202 >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
203 >> utime >> stime >> cutime >> cstime >> priority >> nice
204 >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
206 long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
207 vm_usage = vsize / 1024.0;
208 resident_set = rss * page_size_kb;
210 mothurOut("Memory Usage: vm = " + toString(vm_usage) + " rss = " + toString(resident_set) + "\n");
214 /* //windows memory usage
215 // Get the list of process identifiers.
216 DWORD aProcesses[1024], cbNeeded, cProcesses;
218 if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){ return 1; }
220 // Calculate how many process identifiers were returned.
221 cProcesses = cbNeeded / sizeof(DWORD);
223 // Print the memory usage for each process
224 for (int i = 0; i < cProcesses; i++ ) {
225 DWORD processID = aProcesses[i];
227 PROCESS_MEMORY_COUNTERS pmc;
229 HANDLE hProcess = OpenProcess((PROCESS_QUERY_INFORMATION | PROCESS_VM_READ), FALSE, processID);
231 // Print the process identifier.
232 printf( "\nProcess ID: %u\n", processID);
234 if (NULL != hProcess) {
236 if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) {
237 printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );
238 printf( "\tPeakWorkingSetSize: 0x%08X\n", pmc.PeakWorkingSetSize );
239 printf( "\tWorkingSetSize: 0x%08X\n", pmc.WorkingSetSize );
240 printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakPagedPoolUsage );
241 printf( "\tQuotaPagedPoolUsage: 0x%08X\n", pmc.QuotaPagedPoolUsage );
242 printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakNonPagedPoolUsage );
243 printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n", pmc.QuotaNonPagedPoolUsage );
244 printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage );
245 printf( "\tPeakPagefileUsage: 0x%08X\n", pmc.PeakPagefileUsage );
247 CloseHandle(hProcess);
257 /***********************************************************************/
258 int MothurOut::openOutputFileAppend(string fileName, ofstream& fileHandle){
260 fileName = getFullPathName(fileName);
262 fileHandle.open(fileName.c_str(), ios::app);
264 mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
271 catch(exception& e) {
272 errorOut(e, "MothurOut", "openOutputFileAppend");
276 /***********************************************************************/
277 void MothurOut::gobble(istream& f){
280 while(isspace(d=f.get())) {;}
283 catch(exception& e) {
284 errorOut(e, "MothurOut", "gobble");
288 /***********************************************************************/
289 void MothurOut::gobble(istringstream& f){
292 while(isspace(d=f.get())) {;}
295 catch(exception& e) {
296 errorOut(e, "MothurOut", "gobble");
301 /***********************************************************************/
303 string MothurOut::getline(istringstream& fileHandle) {
308 while (!fileHandle.eof()) {
310 char c = fileHandle.get();
312 //are you at the end of the line
313 if ((c == '\n') || (c == '\r') || (c == '\f')){ break; }
320 catch(exception& e) {
321 errorOut(e, "MothurOut", "getline");
325 /***********************************************************************/
327 string MothurOut::getline(ifstream& fileHandle) {
332 while (!fileHandle.eof()) {
334 char c = fileHandle.get();
336 //are you at the end of the line
337 if ((c == '\n') || (c == '\r') || (c == '\f')){ break; }
344 catch(exception& e) {
345 errorOut(e, "MothurOut", "getline");
349 /***********************************************************************/
351 #ifdef USE_COMPRESSION
352 inline bool endsWith(string s, const char * suffix){
353 size_t suffixLength = strlen(suffix);
354 return s.size() >= suffixLength && s.substr(s.size() - suffixLength, suffixLength).compare(suffix) == 0;
358 string MothurOut::getRootName(string longName){
361 string rootName = longName;
363 #ifdef USE_COMPRESSION
364 if (endsWith(rootName, ".gz") || endsWith(rootName, ".bz2")) {
365 int pos = rootName.find_last_of('.');
366 rootName = rootName.substr(0, pos);
367 cerr << "shortening " << longName << " to " << rootName << "\n";
371 if(rootName.find_last_of(".") != rootName.npos){
372 int pos = rootName.find_last_of('.')+1;
373 rootName = rootName.substr(0, pos);
378 catch(exception& e) {
379 errorOut(e, "MothurOut", "getRootName");
383 /***********************************************************************/
385 string MothurOut::getSimpleName(string longName){
387 string simpleName = longName;
390 found=longName.find_last_of("/\\");
392 if(found != longName.npos){
393 simpleName = longName.substr(found+1);
398 catch(exception& e) {
399 errorOut(e, "MothurOut", "getSimpleName");
404 /***********************************************************************/
406 string MothurOut::getPathName(string longName){
408 string rootPathName = longName;
410 if(longName.find_last_of("/\\") != longName.npos){
411 int pos = longName.find_last_of("/\\")+1;
412 rootPathName = longName.substr(0, pos);
417 catch(exception& e) {
418 errorOut(e, "MothurOut", "getPathName");
423 /***********************************************************************/
425 string MothurOut::hasPath(string longName){
430 found=longName.find_last_of("~/\\");
432 if(found != longName.npos){
433 path = longName.substr(0, found+1);
438 catch(exception& e) {
439 errorOut(e, "MothurOut", "hasPath");
444 /***********************************************************************/
446 string MothurOut::getExtension(string longName){
448 string extension = longName;
450 if(longName.find_last_of('.') != longName.npos){
451 int pos = longName.find_last_of('.');
452 extension = longName.substr(pos, longName.length());
457 catch(exception& e) {
458 errorOut(e, "MothurOut", "getExtension");
462 /***********************************************************************/
463 bool MothurOut::isBlank(string fileName){
466 fileName = getFullPathName(fileName);
469 fileHandle.open(fileName.c_str());
471 mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
474 //check for blank file
476 if (fileHandle.eof()) { fileHandle.close(); return true; }
480 catch(exception& e) {
481 errorOut(e, "MothurOut", "isBlank");
485 /***********************************************************************/
487 string MothurOut::getFullPathName(string fileName){
490 string path = hasPath(fileName);
494 if (path == "") { return fileName; } //its a simple name
495 else { //we need to complete the pathname
496 // ex. ../../../filename
497 // cwd = /user/work/desktop
500 //get current working directory
501 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
503 if (path.find("~") != -1) { //go to home directory
504 string homeDir = getenv ("HOME");
505 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
508 if (path.rfind("./") == -1) { return fileName; } //already complete name
509 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
511 char* cwdpath = new char[1024];
514 cwdpath=getcwd(cwdpath,size);
520 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
522 //break apart the current working directory
524 while (simpleCWD.find_first_of('/') != -1) {
525 string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
526 simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
529 //get last one // ex. ../../../filename = /user/work/desktop/filename
530 dirs.push_back(simpleCWD); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
533 int index = dirs.size()-1;
535 while((pos = path.rfind("./")) != -1) { //while you don't have a complete path
536 if (pos == 0) { break; //you are at the end
537 }else if (path[(pos-1)] == '.') { //you want your parent directory ../
538 path = path.substr(0, pos-1);
540 if (index == 0) { break; }
541 }else if (path[(pos-1)] == '/') { //you want the current working dir ./
542 path = path.substr(0, pos);
543 }else if (pos == 1) { break; //you are at the end
544 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
547 for (int i = index; i >= 0; i--) {
548 newFileName = dirs[i] + "/" + newFileName;
551 newFileName = "/" + newFileName;
555 if (path.find("~") != -1) { //go to home directory
556 string homeDir = getenv ("HOMEPATH");
557 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
560 if (path.rfind(".\\") == -1) { return fileName; } //already complete name
561 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
563 char *cwdpath = NULL;
564 cwdpath = getcwd(NULL, 0); // or _getcwd
565 if ( cwdpath != NULL) { cwd = cwdpath; }
568 //break apart the current working directory
570 while (cwd.find_first_of('\\') != -1) {
571 string dir = cwd.substr(0,cwd.find_first_of('\\'));
572 cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
577 dirs.push_back(cwd); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
579 int index = dirs.size()-1;
581 while((pos = path.rfind(".\\")) != -1) { //while you don't have a complete path
582 if (pos == 0) { break; //you are at the end
583 }else if (path[(pos-1)] == '.') { //you want your parent directory ../
584 path = path.substr(0, pos-1);
586 if (index == 0) { break; }
587 }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
588 path = path.substr(0, pos);
589 }else if (pos == 1) { break; //you are at the end
590 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
593 for (int i = index; i >= 0; i--) {
594 newFileName = dirs[i] + "\\" + newFileName;
603 catch(exception& e) {
604 errorOut(e, "MothurOut", "getFullPathName");
608 /***********************************************************************/
610 int MothurOut::openInputFile(string fileName, ifstream& fileHandle, string m){
613 string completeFileName = getFullPathName(fileName);
615 #ifdef USE_COMPRESSION
616 // check for gzipped or bzipped file
617 if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
618 string tempName = string(tmpnam(0));
619 mkfifo(tempName.c_str(), 0666);
620 int fork_result = fork();
621 if (fork_result < 0) {
622 cerr << "Error forking.\n";
624 } else if (fork_result == 0) {
625 string command = (endsWith(completeFileName, ".gz") ? "zcat " : "bzcat ") + completeFileName + string(" > ") + tempName;
626 cerr << "Decompressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
627 system(command.c_str());
628 cerr << "Done decompressing " << completeFileName << "\n";
629 remove(tempName.c_str());
632 cerr << "waiting on child process " << fork_result << "\n";
633 completeFileName = tempName;
638 fileHandle.open(completeFileName.c_str());
642 //check for blank file
647 catch(exception& e) {
648 errorOut(e, "MothurOut", "openInputFile - no Error");
652 /***********************************************************************/
654 int MothurOut::openInputFile(string fileName, ifstream& fileHandle){
658 string completeFileName = getFullPathName(fileName);
660 #ifdef USE_COMPRESSION
661 // check for gzipped or bzipped file
662 if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
663 string tempName = string(tmpnam(0));
664 mkfifo(tempName.c_str(), 0666);
665 int fork_result = fork();
666 if (fork_result < 0) {
667 cerr << "Error forking.\n";
669 } else if (fork_result == 0) {
670 string command = (endsWith(completeFileName, ".gz") ? "zcat " : "bzcat ") + completeFileName + string(" > ") + tempName;
671 cerr << "Decompressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
672 system(command.c_str());
673 cerr << "Done decompressing " << completeFileName << "\n";
674 remove(tempName.c_str());
677 cerr << "waiting on child process " << fork_result << "\n";
678 completeFileName = tempName;
684 fileHandle.open(completeFileName.c_str());
686 mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
690 //check for blank file
692 if (fileHandle.eof()) { mothurOut("[ERROR]: " + completeFileName + " is blank. Please correct."); mothurOutEndLine(); }
697 catch(exception& e) {
698 errorOut(e, "MothurOut", "openInputFile");
702 /***********************************************************************/
704 int MothurOut::renameFile(string oldName, string newName){
707 int exist = openInputFile(newName, inTest, "");
709 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
710 if (exist == 0) { //you could open it so you want to delete it
712 string command = "rm " + newName;
713 system(command.c_str());
716 string command = "mv " + oldName + " " + newName;
717 system(command.c_str());
719 remove(newName.c_str());
720 int renameOk = rename(oldName.c_str(), newName.c_str());
725 catch(exception& e) {
726 errorOut(e, "MothurOut", "renameFile");
731 /***********************************************************************/
733 int MothurOut::openOutputFile(string fileName, ofstream& fileHandle){
736 string completeFileName = getFullPathName(fileName);
738 #ifdef USE_COMPRESSION
739 // check for gzipped file
740 if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
741 string tempName = string(tmpnam(0));
742 mkfifo(tempName.c_str(), 0666);
743 cerr << "Compressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
744 int fork_result = fork();
745 if (fork_result < 0) {
746 cerr << "Error forking.\n";
748 } else if (fork_result == 0) {
749 string command = string(endsWith(completeFileName, ".gz") ? "gzip" : "bzip2") + " -v > " + completeFileName + string(" < ") + tempName;
750 system(command.c_str());
753 completeFileName = tempName;
758 fileHandle.open(completeFileName.c_str(), ios::trunc);
760 mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
767 catch(exception& e) {
768 errorOut(e, "MothurOut", "openOutputFile");
774 /**************************************************************************************************/
775 void MothurOut::appendFiles(string temp, string filename) {
780 //open output file in append mode
781 openOutputFileAppend(filename, output);
782 int ableToOpen = openInputFile(temp, input, "no error");
784 if (ableToOpen == 0) { //you opened it
785 while(char c = input.get()){
786 if(input.eof()) { break; }
787 else { output << c; }
794 catch(exception& e) {
795 errorOut(e, "MothurOut", "appendFiles");
800 /**************************************************************************************************/
801 string MothurOut::sortFile(string distFile, string outputDir){
804 //if (outputDir == "") { outputDir += hasPath(distFile); }
805 string outfile = getRootName(distFile) + "sorted.dist";
808 //if you can, use the unix sort since its been optimized for years
809 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
810 string command = "sort -n -k +3 " + distFile + " -o " + outfile;
811 system(command.c_str());
812 #else //you are stuck with my best attempt...
813 //windows sort does not have a way to specify a column, only a character in the line
814 //since we cannot assume that the distance will always be at the the same character location on each line
815 //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
817 //read in file line by file and put distance first
818 string tempDistFile = distFile + ".temp";
821 openInputFile(distFile, input);
822 openOutputFile(tempDistFile, output);
824 string firstName, secondName;
827 input >> firstName >> secondName >> dist;
828 output << dist << '\t' << firstName << '\t' << secondName << endl;
835 //sort using windows sort
836 string tempOutfile = outfile + ".temp";
837 string command = "sort " + tempDistFile + " /O " + tempOutfile;
838 system(command.c_str());
840 //read in sorted file and put distance at end again
842 openInputFile(tempOutfile, input2);
843 openOutputFile(outfile, output);
846 input2 >> dist >> firstName >> secondName;
847 output << firstName << '\t' << secondName << '\t' << dist << endl;
854 remove(tempDistFile.c_str());
855 remove(tempOutfile.c_str());
860 catch(exception& e) {
861 errorOut(e, "MothurOut", "sortFile");
865 /**************************************************************************************************/
866 vector<unsigned long int> MothurOut::setFilePosFasta(string filename, int& num) {
868 vector<unsigned long int> positions;
870 openInputFile(filename, inFASTA);
873 while(!inFASTA.eof()){
874 input = getline(inFASTA);
875 if (input.length() != 0) {
876 if(input[0] == '>'){ unsigned long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
878 gobble(inFASTA); //has to be here since windows line endings are 2 characters and mess up the positions
882 num = positions.size();
887 //get num bytes in file
888 pFile = fopen (filename.c_str(),"rb");
889 if (pFile==NULL) perror ("Error opening file");
891 fseek (pFile, 0, SEEK_END);
896 unsigned long int size = positions[(positions.size()-1)];
898 openInputFile(filename, in);
902 while(char c = in.get()){
903 if(in.eof()) { break; }
908 positions.push_back(size);
912 catch(exception& e) {
913 errorOut(e, "MothurOut", "setFilePosFasta");
917 /**************************************************************************************************/
918 vector<unsigned long int> MothurOut::setFilePosEachLine(string filename, int& num) {
920 filename = getFullPathName(filename);
922 vector<unsigned long int> positions;
924 openInputFile(filename, in);
928 unsigned long int lastpos = in.tellg();
930 if (input.length() != 0) {
931 unsigned long int pos = in.tellg();
932 if (pos != -1) { positions.push_back(pos - input.length() - 1); }
933 else { positions.push_back(lastpos); }
935 gobble(in); //has to be here since windows line endings are 2 characters and mess up the positions
939 num = positions.size();
942 unsigned long int size;
944 //get num bytes in file
945 pFile = fopen (filename.c_str(),"rb");
946 if (pFile==NULL) perror ("Error opening file");
948 fseek (pFile, 0, SEEK_END);
953 positions.push_back(size);
957 catch(exception& e) {
958 errorOut(e, "MothurOut", "setFilePosEachLine");
962 /**************************************************************************************************/
964 vector<unsigned long int> MothurOut::divideFile(string filename, int& proc) {
967 vector<unsigned long int> filePos;
968 filePos.push_back(0);
971 unsigned long int size;
973 filename = getFullPathName(filename);
975 //get num bytes in file
976 pFile = fopen (filename.c_str(),"rb");
977 if (pFile==NULL) perror ("Error opening file");
979 fseek (pFile, 0, SEEK_END);
984 //estimate file breaks
985 unsigned long int chunkSize = 0;
986 chunkSize = size / proc;
988 //file to small to divide by processors
989 if (chunkSize == 0) { proc = 1; filePos.push_back(size); return filePos; }
991 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
992 for (int i = 0; i < proc; i++) {
993 unsigned long int spot = (i+1) * chunkSize;
996 openInputFile(filename, in);
1000 unsigned long int newSpot = spot;
1003 if (c == '>') { in.putback(c); newSpot = in.tellg(); break; }
1006 //there was not another sequence before the end of the file
1007 unsigned long int sanityPos = in.tellg();
1009 if (sanityPos == -1) { break; }
1010 else { filePos.push_back(newSpot); }
1016 filePos.push_back(size);
1018 //sanity check filePos
1019 for (int i = 0; i < (filePos.size()-1); i++) {
1020 if (filePos[(i+1)] <= filePos[i]) { filePos.erase(filePos.begin()+(i+1)); i--; }
1023 proc = (filePos.size() - 1);
1027 catch(exception& e) {
1028 errorOut(e, "MothurOut", "divideFile");
1033 /***********************************************************************/
1035 bool MothurOut::isTrue(string f){
1038 for (int i = 0; i < f.length(); i++) { f[i] = toupper(f[i]); }
1040 if ((f == "TRUE") || (f == "T")) { return true; }
1041 else { return false; }
1043 catch(exception& e) {
1044 errorOut(e, "MothurOut", "isTrue");
1049 /***********************************************************************/
1051 float MothurOut::roundDist(float dist, int precision){
1053 return int(dist * precision + 0.5)/float(precision);
1055 catch(exception& e) {
1056 errorOut(e, "MothurOut", "roundDist");
1060 /***********************************************************************/
1062 float MothurOut::ceilDist(float dist, int precision){
1064 return int(ceil(dist * precision))/float(precision);
1066 catch(exception& e) {
1067 errorOut(e, "MothurOut", "ceilDist");
1072 /***********************************************************************/
1074 int MothurOut::getNumNames(string names){
1080 for(int i=0;i<names.size();i++){
1081 if(names[i] == ','){
1089 catch(exception& e) {
1090 errorOut(e, "MothurOut", "getNumNames");
1095 /**************************************************************************************************/
1097 vector<vector<double> > MothurOut::binomial(int maxOrder){
1099 vector<vector<double> > binomial(maxOrder+1);
1101 for(int i=0;i<=maxOrder;i++){
1102 binomial[i].resize(maxOrder+1);
1111 for(int i=2;i<=maxOrder;i++){
1115 for(int i=2;i<=maxOrder;i++){
1116 for(int j=1;j<=maxOrder;j++){
1117 if(i==j){ binomial[i][j]=1; }
1118 if(j>i) { binomial[i][j]=0; }
1119 else { binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j]; }
1126 catch(exception& e) {
1127 errorOut(e, "MothurOut", "binomial");
1132 /***********************************************************************/
1134 int MothurOut::factorial(int num){
1138 for (int i = 1; i <= num; i++) {
1144 catch(exception& e) {
1145 errorOut(e, "MothurOut", "factorial");
1149 /***********************************************************************/
1151 int MothurOut::getNumSeqs(ifstream& file){
1153 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
1157 catch(exception& e) {
1158 errorOut(e, "MothurOut", "getNumSeqs");
1162 /***********************************************************************/
1163 void MothurOut::getNumSeqs(ifstream& file, int& numSeqs){
1168 input = getline(file);
1169 if (input.length() != 0) {
1170 if(input[0] == '>'){ numSeqs++; }
1174 catch(exception& e) {
1175 errorOut(e, "MothurOut", "getNumSeqs");
1179 /***********************************************************************/
1181 //This function parses the estimator options and puts them in a vector
1182 void MothurOut::splitAtChar(string& estim, vector<string>& container, char symbol) {
1186 while (estim.find_first_of(symbol) != -1) {
1187 individual = estim.substr(0,estim.find_first_of(symbol));
1188 if ((estim.find_first_of(symbol)+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1189 estim = estim.substr(estim.find_first_of(symbol)+1, estim.length());
1190 container.push_back(individual);
1194 container.push_back(estim);
1196 catch(exception& e) {
1197 errorOut(e, "MothurOut", "splitAtChar");
1202 /***********************************************************************/
1204 //This function parses the estimator options and puts them in a vector
1205 void MothurOut::splitAtDash(string& estim, vector<string>& container) {
1207 string individual = "";
1208 int estimLength = estim.size();
1209 for(int i=0;i<estimLength;i++){
1210 if(estim[i] == '-'){
1211 container.push_back(individual);
1215 individual += estim[i];
1218 container.push_back(individual);
1221 /* string individual;
1223 while (estim.find_first_of('-') != -1) {
1224 individual = estim.substr(0,estim.find_first_of('-'));
1225 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1226 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1227 container.push_back(individual);
1231 container.push_back(estim); */
1233 catch(exception& e) {
1234 errorOut(e, "MothurOut", "splitAtDash");
1239 /***********************************************************************/
1240 //This function parses the label options and puts them in a set
1241 void MothurOut::splitAtDash(string& estim, set<string>& container) {
1243 string individual = "";
1244 int estimLength = estim.size();
1245 for(int i=0;i<estimLength;i++){
1246 if(estim[i] == '-'){
1247 container.insert(individual);
1251 individual += estim[i];
1254 container.insert(individual);
1256 // string individual;
1258 // while (estim.find_first_of('-') != -1) {
1259 // individual = estim.substr(0,estim.find_first_of('-'));
1260 // if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1261 // estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1262 // container.insert(individual);
1266 // container.insert(estim);
1269 catch(exception& e) {
1270 errorOut(e, "MothurOut", "splitAtDash");
1274 /***********************************************************************/
1275 //This function parses the line options and puts them in a set
1276 void MothurOut::splitAtDash(string& estim, set<int>& container) {
1281 while (estim.find_first_of('-') != -1) {
1282 individual = estim.substr(0,estim.find_first_of('-'));
1283 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1284 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1285 convert(individual, lineNum); //convert the string to int
1286 container.insert(lineNum);
1290 convert(estim, lineNum); //convert the string to int
1291 container.insert(lineNum);
1293 catch(exception& e) {
1294 errorOut(e, "MothurOut", "splitAtDash");
1298 /***********************************************************************/
1299 //This function parses the a string and puts peices in a vector
1300 void MothurOut::splitAtComma(string& estim, vector<string>& container) {
1302 string individual = "";
1303 int estimLength = estim.size();
1304 for(int i=0;i<estimLength;i++){
1305 if(estim[i] == ','){
1306 container.push_back(individual);
1310 individual += estim[i];
1313 container.push_back(individual);
1318 // string individual;
1320 // while (estim.find_first_of(',') != -1) {
1321 // individual = estim.substr(0,estim.find_first_of(','));
1322 // if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
1323 // estim = estim.substr(estim.find_first_of(',')+1, estim.length());
1324 // container.push_back(individual);
1328 // container.push_back(estim);
1330 catch(exception& e) {
1331 errorOut(e, "MothurOut", "splitAtComma");
1335 /***********************************************************************/
1337 //This function splits up the various option parameters
1338 void MothurOut::splitAtComma(string& prefix, string& suffix){
1340 prefix = suffix.substr(0,suffix.find_first_of(','));
1341 if ((suffix.find_first_of(',')+2) <= suffix.length()) { //checks to make sure you don't have comma at end of string
1342 suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
1344 while(suffix.at(0) == ' ')
1345 suffix = suffix.substr(1, suffix.length());
1349 catch(exception& e) {
1350 errorOut(e, "MothurOut", "splitAtComma");
1354 /***********************************************************************/
1356 //This function separates the key value from the option value i.e. dist=96_...
1357 void MothurOut::splitAtEquals(string& key, string& value){
1359 if(value.find_first_of('=') != -1){
1360 key = value.substr(0,value.find_first_of('='));
1361 if ((value.find_first_of('=')+1) <= value.length()) {
1362 value = value.substr(value.find_first_of('=')+1, value.length());
1369 catch(exception& e) {
1370 errorOut(e, "MothurOut", "splitAtEquals");
1375 /**************************************************************************************************/
1377 bool MothurOut::inUsersGroups(string groupname, vector<string> Groups) {
1379 for (int i = 0; i < Groups.size(); i++) {
1380 if (groupname == Groups[i]) { return true; }
1384 catch(exception& e) {
1385 errorOut(e, "MothurOut", "inUsersGroups");
1389 /**************************************************************************************************/
1390 //returns true if any of the strings in first vector are in second vector
1391 bool MothurOut::inUsersGroups(vector<string> groupnames, vector<string> Groups) {
1394 for (int i = 0; i < groupnames.size(); i++) {
1395 if (inUsersGroups(groupnames[i], Groups)) { return true; }
1399 catch(exception& e) {
1400 errorOut(e, "MothurOut", "inUsersGroups");
1404 /***********************************************************************/
1405 //this function determines if the user has given us labels that are smaller than the given label.
1406 //if so then it returns true so that the calling function can run the previous valid distance.
1407 //it's a "smart" distance function. It also checks for invalid labels.
1408 bool MothurOut::anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
1411 set<string>::iterator it;
1412 vector<float> orderFloat;
1413 map<string, float> userMap; //the conversion process removes trailing 0's which we need to put back
1414 map<string, float>::iterator it2;
1416 bool smaller = false;
1418 //unique is the smallest line
1419 if (label == "unique") { return false; }
1421 if (convertTestFloat(label, labelFloat)) {
1422 convert(label, labelFloat);
1423 }else { //cant convert
1428 //go through users set and make them floats
1429 for(it = userLabels.begin(); it != userLabels.end(); ++it) {
1432 if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
1434 orderFloat.push_back(temp);
1435 userMap[*it] = temp;
1436 }else if (*it == "unique") {
1437 orderFloat.push_back(-1.0);
1438 userMap["unique"] = -1.0;
1440 if (errorOff == "") { cout << *it << " is not a valid label." << endl; }
1441 userLabels.erase(*it);
1447 sort(orderFloat.begin(), orderFloat.end());
1449 /*************************************************/
1450 //is this label bigger than any of the users labels
1451 /*************************************************/
1453 //loop through order until you find a label greater than label
1454 for (int i = 0; i < orderFloat.size(); i++) {
1455 if (orderFloat[i] < labelFloat) {
1457 if (orderFloat[i] == -1) {
1458 if (errorOff == "") { cout << "Your file does not include the label unique." << endl; }
1459 userLabels.erase("unique");
1462 if (errorOff == "") { cout << "Your file does not include the label " << endl; }
1464 for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {
1465 if (it2->second == orderFloat[i]) {
1467 //remove small labels
1468 userLabels.erase(s);
1472 if (errorOff == "") {cout << s << ". I will use the next smallest distance. " << endl; }
1474 //since they are sorted once you find a bigger one stop looking
1481 catch(exception& e) {
1482 errorOut(e, "MothurOut", "anyLabelsToProcess");
1487 /**************************************************************************************************/
1488 bool MothurOut::checkReleaseVersion(ifstream& file, string version) {
1493 string line = getline(file);
1495 //before we added this check
1496 if (line[0] != '#') { good = false; }
1499 line = line.substr(1);
1501 vector<string> versionVector;
1502 splitAtChar(version, versionVector, '.');
1504 //check file version
1505 vector<string> linesVector;
1506 splitAtChar(line, linesVector, '.');
1508 if (versionVector.size() != linesVector.size()) { good = false; }
1510 for (int j = 0; j < versionVector.size(); j++) {
1512 convert(versionVector[j], num1);
1513 convert(linesVector[j], num2);
1515 //if mothurs version is newer than this files version, then we want to remake it
1516 if (num1 > num2) { good = false; break; }
1522 if (!good) { file.close(); }
1523 else { file.seekg(0); }
1527 catch(exception& e) {
1528 errorOut(e, "MothurOut", "checkReleaseVersion");
1532 /**************************************************************************************************/