5 * Created by westcott on 2/25/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "mothurout.h"
13 /******************************************************/
14 MothurOut* MothurOut::getInstance() {
15 if( _uniqueInstance == 0) {
16 _uniqueInstance = new MothurOut();
18 return _uniqueInstance;
20 /*********************************************************************************************/
21 void MothurOut::setFileName(string filename) {
23 logFileName = filename;
27 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
29 if (pid == 0) { //only one process should output to screen
32 openOutputFile(filename, out);
39 errorOut(e, "MothurOut", "setFileName");
43 /*********************************************************************************************/
44 void MothurOut::setDefaultPath(string pathname) {
47 //add / to name if needed
48 string lastChar = pathname.substr(pathname.length()-1);
49 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
50 if (lastChar != "/") { pathname += "/"; }
52 if (lastChar != "\\") { pathname += "\\"; }
55 defaultPath = pathname;
59 errorOut(e, "MothurOut", "setDefaultPath");
63 /*********************************************************************************************/
64 void MothurOut::setOutputDir(string pathname) {
69 errorOut(e, "MothurOut", "setOutputDir");
73 /*********************************************************************************************/
74 void MothurOut::closeLog() {
79 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
81 if (pid == 0) { //only one process should output to screen
91 errorOut(e, "MothurOut", "closeLog");
96 /*********************************************************************************************/
97 MothurOut::~MothurOut() {
102 catch(exception& e) {
103 errorOut(e, "MothurOut", "MothurOut");
107 /*********************************************************************************************/
108 void MothurOut::mothurOut(string output) {
113 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
115 if (pid == 0) { //only one process should output to screen
125 catch(exception& e) {
126 errorOut(e, "MothurOut", "MothurOut");
130 /*********************************************************************************************/
131 void MothurOut::mothurOutEndLine() {
135 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
137 if (pid == 0) { //only one process should output to screen
147 catch(exception& e) {
148 errorOut(e, "MothurOut", "MothurOutEndLine");
152 /*********************************************************************************************/
153 void MothurOut::mothurOutJustToLog(string output) {
157 MPI_Comm_rank(MPI_COMM_WORLD, &pid);
159 if (pid == 0) { //only one process should output to screen
168 catch(exception& e) {
169 errorOut(e, "MothurOut", "MothurOutJustToLog");
173 /*********************************************************************************************/
174 void MothurOut::errorOut(exception& e, string object, string function) {
176 //mem_usage(vm, rss);
178 mothurOut("[ERROR]: ");
179 mothurOut(toString(e.what()));
180 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.");
183 /*********************************************************************************************/
184 //The following was originally from http://stackoverflow.com/questions/669438/how-to-get-memory-usage-at-run-time-in-c
185 // process_mem_usage(double &, double &) - takes two doubles by reference,
186 // attempts to read the system-dependent data for a process' virtual memory
187 // size and resident set size, and return the results in KB.
189 // On failure, returns 0.0, 0.0
190 int MothurOut::mem_usage(double& vm_usage, double& resident_set) {
191 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
196 // 'file' stat seems to give the most reliable results
198 ifstream stat_stream("/proc/self/stat",ios_base::in);
200 // dummy vars for leading entries in stat that we don't care about
202 string pid, comm, state, ppid, pgrp, session, tty_nr;
203 string tpgid, flags, minflt, cminflt, majflt, cmajflt;
204 string utime, stime, cutime, cstime, priority, nice;
205 string O, itrealvalue, starttime;
207 // the two fields we want
212 stat_stream >> pid >> comm >> state >> ppid >> pgrp >> session >> tty_nr
213 >> tpgid >> flags >> minflt >> cminflt >> majflt >> cmajflt
214 >> utime >> stime >> cutime >> cstime >> priority >> nice
215 >> O >> itrealvalue >> starttime >> vsize >> rss; // don't care about the rest
217 long page_size_kb = sysconf(_SC_PAGE_SIZE) / 1024; // in case x86-64 is configured to use 2MB pages
218 vm_usage = vsize / 1024.0;
219 resident_set = rss * page_size_kb;
221 mothurOut("Memory Usage: vm = " + toString(vm_usage) + " rss = " + toString(resident_set) + "\n");
225 /* //windows memory usage
226 // Get the list of process identifiers.
227 DWORD aProcesses[1024], cbNeeded, cProcesses;
229 if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) ){ return 1; }
231 // Calculate how many process identifiers were returned.
232 cProcesses = cbNeeded / sizeof(DWORD);
234 // Print the memory usage for each process
235 for (int i = 0; i < cProcesses; i++ ) {
236 DWORD processID = aProcesses[i];
238 PROCESS_MEMORY_COUNTERS pmc;
240 HANDLE hProcess = OpenProcess((PROCESS_QUERY_INFORMATION | PROCESS_VM_READ), FALSE, processID);
242 // Print the process identifier.
243 printf( "\nProcess ID: %u\n", processID);
245 if (NULL != hProcess) {
247 if ( GetProcessMemoryInfo( hProcess, &pmc, sizeof(pmc)) ) {
248 printf( "\tPageFaultCount: 0x%08X\n", pmc.PageFaultCount );
249 printf( "\tPeakWorkingSetSize: 0x%08X\n", pmc.PeakWorkingSetSize );
250 printf( "\tWorkingSetSize: 0x%08X\n", pmc.WorkingSetSize );
251 printf( "\tQuotaPeakPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakPagedPoolUsage );
252 printf( "\tQuotaPagedPoolUsage: 0x%08X\n", pmc.QuotaPagedPoolUsage );
253 printf( "\tQuotaPeakNonPagedPoolUsage: 0x%08X\n", pmc.QuotaPeakNonPagedPoolUsage );
254 printf( "\tQuotaNonPagedPoolUsage: 0x%08X\n", pmc.QuotaNonPagedPoolUsage );
255 printf( "\tPagefileUsage: 0x%08X\n", pmc.PagefileUsage );
256 printf( "\tPeakPagefileUsage: 0x%08X\n", pmc.PeakPagefileUsage );
258 CloseHandle(hProcess);
268 /***********************************************************************/
269 int MothurOut::openOutputFileAppend(string fileName, ofstream& fileHandle){
271 fileName = getFullPathName(fileName);
273 fileHandle.open(fileName.c_str(), ios::app);
275 mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
282 catch(exception& e) {
283 errorOut(e, "MothurOut", "openOutputFileAppend");
287 /***********************************************************************/
288 void MothurOut::gobble(istream& f){
292 while(isspace(d=f.get())) { ;}
295 catch(exception& e) {
296 errorOut(e, "MothurOut", "gobble");
300 /***********************************************************************/
301 void MothurOut::gobble(istringstream& f){
304 while(isspace(d=f.get())) {;}
307 catch(exception& e) {
308 errorOut(e, "MothurOut", "gobble");
313 /***********************************************************************/
315 string MothurOut::getline(istringstream& fileHandle) {
320 while (!fileHandle.eof()) {
322 char c = fileHandle.get();
324 //are you at the end of the line
325 if ((c == '\n') || (c == '\r') || (c == '\f')){ break; }
332 catch(exception& e) {
333 errorOut(e, "MothurOut", "getline");
337 /***********************************************************************/
339 string MothurOut::getline(ifstream& fileHandle) {
344 while (!fileHandle.eof()) {
346 char c = fileHandle.get();
348 //are you at the end of the line
349 if ((c == '\n') || (c == '\r') || (c == '\f')){ break; }
356 catch(exception& e) {
357 errorOut(e, "MothurOut", "getline");
361 /***********************************************************************/
363 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
364 #ifdef USE_COMPRESSION
365 inline bool endsWith(string s, const char * suffix){
366 size_t suffixLength = strlen(suffix);
367 return s.size() >= suffixLength && s.substr(s.size() - suffixLength, suffixLength).compare(suffix) == 0;
372 string MothurOut::getRootName(string longName){
375 string rootName = longName;
377 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
378 #ifdef USE_COMPRESSION
379 if (endsWith(rootName, ".gz") || endsWith(rootName, ".bz2")) {
380 int pos = rootName.find_last_of('.');
381 rootName = rootName.substr(0, pos);
382 cerr << "shortening " << longName << " to " << rootName << "\n";
386 if(rootName.find_last_of(".") != rootName.npos){
387 int pos = rootName.find_last_of('.')+1;
388 rootName = rootName.substr(0, pos);
393 catch(exception& e) {
394 errorOut(e, "MothurOut", "getRootName");
398 /***********************************************************************/
400 string MothurOut::getSimpleName(string longName){
402 string simpleName = longName;
405 found=longName.find_last_of("/\\");
407 if(found != longName.npos){
408 simpleName = longName.substr(found+1);
413 catch(exception& e) {
414 errorOut(e, "MothurOut", "getSimpleName");
419 /***********************************************************************/
421 string MothurOut::getPathName(string longName){
423 string rootPathName = longName;
425 if(longName.find_last_of("/\\") != longName.npos){
426 int pos = longName.find_last_of("/\\")+1;
427 rootPathName = longName.substr(0, pos);
432 catch(exception& e) {
433 errorOut(e, "MothurOut", "getPathName");
438 /***********************************************************************/
440 string MothurOut::hasPath(string longName){
445 found=longName.find_last_of("~/\\");
447 if(found != longName.npos){
448 path = longName.substr(0, found+1);
453 catch(exception& e) {
454 errorOut(e, "MothurOut", "hasPath");
459 /***********************************************************************/
461 string MothurOut::getExtension(string longName){
463 string extension = longName;
465 if(longName.find_last_of('.') != longName.npos){
466 int pos = longName.find_last_of('.');
467 extension = longName.substr(pos, longName.length());
472 catch(exception& e) {
473 errorOut(e, "MothurOut", "getExtension");
477 /***********************************************************************/
478 bool MothurOut::isBlank(string fileName){
481 fileName = getFullPathName(fileName);
484 fileHandle.open(fileName.c_str());
486 mothurOut("[ERROR]: Could not open " + fileName); mothurOutEndLine();
489 //check for blank file
491 if (fileHandle.eof()) { fileHandle.close(); return true; }
495 catch(exception& e) {
496 errorOut(e, "MothurOut", "isBlank");
500 /***********************************************************************/
502 string MothurOut::getFullPathName(string fileName){
505 string path = hasPath(fileName);
509 if (path == "") { return fileName; } //its a simple name
510 else { //we need to complete the pathname
511 // ex. ../../../filename
512 // cwd = /user/work/desktop
515 //get current working directory
516 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
518 if (path.find("~") != -1) { //go to home directory
521 char *homepath = NULL;
522 homepath = getenv ("HOME");
523 if ( homepath != NULL) { homeDir = homepath; }
524 else { homeDir = ""; }
526 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
529 if (path.rfind("./") == string::npos) { return fileName; } //already complete name
530 else { newFileName = fileName.substr(fileName.rfind("./")+2); } //save the complete part of the name
532 //char* cwdpath = new char[1024];
534 //cwdpath=getcwd(cwdpath,size);
537 char *cwdpath = NULL;
538 cwdpath = getcwd(NULL, 0); // or _getcwd
539 if ( cwdpath != NULL) { cwd = cwdpath; }
545 if (cwd.length() > 0) { simpleCWD = cwd.substr(1); }
547 //break apart the current working directory
549 while (simpleCWD.find_first_of('/') != string::npos) {
550 string dir = simpleCWD.substr(0,simpleCWD.find_first_of('/'));
551 simpleCWD = simpleCWD.substr(simpleCWD.find_first_of('/')+1, simpleCWD.length());
554 //get last one // ex. ../../../filename = /user/work/desktop/filename
555 dirs.push_back(simpleCWD); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
558 int index = dirs.size()-1;
560 while((pos = path.rfind("./")) != string::npos) { //while you don't have a complete path
561 if (pos == 0) { break; //you are at the end
562 }else if (path[(pos-1)] == '.') { //you want your parent directory ../
563 path = path.substr(0, pos-1);
565 if (index == 0) { break; }
566 }else if (path[(pos-1)] == '/') { //you want the current working dir ./
567 path = path.substr(0, pos);
568 }else if (pos == 1) { break; //you are at the end
569 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
572 for (int i = index; i >= 0; i--) {
573 newFileName = dirs[i] + "/" + newFileName;
576 newFileName = "/" + newFileName;
580 if (path.find("~") != string::npos) { //go to home directory
581 string homeDir = getenv ("HOMEPATH");
582 newFileName = homeDir + fileName.substr(fileName.find("~")+1);
585 if (path.rfind(".\\") == string::npos) { return fileName; } //already complete name
586 else { newFileName = fileName.substr(fileName.rfind(".\\")+2); } //save the complete part of the name
588 char *cwdpath = NULL;
589 cwdpath = getcwd(NULL, 0); // or _getcwd
590 if ( cwdpath != NULL) { cwd = cwdpath; }
593 //break apart the current working directory
595 while (cwd.find_first_of('\\') != -1) {
596 string dir = cwd.substr(0,cwd.find_first_of('\\'));
597 cwd = cwd.substr(cwd.find_first_of('\\')+1, cwd.length());
602 dirs.push_back(cwd); //ex. dirs[0] = user, dirs[1] = work, dirs[2] = desktop
604 int index = dirs.size()-1;
606 while((pos = path.rfind(".\\")) != string::npos) { //while you don't have a complete path
607 if (pos == 0) { break; //you are at the end
608 }else if (path[(pos-1)] == '.') { //you want your parent directory ../
609 path = path.substr(0, pos-1);
611 if (index == 0) { break; }
612 }else if (path[(pos-1)] == '\\') { //you want the current working dir ./
613 path = path.substr(0, pos);
614 }else if (pos == 1) { break; //you are at the end
615 }else { cout << "cannot resolve path for " << fileName << endl; return fileName; }
618 for (int i = index; i >= 0; i--) {
619 newFileName = dirs[i] + "\\" + newFileName;
628 catch(exception& e) {
629 errorOut(e, "MothurOut", "getFullPathName");
633 /***********************************************************************/
635 int MothurOut::openInputFile(string fileName, ifstream& fileHandle, string m){
638 string completeFileName = getFullPathName(fileName);
639 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
640 #ifdef USE_COMPRESSION
641 // check for gzipped or bzipped file
642 if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
643 string tempName = string(tmpnam(0));
644 mkfifo(tempName.c_str(), 0666);
645 int fork_result = fork();
646 if (fork_result < 0) {
647 cerr << "Error forking.\n";
649 } else if (fork_result == 0) {
650 string command = (endsWith(completeFileName, ".gz") ? "zcat " : "bzcat ") + completeFileName + string(" > ") + tempName;
651 cerr << "Decompressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
652 system(command.c_str());
653 cerr << "Done decompressing " << completeFileName << "\n";
654 remove(tempName.c_str());
657 cerr << "waiting on child process " << fork_result << "\n";
658 completeFileName = tempName;
663 fileHandle.open(completeFileName.c_str());
665 //mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
668 //check for blank file
673 catch(exception& e) {
674 errorOut(e, "MothurOut", "openInputFile - no Error");
678 /***********************************************************************/
680 int MothurOut::openInputFile(string fileName, ifstream& fileHandle){
684 string completeFileName = getFullPathName(fileName);
685 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
686 #ifdef USE_COMPRESSION
687 // check for gzipped or bzipped file
688 if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
689 string tempName = string(tmpnam(0));
690 mkfifo(tempName.c_str(), 0666);
691 int fork_result = fork();
692 if (fork_result < 0) {
693 cerr << "Error forking.\n";
695 } else if (fork_result == 0) {
696 string command = (endsWith(completeFileName, ".gz") ? "zcat " : "bzcat ") + completeFileName + string(" > ") + tempName;
697 cerr << "Decompressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
698 system(command.c_str());
699 cerr << "Done decompressing " << completeFileName << "\n";
700 remove(tempName.c_str());
703 cerr << "waiting on child process " << fork_result << "\n";
704 completeFileName = tempName;
710 fileHandle.open(completeFileName.c_str());
712 mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
716 //check for blank file
718 if (fileHandle.eof()) { mothurOut("[ERROR]: " + completeFileName + " is blank. Please correct."); mothurOutEndLine(); }
723 catch(exception& e) {
724 errorOut(e, "MothurOut", "openInputFile");
728 /***********************************************************************/
730 int MothurOut::renameFile(string oldName, string newName){
733 int exist = openInputFile(newName, inTest, "");
735 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
736 if (exist == 0) { //you could open it so you want to delete it
738 string command = "rm " + newName;
739 system(command.c_str());
742 string command = "mv " + oldName + " " + newName;
743 system(command.c_str());
745 remove(newName.c_str());
746 int renameOk = rename(oldName.c_str(), newName.c_str());
751 catch(exception& e) {
752 errorOut(e, "MothurOut", "renameFile");
757 /***********************************************************************/
759 int MothurOut::openOutputFile(string fileName, ofstream& fileHandle){
762 string completeFileName = getFullPathName(fileName);
763 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
764 #ifdef USE_COMPRESSION
765 // check for gzipped file
766 if (endsWith(completeFileName, ".gz") || endsWith(completeFileName, ".bz2")) {
767 string tempName = string(tmpnam(0));
768 mkfifo(tempName.c_str(), 0666);
769 cerr << "Compressing " << completeFileName << " via temporary named pipe " << tempName << "\n";
770 int fork_result = fork();
771 if (fork_result < 0) {
772 cerr << "Error forking.\n";
774 } else if (fork_result == 0) {
775 string command = string(endsWith(completeFileName, ".gz") ? "gzip" : "bzip2") + " -v > " + completeFileName + string(" < ") + tempName;
776 system(command.c_str());
779 completeFileName = tempName;
784 fileHandle.open(completeFileName.c_str(), ios::trunc);
786 mothurOut("[ERROR]: Could not open " + completeFileName); mothurOutEndLine();
793 catch(exception& e) {
794 errorOut(e, "MothurOut", "openOutputFile");
800 /**************************************************************************************************/
801 void MothurOut::appendFiles(string temp, string filename) {
806 //open output file in append mode
807 openOutputFileAppend(filename, output);
808 int ableToOpen = openInputFile(temp, input, "no error");
809 //int ableToOpen = openInputFile(temp, input);
811 if (ableToOpen == 0) { //you opened it
812 while(char c = input.get()){
813 if(input.eof()) { break; }
814 else { output << c; }
821 catch(exception& e) {
822 errorOut(e, "MothurOut", "appendFiles");
827 /**************************************************************************************************/
828 string MothurOut::sortFile(string distFile, string outputDir){
831 //if (outputDir == "") { outputDir += hasPath(distFile); }
832 string outfile = getRootName(distFile) + "sorted.dist";
835 //if you can, use the unix sort since its been optimized for years
836 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
837 string command = "sort -n -k +3 " + distFile + " -o " + outfile;
838 system(command.c_str());
839 #else //you are stuck with my best attempt...
840 //windows sort does not have a way to specify a column, only a character in the line
841 //since we cannot assume that the distance will always be at the the same character location on each line
842 //due to variable sequence name lengths, I chose to force the distance into first position, then sort and then put it back.
844 //read in file line by file and put distance first
845 string tempDistFile = distFile + ".temp";
848 openInputFile(distFile, input);
849 openOutputFile(tempDistFile, output);
851 string firstName, secondName;
854 input >> firstName >> secondName >> dist;
855 output << dist << '\t' << firstName << '\t' << secondName << endl;
862 //sort using windows sort
863 string tempOutfile = outfile + ".temp";
864 string command = "sort " + tempDistFile + " /O " + tempOutfile;
865 system(command.c_str());
867 //read in sorted file and put distance at end again
869 openInputFile(tempOutfile, input2);
870 openOutputFile(outfile, output);
873 input2 >> dist >> firstName >> secondName;
874 output << firstName << '\t' << secondName << '\t' << dist << endl;
881 remove(tempDistFile.c_str());
882 remove(tempOutfile.c_str());
887 catch(exception& e) {
888 errorOut(e, "MothurOut", "sortFile");
892 /**************************************************************************************************/
893 vector<unsigned long int> MothurOut::setFilePosFasta(string filename, int& num) {
895 vector<unsigned long int> positions;
897 openInputFile(filename, inFASTA);
900 while(!inFASTA.eof()){
901 input = getline(inFASTA);
902 if (input.length() != 0) {
903 if(input[0] == '>'){ unsigned long int pos = inFASTA.tellg(); positions.push_back(pos - input.length() - 1); }
905 gobble(inFASTA); //has to be here since windows line endings are 2 characters and mess up the positions
909 num = positions.size();
914 //get num bytes in file
915 pFile = fopen (filename.c_str(),"rb");
916 if (pFile==NULL) perror ("Error opening file");
918 fseek (pFile, 0, SEEK_END);
923 unsigned long int size = positions[(positions.size()-1)];
925 openInputFile(filename, in);
929 while(char c = in.get()){
930 if(in.eof()) { break; }
935 positions.push_back(size);
939 catch(exception& e) {
940 errorOut(e, "MothurOut", "setFilePosFasta");
944 /**************************************************************************************************/
945 vector<unsigned long int> MothurOut::setFilePosEachLine(string filename, int& num) {
947 filename = getFullPathName(filename);
949 vector<unsigned long int> positions;
951 openInputFile(filename, in);
955 unsigned long int lastpos = in.tellg();
957 if (input.length() != 0) {
958 unsigned long int pos = in.tellg();
959 if (pos != -1) { positions.push_back(pos - input.length() - 1); }
960 else { positions.push_back(lastpos); }
962 gobble(in); //has to be here since windows line endings are 2 characters and mess up the positions
966 num = positions.size();
969 unsigned long int size;
971 //get num bytes in file
972 pFile = fopen (filename.c_str(),"rb");
973 if (pFile==NULL) perror ("Error opening file");
975 fseek (pFile, 0, SEEK_END);
980 positions.push_back(size);
984 catch(exception& e) {
985 errorOut(e, "MothurOut", "setFilePosEachLine");
989 /**************************************************************************************************/
991 vector<unsigned long int> MothurOut::divideFile(string filename, int& proc) {
994 vector<unsigned long int> filePos;
995 filePos.push_back(0);
998 unsigned long int size;
1000 filename = getFullPathName(filename);
1002 //get num bytes in file
1003 pFile = fopen (filename.c_str(),"rb");
1004 if (pFile==NULL) perror ("Error opening file");
1006 fseek (pFile, 0, SEEK_END);
1011 //estimate file breaks
1012 unsigned long int chunkSize = 0;
1013 chunkSize = size / proc;
1015 //file to small to divide by processors
1016 if (chunkSize == 0) { proc = 1; filePos.push_back(size); return filePos; }
1018 //for each process seekg to closest file break and search for next '>' char. make that the filebreak
1019 for (int i = 0; i < proc; i++) {
1020 unsigned long int spot = (i+1) * chunkSize;
1023 openInputFile(filename, in);
1027 unsigned long int newSpot = spot;
1030 if (c == '>') { in.putback(c); newSpot = in.tellg(); break; }
1033 //there was not another sequence before the end of the file
1034 unsigned long int sanityPos = in.tellg();
1036 if (sanityPos == -1) { break; }
1037 else { filePos.push_back(newSpot); }
1043 filePos.push_back(size);
1045 //sanity check filePos
1046 for (int i = 0; i < (filePos.size()-1); i++) {
1047 if (filePos[(i+1)] <= filePos[i]) { filePos.erase(filePos.begin()+(i+1)); i--; }
1050 proc = (filePos.size() - 1);
1054 catch(exception& e) {
1055 errorOut(e, "MothurOut", "divideFile");
1060 /***********************************************************************/
1062 bool MothurOut::isTrue(string f){
1065 for (int i = 0; i < f.length(); i++) { f[i] = toupper(f[i]); }
1067 if ((f == "TRUE") || (f == "T")) { return true; }
1068 else { return false; }
1070 catch(exception& e) {
1071 errorOut(e, "MothurOut", "isTrue");
1076 /***********************************************************************/
1078 float MothurOut::roundDist(float dist, int precision){
1080 return int(dist * precision + 0.5)/float(precision);
1082 catch(exception& e) {
1083 errorOut(e, "MothurOut", "roundDist");
1087 /***********************************************************************/
1089 float MothurOut::ceilDist(float dist, int precision){
1091 return int(ceil(dist * precision))/float(precision);
1093 catch(exception& e) {
1094 errorOut(e, "MothurOut", "ceilDist");
1099 /***********************************************************************/
1101 int MothurOut::getNumNames(string names){
1107 for(int i=0;i<names.size();i++){
1108 if(names[i] == ','){
1116 catch(exception& e) {
1117 errorOut(e, "MothurOut", "getNumNames");
1122 /**************************************************************************************************/
1124 vector<vector<double> > MothurOut::binomial(int maxOrder){
1126 vector<vector<double> > binomial(maxOrder+1);
1128 for(int i=0;i<=maxOrder;i++){
1129 binomial[i].resize(maxOrder+1);
1138 for(int i=2;i<=maxOrder;i++){
1142 for(int i=2;i<=maxOrder;i++){
1143 for(int j=1;j<=maxOrder;j++){
1144 if(i==j){ binomial[i][j]=1; }
1145 if(j>i) { binomial[i][j]=0; }
1146 else { binomial[i][j]=binomial[i-1][j-1]+binomial[i-1][j]; }
1153 catch(exception& e) {
1154 errorOut(e, "MothurOut", "binomial");
1159 /***********************************************************************/
1161 int MothurOut::factorial(int num){
1165 for (int i = 1; i <= num; i++) {
1171 catch(exception& e) {
1172 errorOut(e, "MothurOut", "factorial");
1176 /***********************************************************************/
1178 int MothurOut::getNumSeqs(ifstream& file){
1180 int numSeqs = count(istreambuf_iterator<char>(file),istreambuf_iterator<char>(), '>');
1184 catch(exception& e) {
1185 errorOut(e, "MothurOut", "getNumSeqs");
1189 /***********************************************************************/
1190 void MothurOut::getNumSeqs(ifstream& file, int& numSeqs){
1195 input = getline(file);
1196 if (input.length() != 0) {
1197 if(input[0] == '>'){ numSeqs++; }
1201 catch(exception& e) {
1202 errorOut(e, "MothurOut", "getNumSeqs");
1206 /***********************************************************************/
1208 //This function parses the estimator options and puts them in a vector
1209 void MothurOut::splitAtChar(string& estim, vector<string>& container, char symbol) {
1211 string individual = "";
1212 int estimLength = estim.size();
1213 for(int i=0;i<estimLength;i++){
1214 if(estim[i] == symbol){
1215 container.push_back(individual);
1219 individual += estim[i];
1222 container.push_back(individual);
1225 catch(exception& e) {
1226 errorOut(e, "MothurOut", "splitAtChar");
1231 /***********************************************************************/
1233 //This function parses the estimator options and puts them in a vector
1234 void MothurOut::splitAtDash(string& estim, vector<string>& container) {
1236 string individual = "";
1237 int estimLength = estim.size();
1238 for(int i=0;i<estimLength;i++){
1239 if(estim[i] == '-'){
1240 container.push_back(individual);
1244 individual += estim[i];
1247 container.push_back(individual);
1250 /* string individual;
1252 while (estim.find_first_of('-') != -1) {
1253 individual = estim.substr(0,estim.find_first_of('-'));
1254 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1255 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1256 container.push_back(individual);
1260 container.push_back(estim); */
1262 catch(exception& e) {
1263 errorOut(e, "MothurOut", "splitAtDash");
1268 /***********************************************************************/
1269 //This function parses the label options and puts them in a set
1270 void MothurOut::splitAtDash(string& estim, set<string>& container) {
1272 string individual = "";
1273 int estimLength = estim.size();
1274 for(int i=0;i<estimLength;i++){
1275 if(estim[i] == '-'){
1276 container.insert(individual);
1280 individual += estim[i];
1283 container.insert(individual);
1285 // string individual;
1287 // while (estim.find_first_of('-') != -1) {
1288 // individual = estim.substr(0,estim.find_first_of('-'));
1289 // if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1290 // estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1291 // container.insert(individual);
1295 // container.insert(estim);
1298 catch(exception& e) {
1299 errorOut(e, "MothurOut", "splitAtDash");
1303 /***********************************************************************/
1304 //This function parses the line options and puts them in a set
1305 void MothurOut::splitAtDash(string& estim, set<int>& container) {
1310 while (estim.find_first_of('-') != -1) {
1311 individual = estim.substr(0,estim.find_first_of('-'));
1312 if ((estim.find_first_of('-')+1) <= estim.length()) { //checks to make sure you don't have dash at end of string
1313 estim = estim.substr(estim.find_first_of('-')+1, estim.length());
1314 convert(individual, lineNum); //convert the string to int
1315 container.insert(lineNum);
1319 convert(estim, lineNum); //convert the string to int
1320 container.insert(lineNum);
1322 catch(exception& e) {
1323 errorOut(e, "MothurOut", "splitAtDash");
1327 /***********************************************************************/
1328 //This function parses the a string and puts peices in a vector
1329 void MothurOut::splitAtComma(string& estim, vector<string>& container) {
1331 string individual = "";
1332 int estimLength = estim.size();
1333 for(int i=0;i<estimLength;i++){
1334 if(estim[i] == ','){
1335 container.push_back(individual);
1339 individual += estim[i];
1342 container.push_back(individual);
1347 // string individual;
1349 // while (estim.find_first_of(',') != -1) {
1350 // individual = estim.substr(0,estim.find_first_of(','));
1351 // if ((estim.find_first_of(',')+1) <= estim.length()) { //checks to make sure you don't have comma at end of string
1352 // estim = estim.substr(estim.find_first_of(',')+1, estim.length());
1353 // container.push_back(individual);
1357 // container.push_back(estim);
1359 catch(exception& e) {
1360 errorOut(e, "MothurOut", "splitAtComma");
1364 /***********************************************************************/
1366 //This function splits up the various option parameters
1367 void MothurOut::splitAtComma(string& prefix, string& suffix){
1369 prefix = suffix.substr(0,suffix.find_first_of(','));
1370 if ((suffix.find_first_of(',')+2) <= suffix.length()) { //checks to make sure you don't have comma at end of string
1371 suffix = suffix.substr(suffix.find_first_of(',')+1, suffix.length());
1373 while(suffix.at(0) == ' ')
1374 suffix = suffix.substr(1, suffix.length());
1378 catch(exception& e) {
1379 errorOut(e, "MothurOut", "splitAtComma");
1383 /***********************************************************************/
1385 //This function separates the key value from the option value i.e. dist=96_...
1386 void MothurOut::splitAtEquals(string& key, string& value){
1388 if(value.find_first_of('=') != -1){
1389 key = value.substr(0,value.find_first_of('='));
1390 if ((value.find_first_of('=')+1) <= value.length()) {
1391 value = value.substr(value.find_first_of('=')+1, value.length());
1398 catch(exception& e) {
1399 errorOut(e, "MothurOut", "splitAtEquals");
1404 /**************************************************************************************************/
1406 bool MothurOut::inUsersGroups(string groupname, vector<string> Groups) {
1408 for (int i = 0; i < Groups.size(); i++) {
1409 if (groupname == Groups[i]) { return true; }
1413 catch(exception& e) {
1414 errorOut(e, "MothurOut", "inUsersGroups");
1418 /**************************************************************************************************/
1419 //returns true if any of the strings in first vector are in second vector
1420 bool MothurOut::inUsersGroups(vector<string> groupnames, vector<string> Groups) {
1423 for (int i = 0; i < groupnames.size(); i++) {
1424 if (inUsersGroups(groupnames[i], Groups)) { return true; }
1428 catch(exception& e) {
1429 errorOut(e, "MothurOut", "inUsersGroups");
1433 /***********************************************************************/
1434 //this function determines if the user has given us labels that are smaller than the given label.
1435 //if so then it returns true so that the calling function can run the previous valid distance.
1436 //it's a "smart" distance function. It also checks for invalid labels.
1437 bool MothurOut::anyLabelsToProcess(string label, set<string>& userLabels, string errorOff) {
1440 set<string>::iterator it;
1441 vector<float> orderFloat;
1442 map<string, float> userMap; //the conversion process removes trailing 0's which we need to put back
1443 map<string, float>::iterator it2;
1445 bool smaller = false;
1447 //unique is the smallest line
1448 if (label == "unique") { return false; }
1450 if (convertTestFloat(label, labelFloat)) {
1451 convert(label, labelFloat);
1452 }else { //cant convert
1457 //go through users set and make them floats
1458 for(it = userLabels.begin(); it != userLabels.end();) {
1461 if ((*it != "unique") && (convertTestFloat(*it, temp) == true)){
1463 orderFloat.push_back(temp);
1464 userMap[*it] = temp;
1466 }else if (*it == "unique") {
1467 orderFloat.push_back(-1.0);
1468 userMap["unique"] = -1.0;
1471 if (errorOff == "") { mothurOut(*it + " is not a valid label."); mothurOutEndLine(); }
1472 userLabels.erase(it++);
1477 sort(orderFloat.begin(), orderFloat.end());
1479 /*************************************************/
1480 //is this label bigger than any of the users labels
1481 /*************************************************/
1483 //loop through order until you find a label greater than label
1484 for (int i = 0; i < orderFloat.size(); i++) {
1485 if (orderFloat[i] < labelFloat) {
1487 if (orderFloat[i] == -1) {
1488 if (errorOff == "") { mothurOut("Your file does not include the label unique."); mothurOutEndLine(); }
1489 userLabels.erase("unique");
1492 if (errorOff == "") { mothurOut("Your file does not include the label "); mothurOutEndLine(); }
1494 for (it2 = userMap.begin(); it2!= userMap.end(); it2++) {
1495 if (it2->second == orderFloat[i]) {
1497 //remove small labels
1498 userLabels.erase(s);
1502 if (errorOff == "") {mothurOut( s + ". I will use the next smallest distance. "); mothurOutEndLine(); }
1504 //since they are sorted once you find a bigger one stop looking
1511 catch(exception& e) {
1512 errorOut(e, "MothurOut", "anyLabelsToProcess");
1517 /**************************************************************************************************/
1518 bool MothurOut::checkReleaseVersion(ifstream& file, string version) {
1523 string line = getline(file);
1525 //before we added this check
1526 if (line[0] != '#') { good = false; }
1529 line = line.substr(1);
1531 vector<string> versionVector;
1532 splitAtChar(version, versionVector, '.');
1534 //check file version
1535 vector<string> linesVector;
1536 splitAtChar(line, linesVector, '.');
1538 if (versionVector.size() != linesVector.size()) { good = false; }
1540 for (int j = 0; j < versionVector.size(); j++) {
1542 convert(versionVector[j], num1);
1543 convert(linesVector[j], num2);
1545 //if mothurs version is newer than this files version, then we want to remake it
1546 if (num1 > num2) { good = false; break; }
1552 if (!good) { file.close(); }
1553 else { file.seekg(0); }
1557 catch(exception& e) {
1558 errorOut(e, "MothurOut", "checkReleaseVersion");
1563 /**************************************************************************************************/