5 * Created by westcott on 5/11/10.
6 * Copyright 2010 Schloss Lab. All rights reserved.
10 #include "catchallcommand.h"
11 #include "globaldata.hpp"
13 //**********************************************************************************************************************
14 vector<string> CatchAllCommand::getValidParameters(){
16 string AlignArray[] = {"sabund","shared","label","inputdir","outputdir"};
17 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
21 m->errorOut(e, "CatchAllCommand", "getValidParameters");
25 //**********************************************************************************************************************
26 CatchAllCommand::CatchAllCommand(){
28 //initialize outputTypes
29 vector<string> tempOutNames;
30 outputTypes["csv"] = tempOutNames;
31 outputTypes["summary"] = tempOutNames;
34 m->errorOut(e, "CatchAllCommand", "CatchAllCommand");
38 //**********************************************************************************************************************
39 vector<string> CatchAllCommand::getRequiredParameters(){
41 string AlignArray[] = {"sabund","shared","or"};
42 vector<string> myArray (AlignArray, AlignArray+(sizeof(AlignArray)/sizeof(string)));
46 m->errorOut(e, "CatchAllCommand", "getRequiredParameters");
50 //**********************************************************************************************************************
51 vector<string> CatchAllCommand::getRequiredFiles(){
53 vector<string> myArray;
57 m->errorOut(e, "CatchAllCommand", "getRequiredFiles");
61 /**************************************************************************************/
62 CatchAllCommand::CatchAllCommand(string option) {
64 globaldata = GlobalData::getInstance();
68 //allow user to run help
69 if(option == "help") { help(); abort = true; }
72 //valid paramters for this command
73 string Array[] = {"shared","sabund","label","inputdir","outputdir"};
74 vector<string> myArray (Array, Array+(sizeof(Array)/sizeof(string)));
76 OptionParser parser(option);
77 map<string,string> parameters = parser.getParameters();
79 ValidParameters validParameter;
80 map<string, string>::iterator it;
82 //check to make sure all parameters are valid for command
83 for (it = parameters.begin(); it != parameters.end(); it++) {
84 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
87 //initialize outputTypes
88 vector<string> tempOutNames;
89 outputTypes["csv"] = tempOutNames;
90 outputTypes["summary"] = tempOutNames;
92 //if the user changes the input directory command factory will send this info to us in the output parameter
93 string inputDir = validParameter.validFile(parameters, "inputdir", false);
94 if (inputDir == "not found"){ inputDir = ""; }
97 it = parameters.find("sabund");
98 //user has given a template file
99 if(it != parameters.end()){
100 path = m->hasPath(it->second);
101 //if the user has not given a path then, add inputdir. else leave path alone.
102 if (path == "") { parameters["sabund"] = inputDir + it->second; }
105 it = parameters.find("shared");
106 //user has given a template file
107 if(it != parameters.end()){
108 path = m->hasPath(it->second);
109 //if the user has not given a path then, add inputdir. else leave path alone.
110 if (path == "") { parameters["shared"] = inputDir + it->second; }
114 //check for required parameters
115 sabundfile = validParameter.validFile(parameters, "sabund", true);
116 if (sabundfile == "not open") { sabundfile = ""; abort = true; }
117 else if (sabundfile == "not found") { sabundfile = ""; }
118 else { globaldata->setSabundFile(sabundfile); globaldata->setFormat("sabund"); }
120 sharedfile = validParameter.validFile(parameters, "shared", true);
121 if (sharedfile == "not open") { sharedfile = ""; abort = true; }
122 else if (sharedfile == "not found") { sharedfile = ""; }
124 string label = validParameter.validFile(parameters, "label", false);
125 if (label == "not found") { label = ""; }
127 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
128 else { allLines = 1; }
131 if ((sharedfile == "") && (sabundfile == "")) { m->mothurOut("You must provide a sabund or shared file for the catchall command."); m->mothurOutEndLine(); abort=true; }
133 //if the user changes the output directory command factory will send this info to us in the output parameter
134 outputDir = validParameter.validFile(parameters, "outputdir", false);
135 if (outputDir == "not found"){
136 if (sabundfile != "") { outputDir = m->hasPath(sabundfile); }
137 else { outputDir = m->hasPath(sharedfile); }
142 catch(exception& e) {
143 m->errorOut(e, "CatchAllCommand", "CatchAllCommand");
147 //**********************************************************************************************************************
149 void CatchAllCommand::help(){
151 m->mothurOut("The catchall command interfaces mothur with the catchall program written by Linda Woodard, Sean Connolly and John Bunge.\n");
152 m->mothurOut("For more information about catchall refer to http://www.northeastern.edu/catchall/index.html \n");
153 m->mothurOut("The catchall executable must be in the same folder as your mothur executable. \n");
154 m->mothurOut("If you are a MAC or Linux user you must also have installed mono, a link to mono is on the webpage. \n");
155 m->mothurOut("The catchall command parameters are shared, sabund and label. shared or sabund is required. \n");
156 m->mothurOut("The label parameter is used to analyze specific labels in your input.\n");
157 m->mothurOut("The catchall command should be in the following format: \n");
158 m->mothurOut("catchall(sabund=yourSabundFile) \n");
159 m->mothurOut("Example: catchall(sabund=abrecovery.fn.sabund) \n");
161 catch(exception& e) {
162 m->errorOut(e, "CatchAllCommand", "help");
167 /**************************************************************************************/
168 int CatchAllCommand::execute() {
171 if (abort == true) { return 0; }
173 //prepare full output directory
174 outputDir = m->getFullPathName(outputDir);
176 //get location of catchall
177 GlobalData* globaldata = GlobalData::getInstance();
178 path = globaldata->argv;
179 path = path.substr(0, (path.find_last_of('m')));
180 path = m->getFullPathName(path);
182 string catchAllCommandExe = "";
183 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
184 catchAllCommandExe += "mono " + path + "CatchAllcmdL.exe ";
186 catchAllCommandExe += "\"" + path + "CatchAllcmdW.exe\"" + " ";
189 vector<string> inputFileNames;
190 if (sharedfile != "") { inputFileNames = parseSharedFile(sharedfile); globaldata->setFormat("sabund"); }
191 else { inputFileNames.push_back(sabundfile); }
193 for (int p = 0; p < inputFileNames.size(); p++) {
194 if (inputFileNames.size() > 1) {
195 m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[p]); m->mothurOutEndLine(); m->mothurOutEndLine();
198 InputData* input = new InputData(inputFileNames[p], "sabund");
199 SAbundVector* sabund = input->getSAbundVector();
200 string lastLabel = sabund->getLabel();
202 set<string> processedLabels;
203 set<string> userLabels = labels;
205 string summaryfilename = outputDir + m->getRootName(m->getSimpleName(inputFileNames[p])) + "catchall.summary";
206 summaryfilename = m->getFullPathName(summaryfilename);
209 m->openOutputFile(summaryfilename, out);
211 out << "label\tmodel\testimate\tlci\tuci" << endl;
213 //for each label the user selected
214 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
217 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
218 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
220 //create catchall input file from mothur's inputfile
221 string filename = process(sabund, inputFileNames[p]);
222 string outputPath = m->getPathName(filename);
224 //create system command
225 string catchAllCommand = "";
226 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
227 catchAllCommand += catchAllCommandExe + filename + " " + outputPath + " 1";
229 if (outputPath.length() > 0) { outputPath = outputPath.substr(0, outputPath.length()-1); }
230 catchAllCommand += catchAllCommandExe + "\"" + filename + "\" \"" + outputPath + "\" 1";
231 //wrap entire string in ""
232 catchAllCommand = "\"" + catchAllCommand + "\"";
235 system(catchAllCommand.c_str());
237 remove(filename.c_str());
239 filename = m->getRootName(filename); filename = filename.substr(0, filename.length()-1); //rip off extra .
241 outputNames.push_back(filename + "_Analysis.csv"); outputTypes["csv"].push_back(filename + "_Analysis.csv");
242 outputNames.push_back(filename + "_BestModelsAnalysis.csv"); outputTypes["csv"].push_back(filename + "_BestModelsAnalysis.csv");
243 outputNames.push_back(filename + "_BestModelsFits.csv"); outputTypes["csv"].push_back(filename + "_BestModelsFits.csv");
244 outputNames.push_back(filename + "_BubblePlot.csv"); outputTypes["csv"].push_back(filename + "_BubblePlot.csv");
246 createSummaryFile(filename + "_BestModelsAnalysis.csv", sabund->getLabel(), out);
248 if (m->control_pressed) { out.close(); for (int i = 0; i < outputNames.size(); i++) {remove(outputNames[i].c_str()); } delete input; delete sabund; return 0; }
250 processedLabels.insert(sabund->getLabel());
251 userLabels.erase(sabund->getLabel());
254 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
255 string saveLabel = sabund->getLabel();
258 sabund = (input->getSAbundVector(lastLabel));
260 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
263 //create catchall input file from mothur's inputfile
264 string filename = process(sabund, inputFileNames[p]);
265 string outputPath = m->getPathName(filename);
267 //create system command
268 string catchAllCommand = "";
269 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
270 catchAllCommand += catchAllCommandExe + filename + " " + outputPath + " 1";
272 if (outputPath.length() > 0) { outputPath = outputPath.substr(0, outputPath.length()-1); }
273 catchAllCommand += catchAllCommandExe + "\"" + filename + "\" \"" + outputPath + "\" 1";
274 catchAllCommand = "\"" + catchAllCommand + "\"";
278 system(catchAllCommand.c_str());
280 remove(filename.c_str());
282 filename = m->getRootName(filename); filename = filename.substr(0, filename.length()-1); //rip off extra .
284 outputNames.push_back(filename + "_Analysis.csv"); outputTypes["csv"].push_back(filename + "_Analysis.csv");
285 outputNames.push_back(filename + "_BestModelsAnalysis.csv"); outputTypes["csv"].push_back(filename + "_BestModelsAnalysis.csv");
286 outputNames.push_back(filename + "_BestModelsFits.csv"); outputTypes["csv"].push_back(filename + "_BestModelsFits.csv");
287 outputNames.push_back(filename + "_BubblePlot.csv"); outputTypes["csv"].push_back(filename + "_BubblePlot.csv");
289 createSummaryFile(filename + "_BestModelsAnalysis.csv", sabund->getLabel(), out);
291 if (m->control_pressed) { out.close(); for (int i = 0; i < outputNames.size(); i++) {remove(outputNames[i].c_str()); } delete input; delete sabund; return 0; }
293 processedLabels.insert(sabund->getLabel());
294 userLabels.erase(sabund->getLabel());
296 //restore real lastlabel to save below
297 sabund->setLabel(saveLabel);
301 lastLabel = sabund->getLabel();
304 sabund = (input->getSAbundVector());
307 //output error messages about any remaining user labels
308 set<string>::iterator it;
309 bool needToRun = false;
310 for (it = userLabels.begin(); it != userLabels.end(); it++) {
311 m->mothurOut("Your file does not include the label " + *it);
312 if (processedLabels.count(lastLabel) != 1) {
313 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
316 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
320 //run last label if you need to
321 if (needToRun == true) {
322 if (sabund != NULL) { delete sabund; }
323 sabund = (input->getSAbundVector(lastLabel));
325 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
327 //create catchall input file from mothur's inputfile
328 string filename = process(sabund, inputFileNames[p]);
329 string outputPath = m->getPathName(filename);
331 //create system command
332 string catchAllCommand = "";
333 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
334 catchAllCommand += catchAllCommandExe + filename + " " + outputPath + " 1";
336 if (outputPath.length() > 0) { outputPath = outputPath.substr(0, outputPath.length()-1); }
337 catchAllCommand += catchAllCommandExe + "\"" + filename + "\" \"" + outputPath + "\" 1";
338 catchAllCommand = "\"" + catchAllCommand + "\"";
342 system(catchAllCommand.c_str());
344 remove(filename.c_str());
346 filename = m->getRootName(filename); filename = filename.substr(0, filename.length()-1); //rip off extra .
348 outputNames.push_back(filename + "_Analysis.csv"); outputTypes["csv"].push_back(filename + "_Analysis.csv");
349 outputNames.push_back(filename + "_BestModelsAnalysis.csv"); outputTypes["csv"].push_back(filename + "_BestModelsAnalysis.csv");
350 outputNames.push_back(filename + "_BestModelsFits.csv"); outputTypes["csv"].push_back(filename + "_BestModelsFits.csv");
351 outputNames.push_back(filename + "_BubblePlot.csv"); outputTypes["csv"].push_back(filename + "_BubblePlot.csv");
353 createSummaryFile(filename + "_BestModelsAnalysis.csv", sabund->getLabel(), out);
361 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {remove(outputNames[i].c_str()); } return 0; }
365 if (sharedfile == "") {
366 string summaryfilename = outputDir + m->getRootName(m->getSimpleName(inputFileNames[0])) + "catchall.summary";
367 summaryfilename = m->getFullPathName(summaryfilename);
368 outputNames.push_back(summaryfilename); outputTypes["summary"].push_back(summaryfilename);
369 }else { //combine summaries
370 vector<string> sumNames;
371 for (int i = 0; i < inputFileNames.size(); i++) {
372 sumNames.push_back(m->getFullPathName(outputDir + m->getRootName(m->getSimpleName(inputFileNames[i])) + "catchall.summary"));
374 string summaryfilename = combineSummmary(sumNames);
375 outputNames.push_back(summaryfilename); outputTypes["summary"].push_back(summaryfilename);
378 m->mothurOutEndLine();
379 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
380 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
381 m->mothurOutEndLine();
386 catch(exception& e) {
387 m->errorOut(e, "CatchAllCommand", "execute");
391 //**********************************************************************************************************************
392 string CatchAllCommand::process(SAbundVector* sabund, string file1) {
394 string filename = outputDir + m->getRootName(m->getSimpleName(file1)) + sabund->getLabel() + ".csv";
395 filename = m->getFullPathName(filename);
398 m->openOutputFile(filename, out);
400 for (int i = 1; i <= sabund->getMaxRank(); i++) {
401 int temp = sabund->get(i);
404 out << i << "," << temp << endl;
412 catch(exception& e) {
413 m->errorOut(e, "CatchAllCommand", "process");
417 //*********************************************************************************************************************
418 string CatchAllCommand::combineSummmary(vector<string>& outputNames) {
422 string combineFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + "catchall.summary";
425 m->openOutputFile(combineFileName, out);
427 out << "label\tgroup\tmodel\testimate\tlci\tuci" << endl;
429 //open each groups summary file
430 string newLabel = "";
432 map<string, vector<string> > files;
433 for (int i=0; i<outputNames.size(); i++) {
434 vector<string> thisFilesLines;
437 m->openInputFile(outputNames[i], temp);
439 //read through first line - labels
444 while (!temp.eof()) {
446 string thisLine = "";
449 for (int j = 0; j < 5; j++) {
453 if (j == 1) { thisLine += groups[i] + "\t" + tempLabel + "\t"; }
454 else{ thisLine += tempLabel + "\t"; }
459 thisFilesLines.push_back(thisLine);
464 files[outputNames[i]] = thisFilesLines;
466 numLines = thisFilesLines.size();
469 remove(outputNames[i].c_str());
473 for (int k = 0; k < numLines; k++) {
475 //grab summary data for each group
476 for (int i=0; i<outputNames.size(); i++) {
477 out << files[outputNames[i]][k];
484 //return combine file name
485 return combineFileName;
488 catch(exception& e) {
489 m->errorOut(e, "CatchAllCommand", "combineSummmary");
493 //**********************************************************************************************************************
494 int CatchAllCommand::createSummaryFile(string file1, string label, ofstream& out) {
498 m->openInputFile(file1, in);
502 string header = m->getline(in); m->gobble(in);
504 int pos = header.find("Total Number of Observed Species =");
505 string numString = "";
508 if (pos == string::npos) { m->mothurOut("[ERROR]: cannot parse " + file1); m->mothurOutEndLine(); }
510 //pos will be the position of the T in total, so we want to count to the position of =
521 if (pos > header.length()) { m->mothurOut("Cannot find number of OTUs in " + file1); m->mothurOutEndLine(); in.close(); return 0; }
525 string firstline = m->getline(in); m->gobble(in);
526 vector<string> values;
527 m->splitAtComma(firstline, values);
529 values.pop_back(); //last value is always a blank string since the last character in the line is always a ','
531 if (values.size() == 1) { //grab next line if firstline didn't have what you wanted
532 string secondline = m->getline(in); m->gobble(in);
534 m->splitAtComma(secondline, values);
536 values.pop_back(); //last value is always a blank string since the last character in the line is always a ','
539 if (values.size() == 1) { //still not what we wanted fill values with numOTUs
540 values.resize(8, "");
542 values[4] = numString;
543 values[6] = numString;
544 values[7] = numString;
547 if (values.size() < 8) { values.resize(8, ""); }
549 out << label << '\t' << values[1] << '\t' << values[4] << '\t' << values[6] << '\t' << values[7] << endl;
557 catch(exception& e) {
558 m->errorOut(e, "CatchAllCommand", "createSummaryFile");
562 //**********************************************************************************************************************
563 vector<string> CatchAllCommand::parseSharedFile(string filename) {
565 vector<string> filenames;
568 InputData* input = new InputData(filename, "sharedfile");
569 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
571 string sharedFileRoot = outputDir + m->getRootName(m->getSimpleName(filename));
573 //clears file before we start to write to it below
574 for (int i=0; i<lookup.size(); i++) {
575 remove((sharedFileRoot + lookup[i]->getGroup() + ".sabund").c_str());
576 filenames.push_back((sharedFileRoot + lookup[i]->getGroup() + ".sabund"));
577 groups.push_back(lookup[i]->getGroup());
580 while(lookup[0] != NULL) {
582 for (int i = 0; i < lookup.size(); i++) {
583 SAbundVector sav = lookup[i]->getSAbundVector();
585 m->openOutputFileAppend(sharedFileRoot + lookup[i]->getGroup() + ".sabund", out);
590 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
591 lookup = input->getSharedRAbundVectors();
598 catch(exception& e) {
599 m->errorOut(e, "CatchAllCommand", "parseSharedFile");
603 /**************************************************************************************/