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 //check for shared file loaded during read.otu
125 if (sharedfile == "") {
126 if (globaldata->getSharedFile() != "") { sharedfile = globaldata->getSharedFile(); }
129 string label = validParameter.validFile(parameters, "label", false);
130 if (label == "not found") { label = ""; }
132 if(label != "all") { m->splitAtDash(label, labels); allLines = 0; }
133 else { allLines = 1; }
136 if ((sharedfile == "") && (sabundfile == "")) { m->mothurOut("You must provide a sabund or shared file for the catchall command."); m->mothurOutEndLine(); abort=true; }
138 //if the user changes the output directory command factory will send this info to us in the output parameter
139 outputDir = validParameter.validFile(parameters, "outputdir", false);
140 if (outputDir == "not found"){
141 if (sabundfile != "") { outputDir = m->hasPath(sabundfile); }
142 else { outputDir = m->hasPath(sharedfile); }
147 catch(exception& e) {
148 m->errorOut(e, "CatchAllCommand", "CatchAllCommand");
152 //**********************************************************************************************************************
154 void CatchAllCommand::help(){
156 m->mothurOut("The catchall command interfaces mothur with the catchall program written by Linda Woodard, Sean Connolly and John Bunge.\n");
157 m->mothurOut("For more information about catchall refer to http://www.northeastern.edu/catchall/index.html \n");
158 m->mothurOut("The catchall executable must be in the same folder as your mothur executable. \n");
159 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");
160 m->mothurOut("The catchall command parameters are shared, sabund and label. shared or sabund is required. \n");
161 m->mothurOut("The label parameter is used to analyze specific labels in your input.\n");
162 m->mothurOut("The catchall command should be in the following format: \n");
163 m->mothurOut("catchall(sabund=yourSabundFile) \n");
164 m->mothurOut("Example: catchall(sabund=abrecovery.fn.sabund) \n");
166 catch(exception& e) {
167 m->errorOut(e, "CatchAllCommand", "help");
172 /**************************************************************************************/
173 int CatchAllCommand::execute() {
176 if (abort == true) { return 0; }
178 //prepare full output directory
179 outputDir = m->getFullPathName(outputDir);
181 //get location of catchall
182 GlobalData* globaldata = GlobalData::getInstance();
183 path = globaldata->argv;
184 path = path.substr(0, (path.find_last_of('m')));
185 path = m->getFullPathName(path);
187 string catchAllCommandExe = "";
188 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
189 catchAllCommandExe += "mono " + path + "CatchAllcmdL.exe ";
191 catchAllCommandExe += "\"" + path + "CatchAllcmdW.exe\"" + " ";
194 vector<string> inputFileNames;
195 if (sharedfile != "") { inputFileNames = parseSharedFile(sharedfile); globaldata->setFormat("sabund"); }
196 else { inputFileNames.push_back(sabundfile); }
198 for (int p = 0; p < inputFileNames.size(); p++) {
199 if (inputFileNames.size() > 1) {
200 m->mothurOutEndLine(); m->mothurOut("Processing group " + groups[p]); m->mothurOutEndLine(); m->mothurOutEndLine();
203 InputData* input = new InputData(inputFileNames[p], "sabund");
204 SAbundVector* sabund = input->getSAbundVector();
205 string lastLabel = sabund->getLabel();
207 set<string> processedLabels;
208 set<string> userLabels = labels;
210 string summaryfilename = outputDir + m->getRootName(m->getSimpleName(inputFileNames[p])) + "catchall.summary";
211 summaryfilename = m->getFullPathName(summaryfilename);
214 m->openOutputFile(summaryfilename, out);
216 out << "label\tmodel\testimate\tlci\tuci" << endl;
218 //for each label the user selected
219 while((sabund != NULL) && ((allLines == 1) || (userLabels.size() != 0))) {
222 if(allLines == 1 || labels.count(sabund->getLabel()) == 1){
223 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
225 //create catchall input file from mothur's inputfile
226 string filename = process(sabund, inputFileNames[p]);
227 string outputPath = m->getPathName(filename);
229 //create system command
230 string catchAllCommand = "";
231 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
232 catchAllCommand += catchAllCommandExe + filename + " " + outputPath + " 1";
234 if (outputPath.length() > 0) { outputPath = outputPath.substr(0, outputPath.length()-1); }
235 catchAllCommand += catchAllCommandExe + "\"" + filename + "\" \"" + outputPath + "\" 1";
236 //wrap entire string in ""
237 catchAllCommand = "\"" + catchAllCommand + "\"";
240 system(catchAllCommand.c_str());
242 remove(filename.c_str());
244 filename = m->getRootName(filename); filename = filename.substr(0, filename.length()-1); //rip off extra .
246 outputNames.push_back(filename + "_Analysis.csv"); outputTypes["csv"].push_back(filename + "_Analysis.csv");
247 outputNames.push_back(filename + "_BestModelsAnalysis.csv"); outputTypes["csv"].push_back(filename + "_BestModelsAnalysis.csv");
248 outputNames.push_back(filename + "_BestModelsFits.csv"); outputTypes["csv"].push_back(filename + "_BestModelsFits.csv");
249 outputNames.push_back(filename + "_BubblePlot.csv"); outputTypes["csv"].push_back(filename + "_BubblePlot.csv");
251 createSummaryFile(filename + "_BestModelsAnalysis.csv", sabund->getLabel(), out);
253 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; }
255 processedLabels.insert(sabund->getLabel());
256 userLabels.erase(sabund->getLabel());
259 if ((m->anyLabelsToProcess(sabund->getLabel(), userLabels, "") == true) && (processedLabels.count(lastLabel) != 1)) {
260 string saveLabel = sabund->getLabel();
263 sabund = (input->getSAbundVector(lastLabel));
265 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
268 //create catchall input file from mothur's inputfile
269 string filename = process(sabund, inputFileNames[p]);
270 string outputPath = m->getPathName(filename);
272 //create system command
273 string catchAllCommand = "";
274 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
275 catchAllCommand += catchAllCommandExe + filename + " " + outputPath + " 1";
277 if (outputPath.length() > 0) { outputPath = outputPath.substr(0, outputPath.length()-1); }
278 catchAllCommand += catchAllCommandExe + "\"" + filename + "\" \"" + outputPath + "\" 1";
279 catchAllCommand = "\"" + catchAllCommand + "\"";
283 system(catchAllCommand.c_str());
285 remove(filename.c_str());
287 filename = m->getRootName(filename); filename = filename.substr(0, filename.length()-1); //rip off extra .
289 outputNames.push_back(filename + "_Analysis.csv"); outputTypes["csv"].push_back(filename + "_Analysis.csv");
290 outputNames.push_back(filename + "_BestModelsAnalysis.csv"); outputTypes["csv"].push_back(filename + "_BestModelsAnalysis.csv");
291 outputNames.push_back(filename + "_BestModelsFits.csv"); outputTypes["csv"].push_back(filename + "_BestModelsFits.csv");
292 outputNames.push_back(filename + "_BubblePlot.csv"); outputTypes["csv"].push_back(filename + "_BubblePlot.csv");
294 createSummaryFile(filename + "_BestModelsAnalysis.csv", sabund->getLabel(), out);
296 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; }
298 processedLabels.insert(sabund->getLabel());
299 userLabels.erase(sabund->getLabel());
301 //restore real lastlabel to save below
302 sabund->setLabel(saveLabel);
306 lastLabel = sabund->getLabel();
309 sabund = (input->getSAbundVector());
312 //output error messages about any remaining user labels
313 set<string>::iterator it;
314 bool needToRun = false;
315 for (it = userLabels.begin(); it != userLabels.end(); it++) {
316 m->mothurOut("Your file does not include the label " + *it);
317 if (processedLabels.count(lastLabel) != 1) {
318 m->mothurOut(". I will use " + lastLabel + "."); m->mothurOutEndLine();
321 m->mothurOut(". Please refer to " + lastLabel + "."); m->mothurOutEndLine();
325 //run last label if you need to
326 if (needToRun == true) {
327 if (sabund != NULL) { delete sabund; }
328 sabund = (input->getSAbundVector(lastLabel));
330 m->mothurOut(sabund->getLabel()); m->mothurOutEndLine();
332 //create catchall input file from mothur's inputfile
333 string filename = process(sabund, inputFileNames[p]);
334 string outputPath = m->getPathName(filename);
336 //create system command
337 string catchAllCommand = "";
338 #if defined (__APPLE__) || (__MACH__) || (linux) || (__linux)
339 catchAllCommand += catchAllCommandExe + filename + " " + outputPath + " 1";
341 if (outputPath.length() > 0) { outputPath = outputPath.substr(0, outputPath.length()-1); }
342 catchAllCommand += catchAllCommandExe + "\"" + filename + "\" \"" + outputPath + "\" 1";
343 catchAllCommand = "\"" + catchAllCommand + "\"";
347 system(catchAllCommand.c_str());
349 remove(filename.c_str());
351 filename = m->getRootName(filename); filename = filename.substr(0, filename.length()-1); //rip off extra .
353 outputNames.push_back(filename + "_Analysis.csv"); outputTypes["csv"].push_back(filename + "_Analysis.csv");
354 outputNames.push_back(filename + "_BestModelsAnalysis.csv"); outputTypes["csv"].push_back(filename + "_BestModelsAnalysis.csv");
355 outputNames.push_back(filename + "_BestModelsFits.csv"); outputTypes["csv"].push_back(filename + "_BestModelsFits.csv");
356 outputNames.push_back(filename + "_BubblePlot.csv"); outputTypes["csv"].push_back(filename + "_BubblePlot.csv");
358 createSummaryFile(filename + "_BestModelsAnalysis.csv", sabund->getLabel(), out);
366 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {remove(outputNames[i].c_str()); } return 0; }
370 if (sharedfile == "") {
371 string summaryfilename = outputDir + m->getRootName(m->getSimpleName(inputFileNames[0])) + "catchall.summary";
372 summaryfilename = m->getFullPathName(summaryfilename);
373 outputNames.push_back(summaryfilename); outputTypes["summary"].push_back(summaryfilename);
374 }else { //combine summaries
375 vector<string> sumNames;
376 for (int i = 0; i < inputFileNames.size(); i++) {
377 sumNames.push_back(m->getFullPathName(outputDir + m->getRootName(m->getSimpleName(inputFileNames[i])) + "catchall.summary"));
379 string summaryfilename = combineSummmary(sumNames);
380 outputNames.push_back(summaryfilename); outputTypes["summary"].push_back(summaryfilename);
383 m->mothurOutEndLine();
384 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
385 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
386 m->mothurOutEndLine();
391 catch(exception& e) {
392 m->errorOut(e, "CatchAllCommand", "execute");
396 //**********************************************************************************************************************
397 string CatchAllCommand::process(SAbundVector* sabund, string file1) {
399 string filename = outputDir + m->getRootName(m->getSimpleName(file1)) + sabund->getLabel() + ".csv";
400 filename = m->getFullPathName(filename);
403 m->openOutputFile(filename, out);
405 for (int i = 1; i <= sabund->getMaxRank(); i++) {
406 int temp = sabund->get(i);
409 out << i << "," << temp << endl;
417 catch(exception& e) {
418 m->errorOut(e, "CatchAllCommand", "process");
422 //*********************************************************************************************************************
423 string CatchAllCommand::combineSummmary(vector<string>& outputNames) {
427 string combineFileName = outputDir + m->getRootName(m->getSimpleName(sharedfile)) + "catchall.summary";
430 m->openOutputFile(combineFileName, out);
432 out << "label\tgroup\tmodel\testimate\tlci\tuci" << endl;
434 //open each groups summary file
435 string newLabel = "";
437 map<string, vector<string> > files;
438 for (int i=0; i<outputNames.size(); i++) {
439 vector<string> thisFilesLines;
442 m->openInputFile(outputNames[i], temp);
444 //read through first line - labels
449 while (!temp.eof()) {
451 string thisLine = "";
454 for (int j = 0; j < 5; j++) {
458 if (j == 1) { thisLine += groups[i] + "\t" + tempLabel + "\t"; }
459 else{ thisLine += tempLabel + "\t"; }
464 thisFilesLines.push_back(thisLine);
469 files[outputNames[i]] = thisFilesLines;
471 numLines = thisFilesLines.size();
474 remove(outputNames[i].c_str());
478 for (int k = 0; k < numLines; k++) {
480 //grab summary data for each group
481 for (int i=0; i<outputNames.size(); i++) {
482 out << files[outputNames[i]][k];
489 //return combine file name
490 return combineFileName;
493 catch(exception& e) {
494 m->errorOut(e, "CatchAllCommand", "combineSummmary");
498 //**********************************************************************************************************************
499 int CatchAllCommand::createSummaryFile(string file1, string label, ofstream& out) {
503 int able = m->openInputFile(file1, in, "noerror");
505 if (able == 1) { m->mothurOut("[ERROR]: the catchall program did not run properly. Please check to make sure it is located in the same folder as your mothur executable.");m->mothurOutEndLine(); m->control_pressed = true; return 0; }
509 string header = m->getline(in); m->gobble(in);
511 int pos = header.find("Total Number of Observed Species =");
512 string numString = "";
515 if (pos == string::npos) { m->mothurOut("[ERROR]: cannot parse " + file1); m->mothurOutEndLine(); }
517 //pos will be the position of the T in total, so we want to count to the position of =
528 if (pos > header.length()) { m->mothurOut("Cannot find number of OTUs in " + file1); m->mothurOutEndLine(); in.close(); return 0; }
532 string firstline = m->getline(in); m->gobble(in);
533 vector<string> values;
534 m->splitAtComma(firstline, values);
536 values.pop_back(); //last value is always a blank string since the last character in the line is always a ','
538 if (values.size() == 1) { //grab next line if firstline didn't have what you wanted
539 string secondline = m->getline(in); m->gobble(in);
541 m->splitAtComma(secondline, values);
543 values.pop_back(); //last value is always a blank string since the last character in the line is always a ','
546 if (values.size() == 1) { //still not what we wanted fill values with numOTUs
547 values.resize(8, "");
549 values[4] = numString;
550 values[6] = numString;
551 values[7] = numString;
554 if (values.size() < 8) { values.resize(8, ""); }
556 out << label << '\t' << values[1] << '\t' << values[4] << '\t' << values[6] << '\t' << values[7] << endl;
564 catch(exception& e) {
565 m->errorOut(e, "CatchAllCommand", "createSummaryFile");
569 //**********************************************************************************************************************
570 vector<string> CatchAllCommand::parseSharedFile(string filename) {
572 vector<string> filenames;
575 InputData* input = new InputData(filename, "sharedfile");
576 vector<SharedRAbundVector*> lookup = input->getSharedRAbundVectors();
578 string sharedFileRoot = outputDir + m->getRootName(m->getSimpleName(filename));
580 //clears file before we start to write to it below
581 for (int i=0; i<lookup.size(); i++) {
582 remove((sharedFileRoot + lookup[i]->getGroup() + ".sabund").c_str());
583 filenames.push_back((sharedFileRoot + lookup[i]->getGroup() + ".sabund"));
584 groups.push_back(lookup[i]->getGroup());
587 while(lookup[0] != NULL) {
589 for (int i = 0; i < lookup.size(); i++) {
590 SAbundVector sav = lookup[i]->getSAbundVector();
592 m->openOutputFileAppend(sharedFileRoot + lookup[i]->getGroup() + ".sabund", out);
597 for (int i = 0; i < lookup.size(); i++) { delete lookup[i]; }
598 lookup = input->getSharedRAbundVectors();
605 catch(exception& e) {
606 m->errorOut(e, "CatchAllCommand", "parseSharedFile");
610 /**************************************************************************************/