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::setOutputDir(string pathname) {
68 errorOut(e, "MothurOut", "setOutputDir");
72 /*********************************************************************************************/
73 void MothurOut::closeLog() {
78 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
80 if (pid == 0) { //only one process should output to screen
90 errorOut(e, "MothurOut", "closeLog");
95 /*********************************************************************************************/
96 MothurOut::~MothurOut() {
101 catch(exception& e) {
102 errorOut(e, "MothurOut", "MothurOut");
106 /*********************************************************************************************/
107 void MothurOut::mothurOut(string output) {
112 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
114 if (pid == 0) { //only one process should output to screen
124 catch(exception& e) {
125 errorOut(e, "MothurOut", "MothurOut");
129 /*********************************************************************************************/
130 void MothurOut::mothurOutEndLine() {
134 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
136 if (pid == 0) { //only one process should output to screen
146 catch(exception& e) {
147 errorOut(e, "MothurOut", "MothurOutEndLine");
151 /*********************************************************************************************/
152 void MothurOut::mothurOutJustToLog(string output) {
156 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
158 if (pid == 0) { //only one process should output to screen
167 catch(exception& e) {
168 errorOut(e, "MothurOut", "MothurOutJustToLog");
172 /*********************************************************************************************/
173 void MothurOut::errorOut(exception& e, string object, string function) {
175 //mem_usage(vm, rss);
177 mothurOut("[ERROR]: ");
178 mothurOut(toString(e.what()));
179 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.");
182 /*********************************************************************************************/
183 //The following was originally from http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c
184 // process_mem_usage(double &, double &) - takes two doubles by reference,
185 // attempts to read the system-dependent data for a process' virtual memory
186 // size and resident set size, and return the results in KB.
188 // On failure, returns 0.0, 0.0
189 int MothurOut::mem_usage(double& vm_usage, double& resident_set) {
190 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
195 // 'file' stat seems to give the most reliable results
197 ifstream stat_stream("/proc/self/stat",ios_base::in);
199 // dummy vars for leading entries in stat that we don't care about
201 string pid, comm, state, ppid, pgrp, session, tty_nr;
202 string tpgid, flags, minflt, cminflt, majflt, cmajflt;
203 string utime, stime, cutime, cstime, priority, nice;
204 string O, itrealvalue, starttime;
206 // the two fields we want
211 stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
212 >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
213 >> utime >> stime >> cutime >> cstime >> priority >> nice
214 >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
216 long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
217 vm_usage = vsize / 1024.0;
218 resident_set = rss * page_size_kb;
220 mothurOut("Memory Usage: vm = " + toString(vm_usage) + " rss = " + toString(resident_set) + "\n");
224 /* //windows memory usage
225 // Get the list of process identifiers.
226 DWORD aProcesses[1024], cbNeeded, cProcesses;
228 if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){ return 1; }
230 // Calculate how many process identifiers were returned.
231 cProcesses = cbNeeded / sizeof(DWORD);
233 // Print the memory usage for each process
234 for (int i = 0; i < cProcesses; i++ ) {
235 DWORD processID = aProcesses[i];
237 PROCESS_MEMORY_COUNTERS pmc;
239 HANDLE hProcess = OpenProcess((PROCESS_QUERY_INFORMATION | PROCESS_VM_READ), FALSE, processID);
241 // Print the process identifier.
242 printf( "\nProcess ID: %u\n", processID);
244 if (NULL != hProcess) {
246 if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) {
247 printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );
248 printf( "\tPeakWorkingSetSize: 0x%08X\n", pmc.PeakWorkingSetSize );
249 printf( "\tWorkingSetSize: 0x%08X\n", pmc.WorkingSetSize );
250 printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakPagedPoolUsage );
251 printf( "\tQuotaPagedPoolUsage: 0x%08X\n", pmc.QuotaPagedPoolUsage );
252 printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakNonPagedPoolUsage );
253 printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n", pmc.QuotaNonPagedPoolUsage );
254 printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage );
255 printf( "\tPeakPagefileUsage: 0x%08X\n", pmc.PeakPagefileUsage );
257 CloseHandle(hProcess);
267 /***********************************************************************/
268 int MothurOut::openOutputFileAppend(string fileName, ofstream& fileHandle){
270 fileName = getFullPathName(fileName);
272 fileHandle.open(fileName.c_str(), ios::app);
274 mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
281 catch(exception& e) {
282 errorOut(e, "MothurOut", "openOutputFileAppend");
286 /***********************************************************************/
287 void MothurOut::gobble(istream& f){
291 while(isspace(d=f.get())) { ;}
294 catch(exception& e) {
295 errorOut(e, "MothurOut", "gobble");
299 /***********************************************************************/
300 void MothurOut::gobble(istringstream& f){
303 while(isspace(d=f.get())) {;}
306 catch(exception& e) {
307 errorOut(e, "MothurOut", "gobble");
312 /***********************************************************************/
314 string MothurOut::getline(istringstream& fileHandle) {
319 while (!fileHandle.eof()) {
321 char c = fileHandle.get();
323 //are you at the end of the line
324 if ((c == '\n') || (c == '\r') || (c == '\f')){ break; }
331 catch(exception& e) {
332 errorOut(e, "MothurOut", "getline");
336 /***********************************************************************/
338 string MothurOut::getline(ifstream& fileHandle) {
343 while (!fileHandle.eof()) {
345 char c = fileHandle.get();
347 //are you at the end of the line
348 if ((c == '\n') || (c == '\r') || (c == '\f')){ break; }
355 catch(exception& e) {
356 errorOut(e, "MothurOut", "getline");
360 /***********************************************************************/
362 #ifdef USE_COMPRESSION
363 inline bool endsWith(string s, const char * suffix){
364 size_t suffixLength = strlen(suffix);
365 return s.size() >= suffixLength && s.substr(s.size() - suffixLength, suffixLength).compare(suffix) == 0;
369 string MothurOut::getRootName(string longName){
372 string rootName = longName;
374 #ifdef USE_COMPRESSION
375 if (endsWith(rootName, ".gz") || endsWith(rootName, ".bz2")) {
376 int pos = rootName.find_last_of('.');
377 rootName = rootName.substr(0, pos);
378 cerr << "shortening " << longName << " to " << rootName << "\n";
382 if(rootName.find_last_of(".") != rootName.npos){
383 int pos = rootName.find_last_of('.')+1;
384 rootName = rootName.substr(0, pos);
389 catch(exception& e) {
390 errorOut(e, "MothurOut", "getRootName");
394 /***********************************************************************/
396 string MothurOut::getSimpleName(string longName){
398 string simpleName = longName;
401 found=longName.find_last_of("/\\");
403 if(found != longName.npos){
404 simpleName = longName.substr(found+1);
409 catch(exception& e) {
410 errorOut(e, "MothurOut", "getSimpleName");
415 /***********************************************************************/
417 string MothurOut::getPathName(string longName){
419 string rootPathName = longName;
421 if(longName.find_last_of("/\\") != longName.npos){
422 int pos = longName.find_last_of("/\\")+1;
423 rootPathName = longName.substr(0, pos);
428 catch(exception& e) {
429 errorOut(e, "MothurOut", "getPathName");
434 /***********************************************************************/
436 string MothurOut::hasPath(string longName){
441 found=longName.find_last_of("~/\\");
443 if(found != longName.npos){
444 path = longName.substr(0, found+1);
449 catch(exception& e) {
450 errorOut(e, "MothurOut", "hasPath");
455 /***********************************************************************/
457 string MothurOut::getExtension(string longName){
459 string extension = longName;
461 if(longName.find_last_of('.') != longName.npos){
462 int pos = longName.find_last_of('.');
463 extension = longName.substr(pos, longName.length());
468 catch(exception& e) {
469 errorOut(e, "MothurOut", "getExtension");
473 /***********************************************************************/
474 bool MothurOut::isBlank(string fileName){
477 fileName = getFullPathName(fileName);
480 fileHandle.open(fileName.c_str());
482 mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
485 //check for blank file
487 if (fileHandle.eof()) { fileHandle.close(); return true; }
491 catch(exception& e) {
492 errorOut(e, "MothurOut", "isBlank");
496 /***********************************************************************/
498 string MothurOut::getFullPathName(string fileName){
501 string path = hasPath(fileName);
505 if (path == "") { return fileName; } //its a simple name
506 else { //we need to complete the pathname
507 // ex. ../../../filename
508 // cwd = /user/work/desktop
511 //get current working directory
512 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
514 if (path.find("~") != -1) { //go to home directory
517 char *homepath = NULL;
518 homepath = getenv ("HOME");
519 if ( homepath != NULL) { homeDir = homepath; }
520 else { homeDir = ""; }
522 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
525 if (path.rfind("./") == -1) { return fileName; } //already complete name
526 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
528 //char* cwdpath = new char[1024];
530 //cwdpath=getcwd(cwdpath,size);
533 char *cwdpath = NULL;
534 cwdpath = getcwd(NULL, 0); // or _getcwd
535 if ( cwdpath != NULL) { cwd = cwdpath; }
541 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
543 //break apart the current working directory
545 while (simpleCWD.find_first_of('/') != -1) {
546 string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
547 simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
550 //get last one // ex. ../../../filename = /user/work/desktop/filename
551 dirs.push_back(simpleCWD); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
554 int index = dirs.size()-1;
556 while((pos = path.rfind("./")) != -1) { //while you don't have a complete path
557 if (pos == 0) { break; //you are at the end
558 }else if (path[(pos-1)] == '.') { //you want your parent directory ../
559 path = path.substr(0, pos-1);
561 if (index == 0) { break; }
562 }else if (path[(pos-1)] == '/') { //you want the current working dir ./
563 path = path.substr(0, pos);
564 }else if (pos == 1) { break; //you are at the end
565 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
568 for (int i = index; i >= 0; i--) {
569 newFileName = dirs[i] + "/" + newFileName;
572 newFileName = "/" + newFileName;
576 if (path.find("~") != -1) { //go to home directory
577 string homeDir = getenv ("HOMEPATH");
578 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
581 if (path.rfind(".\\") == -1) { return fileName; } //already complete name
582 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
584 char *cwdpath = NULL;
585 cwdpath = getcwd(NULL, 0); // or _getcwd
586 if ( cwdpath != NULL) { cwd = cwdpath; }
589 //break apart the current working directory
591 while (cwd.find_first_of('\\') != -1) {
592 string dir = cwd.substr(0,cwd.find_first_of('\\'));
593 cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
598 dirs.push_back(cwd); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
600 int index = dirs.size()-1;
602 while((pos = path.rfind(".\\")) != -1) { //while you don't have a complete path
603 if (pos == 0) { break; //you are at the end
604 }else if (path[(pos-1)] == '.') { //you want your parent directory ../
605 path = path.substr(0, pos-1);
607 if (index == 0) { break; }
608 }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
609 path = path.substr(0, pos);
610 }else if (pos == 1) { break; //you are at the end
611 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
614 for (int i = index; i >= 0; i--) {
615 newFileName = dirs[i] + "\\" + newFileName;
624 catch(exception& e) {
625 errorOut(e, "MothurOut", "getFullPathName");
629 /***********************************************************************/
631 int MothurOut::openInputFile(string fileName, ifstream& fileHandle, string m){
634 string completeFileName = getFullPathName(fileName);
636 #ifdef USE_COMPRESSION
637 // check for gzipped or bzipped file
638 if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
639 string tempName = string(tmpnam(0));
640 mkfifo(tempName.c_str(), 0666);
641 int fork_result = fork();
642 if (fork_result < 0) {
643 cerr << "Error forking.\n";
645 } else if (fork_result == 0) {
646 string command = (endsWith(completeFileName, ".gz") ? "zcat " : "bzcat ") + completeFileName + string(" > ") + tempName;
647 cerr << "Decompressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
648 system(command.c_str());
649 cerr << "Done decompressing " << completeFileName << "\n";
650 remove(tempName.c_str());
653 cerr << "waiting on child process " << fork_result << "\n";
654 completeFileName = tempName;
659 fileHandle.open(completeFileName.c_str());
663 //check for blank file
668 catch(exception& e) {
669 errorOut(e, "MothurOut", "openInputFile - no Error");
673 /***********************************************************************/
675 int MothurOut::openInputFile(string fileName, ifstream& fileHandle){
679 string completeFileName = getFullPathName(fileName);
681 #ifdef USE_COMPRESSION
682 // check for gzipped or bzipped file
683 if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
684 string tempName = string(tmpnam(0));
685 mkfifo(tempName.c_str(), 0666);
686 int fork_result = fork();
687 if (fork_result < 0) {
688 cerr << "Error forking.\n";
690 } else if (fork_result == 0) {
691 string command = (endsWith(completeFileName, ".gz") ? "zcat " : "bzcat ") + completeFileName + string(" > ") + tempName;
692 cerr << "Decompressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
693 system(command.c_str());
694 cerr << "Done decompressing " << completeFileName << "\n";
695 remove(tempName.c_str());
698 cerr << "waiting on child process " << fork_result << "\n";
699 completeFileName = tempName;
705 fileHandle.open(completeFileName.c_str());
707 mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
711 //check for blank file
713 if (fileHandle.eof()) { mothurOut("[ERROR]: " + completeFileName + " is blank. Please correct."); mothurOutEndLine(); }
718 catch(exception& e) {
719 errorOut(e, "MothurOut", "openInputFile");
723 /***********************************************************************/
725 int MothurOut::renameFile(string oldName, string newName){
728 int exist = openInputFile(newName, inTest, "");
730 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
731 if (exist == 0) { //you could open it so you want to delete it
733 string command = "rm " + newName;
734 system(command.c_str());
737 string command = "mv " + oldName + " " + newName;
738 system(command.c_str());
740 remove(newName.c_str());
741 int renameOk = rename(oldName.c_str(), newName.c_str());
746 catch(exception& e) {
747 errorOut(e, "MothurOut", "renameFile");
752 /***********************************************************************/
754 int MothurOut::openOutputFile(string fileName, ofstream& fileHandle){
757 string completeFileName = getFullPathName(fileName);
759 #ifdef USE_COMPRESSION
760 // check for gzipped file
761 if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
762 string tempName = string(tmpnam(0));
763 mkfifo(tempName.c_str(), 0666);
764 cerr << "Compressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
765 int fork_result = fork();
766 if (fork_result < 0) {
767 cerr << "Error forking.\n";
769 } else if (fork_result == 0) {
770 string command = string(endsWith(completeFileName, ".gz") ? "gzip" : "bzip2") + " -v > " + completeFileName + string(" < ") + tempName;
771 system(command.c_str());
774 completeFileName = tempName;
779 fileHandle.open(completeFileName.c_str(), ios::trunc);
781 mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
788 catch(exception& e) {
789 errorOut(e, "MothurOut", "openOutputFile");
795 /**************************************************************************************************/
796 void MothurOut::appendFiles(string temp, string filename) {
801 //open output file in append mode
802 openOutputFileAppend(filename, output);
803 int ableToOpen = openInputFile(temp, input, "no error");
805 if (ableToOpen == 0) { //you opened it
806 while(char c = input.get()){
807 if(input.eof()) { break; }
808 else { output << c; }
815 catch(exception& e) {
816 errorOut(e, "MothurOut", "appendFiles");
821 /**************************************************************************************************/
822 string MothurOut::sortFile(string distFile, string outputDir){
825 //if (outputDir == "") { outputDir += hasPath(distFile); }
826 string outfile = getRootName(distFile) + "sorted.dist";
829 //if you can, use the unix sort since its been optimized for years
830 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
831 string command = "sort -n -k +3 " + distFile + " -o " + outfile;
832 system(command.c_str());
833 #else //you are stuck with my best attempt...
834 //windows sort does not have a way to specify a column, only a character in the line
835 //since we cannot assume that the distance will always be at the the same character location on each line
836 //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
838 //read in file line by file and put distance first
839 string tempDistFile = distFile + ".temp";
842 openInputFile(distFile, input);
843 openOutputFile(tempDistFile, output);
845 string firstName, secondName;
848 input >> firstName >> secondName >> dist;
849 output << dist << '\t' << firstName << '\t' << secondName << endl;
856 //sort using windows sort
857 string tempOutfile = outfile + ".temp";
858 string command = "sort " + tempDistFile + " /O " + tempOutfile;
859 system(command.c_str());
861 //read in sorted file and put distance at end again
863 openInputFile(tempOutfile, input2);
864 openOutputFile(outfile, output);
867 input2 >> dist >> firstName >> secondName;
868 output << firstName << '\t' << secondName << '\t' << dist << endl;
875 remove(tempDistFile.c_str());
876 remove(tempOutfile.c_str());
881 catch(exception& e) {
882 errorOut(e, "MothurOut", "sortFile");
886 /**************************************************************************************************/
887 vector<unsigned long int> MothurOut::setFilePosFasta(string filename, int& num) {
889 vector<unsigned long int> positions;
891 openInputFile(filename, inFASTA);
894 while(!inFASTA.eof()){
895 input = getline(inFASTA);
896 if (input.length() != 0) {
897 if(input[0] == '>'){ unsigned long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
899 gobble(inFASTA); //has to be here since windows line endings are 2 characters and mess up the positions
903 num = positions.size();
908 //get num bytes in file
909 pFile = fopen (filename.c_str(),"rb");
910 if (pFile==NULL) perror ("Error opening file");
912 fseek (pFile, 0, SEEK_END);
917 unsigned long int size = positions[(positions.size()-1)];
919 openInputFile(filename, in);
923 while(char c = in.get()){
924 if(in.eof()) { break; }
929 positions.push_back(size);
933 catch(exception& e) {
934 errorOut(e, "MothurOut", "setFilePosFasta");
938 /**************************************************************************************************/
939 vector<unsigned long int> MothurOut::setFilePosEachLine(string filename, int& num) {
941 filename = getFullPathName(filename);
943 vector<unsigned long int> positions;
945 openInputFile(filename, in);
949 unsigned long int lastpos = in.tellg();
951 if (input.length() != 0) {
952 unsigned long int pos = in.tellg();
953 if (pos != -1) { positions.push_back(pos - input.length() - 1); }
954 else { positions.push_back(lastpos); }
956 gobble(in); //has to be here since windows line endings are 2 characters and mess up the positions
960 num = positions.size();
963 unsigned long int size;
965 //get num bytes in file
966 pFile = fopen (filename.c_str(),"rb");
967 if (pFile==NULL) perror ("Error opening file");
969 fseek (pFile, 0, SEEK_END);
974 positions.push_back(size);
978 catch(exception& e) {
979 errorOut(e, "MothurOut", "setFilePosEachLine");
983 /**************************************************************************************************/
985 vector<unsigned long int> MothurOut::divideFile(string filename, int& proc) {
988 vector<unsigned long int> filePos;
989 filePos.push_back(0);
992 unsigned long int size;
994 filename = getFullPathName(filename);
996 //get num bytes in file
997 pFile = fopen (filename.c_str(),"rb");
998 if (pFile==NULL) perror ("Error opening file");
1000 fseek (pFile, 0, SEEK_END);
1005 //estimate file breaks
1006 unsigned long int chunkSize = 0;
1007 chunkSize = size / proc;
1009 //file to small to divide by processors
1010 if (chunkSize == 0) { proc = 1; filePos.push_back(size); return filePos; }
1012 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
1013 for (int i = 0; i < proc; i++) {
1014 unsigned long int spot = (i+1) * chunkSize;
1017 openInputFile(filename, in);
1021 unsigned long int newSpot = spot;
1024 if (c == '>') { in.putback(c); newSpot = in.tellg(); break; }
1027 //there was not another sequence before the end of the file
1028 unsigned long int sanityPos = in.tellg();
1030 if (sanityPos == -1) { break; }
1031 else { filePos.push_back(newSpot); }
1037 filePos.push_back(size);
1039 //sanity check filePos
1040 for (int i = 0; i < (filePos.size()-1); i++) {
1041 if (filePos[(i+1)] <= filePos[i]) { cout << "erasing " << (i+1) << endl; filePos.erase(filePos.begin()+(i+1)); i--; }
1044 proc = (filePos.size() - 1);
1048 catch(exception& e) {
1049 errorOut(e, "MothurOut", "divideFile");
1054 /***********************************************************************/
1056 bool MothurOut::isTrue(string f){
1059 for (int i = 0; i < f.length(); i++) { f[i] = toupper(f[i]); }
1061 if ((f == "TRUE") || (f == "T")) { return true; }
1062 else { return false; }
1064 catch(exception& e) {
1065 errorOut(e, "MothurOut", "isTrue");
1070 /***********************************************************************/
1072 float MothurOut::roundDist(float dist, int precision){
1074 return int(dist * precision + 0.5)/float(precision);
1076 catch(exception& e) {
1077 errorOut(e, "MothurOut", "roundDist");
1081 /***********************************************************************/
1083 float MothurOut::ceilDist(float dist, int precision){
1085 return int(ceil(dist * precision))/float(precision);
1087 catch(exception& e) {
1088 errorOut(e, "MothurOut", "ceilDist");
1093 /***********************************************************************/
1095 int MothurOut::getNumNames(string names){
1101 for(int i=0;i<names.size();i++){
1102 if(names[i] == ','){
1110 catch(exception& e) {
1111 errorOut(e, "MothurOut", "getNumNames");
1116 /**************************************************************************************************/
1118 vector<vector<double> > MothurOut::binomial(int maxOrder){
1120 vector<vector<double> > binomial(maxOrder+1);
1122 for(int i=0;i<=maxOrder;i++){
1123 binomial[i].resize(maxOrder+1);
1132 for(int i=2;i<=maxOrder;i++){
1136 for(int i=2;i<=maxOrder;i++){
1137 for(int j=1;j<=maxOrder;j++){
1138 if(i==j){ binomial[i][j]=1; }
1139 if(j>i) { binomial[i][j]=0; }
1140 else { binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j]; }
1147 catch(exception& e) {
1148 errorOut(e, "MothurOut", "binomial");
1153 /***********************************************************************/
1155 int MothurOut::factorial(int num){
1159 for (int i = 1; i <= num; i++) {
1165 catch(exception& e) {
1166 errorOut(e, "MothurOut", "factorial");
1170 /***********************************************************************/
1172 int MothurOut::getNumSeqs(ifstream& file){
1174 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
1178 catch(exception& e) {
1179 errorOut(e, "MothurOut", "getNumSeqs");
1183 /***********************************************************************/
1184 void MothurOut::getNumSeqs(ifstream& file, int& numSeqs){
1189 input = getline(file);
1190 if (input.length() != 0) {
1191 if(input[0] == '>'){ numSeqs++; }
1195 catch(exception& e) {
1196 errorOut(e, "MothurOut", "getNumSeqs");
1200 /***********************************************************************/
1202 //This function parses the estimator options and puts them in a vector
1203 void MothurOut::splitAtChar(string& estim, vector<string>& container, char symbol) {
1205 string individual = "";
1206 int estimLength = estim.size();
1207 for(int i=0;i<estimLength;i++){
1208 if(estim[i] == symbol){
1209 container.push_back(individual);
1213 individual += estim[i];
1216 container.push_back(individual);
1220 while (estim.find_first_of(symbol) != -1) {
1221 individual = estim.substr(0,estim.find_first_of(symbol));
1222 if ((estim.find_first_of(symbol)+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1223 estim = estim.substr(estim.find_first_of(symbol)+1, estim.length());
1224 container.push_back(individual);
1228 container.push_back(estim); */
1230 catch(exception& e) {
1231 errorOut(e, "MothurOut", "splitAtChar");
1236 /***********************************************************************/
1238 //This function parses the estimator options and puts them in a vector
1239 void MothurOut::splitAtDash(string& estim, vector<string>& container) {
1241 string individual = "";
1242 int estimLength = estim.size();
1243 for(int i=0;i<estimLength;i++){
1244 if(estim[i] == '-'){
1245 container.push_back(individual);
1249 individual += estim[i];
1252 container.push_back(individual);
1255 /* string individual;
1257 while (estim.find_first_of('-') != -1) {
1258 individual = estim.substr(0,estim.find_first_of('-'));
1259 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1260 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1261 container.push_back(individual);
1265 container.push_back(estim); */
1267 catch(exception& e) {
1268 errorOut(e, "MothurOut", "splitAtDash");
1273 /***********************************************************************/
1274 //This function parses the label options and puts them in a set
1275 void MothurOut::splitAtDash(string& estim, set<string>& container) {
1277 string individual = "";
1278 int estimLength = estim.size();
1279 for(int i=0;i<estimLength;i++){
1280 if(estim[i] == '-'){
1281 container.insert(individual);
1285 individual += estim[i];
1288 container.insert(individual);
1290 // string individual;
1292 // while (estim.find_first_of('-') != -1) {
1293 // individual = estim.substr(0,estim.find_first_of('-'));
1294 // if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1295 // estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1296 // container.insert(individual);
1300 // container.insert(estim);
1303 catch(exception& e) {
1304 errorOut(e, "MothurOut", "splitAtDash");
1308 /***********************************************************************/
1309 //This function parses the line options and puts them in a set
1310 void MothurOut::splitAtDash(string& estim, set<int>& container) {
1315 while (estim.find_first_of('-') != -1) {
1316 individual = estim.substr(0,estim.find_first_of('-'));
1317 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1318 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1319 convert(individual, lineNum); //convert the string to int
1320 container.insert(lineNum);
1324 convert(estim, lineNum); //convert the string to int
1325 container.insert(lineNum);
1327 catch(exception& e) {
1328 errorOut(e, "MothurOut", "splitAtDash");
1332 /***********************************************************************/
1333 //This function parses the a string and puts peices in a vector
1334 void MothurOut::splitAtComma(string& estim, vector<string>& container) {
1336 string individual = "";
1337 int estimLength = estim.size();
1338 for(int i=0;i<estimLength;i++){
1339 if(estim[i] == ','){
1340 container.push_back(individual);
1344 individual += estim[i];
1347 container.push_back(individual);
1352 // string individual;
1354 // while (estim.find_first_of(',') != -1) {
1355 // individual = estim.substr(0,estim.find_first_of(','));
1356 // if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
1357 // estim = estim.substr(estim.find_first_of(',')+1, estim.length());
1358 // container.push_back(individual);
1362 // container.push_back(estim);
1364 catch(exception& e) {
1365 errorOut(e, "MothurOut", "splitAtComma");
1369 /***********************************************************************/
1371 //This function splits up the various option parameters
1372 void MothurOut::splitAtComma(string& prefix, string& suffix){
1374 prefix = suffix.substr(0,suffix.find_first_of(','));
1375 if ((suffix.find_first_of(',')+2) <= suffix.length()) { //checks to make sure you don't have comma at end of string
1376 suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
1378 while(suffix.at(0) == ' ')
1379 suffix = suffix.substr(1, suffix.length());
1383 catch(exception& e) {
1384 errorOut(e, "MothurOut", "splitAtComma");
1388 /***********************************************************************/
1390 //This function separates the key value from the option value i.e. dist=96_...
1391 void MothurOut::splitAtEquals(string& key, string& value){
1393 if(value.find_first_of('=') != -1){
1394 key = value.substr(0,value.find_first_of('='));
1395 if ((value.find_first_of('=')+1) <= value.length()) {
1396 value = value.substr(value.find_first_of('=')+1, value.length());
1403 catch(exception& e) {
1404 errorOut(e, "MothurOut", "splitAtEquals");
1409 /**************************************************************************************************/
1411 bool MothurOut::inUsersGroups(string groupname, vector<string> Groups) {
1413 for (int i = 0; i < Groups.size(); i++) {
1414 if (groupname == Groups[i]) { return true; }
1418 catch(exception& e) {
1419 errorOut(e, "MothurOut", "inUsersGroups");
1423 /**************************************************************************************************/
1424 //returns true if any of the strings in first vector are in second vector
1425 bool MothurOut::inUsersGroups(vector<string> groupnames, vector<string> Groups) {
1428 for (int i = 0; i < groupnames.size(); i++) {
1429 if (inUsersGroups(groupnames[i], Groups)) { return true; }
1433 catch(exception& e) {
1434 errorOut(e, "MothurOut", "inUsersGroups");
1438 /***********************************************************************/
1439 //this function determines if the user has given us labels that are smaller than the given label.
1440 //if so then it returns true so that the calling function can run the previous valid distance.
1441 //it's a "smart" distance function. It also checks for invalid labels.
1442 bool MothurOut::anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
1445 set<string>::iterator it;
1446 vector<float> orderFloat;
1447 map<string, float> userMap; //the conversion process removes trailing 0's which we need to put back
1448 map<string, float>::iterator it2;
1450 bool smaller = false;
1452 //unique is the smallest line
1453 if (label == "unique") { return false; }
1455 if (convertTestFloat(label, labelFloat)) {
1456 convert(label, labelFloat);
1457 }else { //cant convert
1462 //go through users set and make them floats
1463 for(it = userLabels.begin(); it != userLabels.end(); ++it) {
1466 if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
1468 orderFloat.push_back(temp);
1469 userMap[*it] = temp;
1470 }else if (*it == "unique") {
1471 orderFloat.push_back(-1.0);
1472 userMap["unique"] = -1.0;
1474 if (errorOff == "") { cout << *it << " is not a valid label." << endl; }
1475 userLabels.erase(*it);
1481 sort(orderFloat.begin(), orderFloat.end());
1483 /*************************************************/
1484 //is this label bigger than any of the users labels
1485 /*************************************************/
1487 //loop through order until you find a label greater than label
1488 for (int i = 0; i < orderFloat.size(); i++) {
1489 if (orderFloat[i] < labelFloat) {
1491 if (orderFloat[i] == -1) {
1492 if (errorOff == "") { cout << "Your file does not include the label unique." << endl; }
1493 userLabels.erase("unique");
1496 if (errorOff == "") { cout << "Your file does not include the label " << endl; }
1498 for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {
1499 if (it2->second == orderFloat[i]) {
1501 //remove small labels
1502 userLabels.erase(s);
1506 if (errorOff == "") {cout << s << ". I will use the next smallest distance. " << endl; }
1508 //since they are sorted once you find a bigger one stop looking
1515 catch(exception& e) {
1516 errorOut(e, "MothurOut", "anyLabelsToProcess");
1521 /**************************************************************************************************/
1522 bool MothurOut::checkReleaseVersion(ifstream& file, string version) {
1527 string line = getline(file);
1529 //before we added this check
1530 if (line[0] != '#') { good = false; }
1533 line = line.substr(1);
1535 vector<string> versionVector;
1536 splitAtChar(version, versionVector, '.');
1538 //check file version
1539 vector<string> linesVector;
1540 splitAtChar(line, linesVector, '.');
1542 if (versionVector.size() != linesVector.size()) { good = false; }
1544 for (int j = 0; j < versionVector.size(); j++) {
1546 convert(versionVector[j], num1);
1547 convert(linesVector[j], num2);
1549 //if mothurs version is newer than this files version, then we want to remake it
1550 if (num1 > num2) { good = false; break; }
1556 if (!good) { file.close(); }
1557 else { file.seekg(0); }
1561 catch(exception& e) {
1562 errorOut(e, "MothurOut", "checkReleaseVersion");
1566 /**************************************************************************************************/