]> git.donarmstrong.com Git - mothur.git/blob - phylotypecommand.cpp
Merge remote-tracking branch 'origin/master'
[mothur.git] / phylotypecommand.cpp
1 /*
2  *  phylotypecommand.cpp
3  *  Mothur
4  *
5  *  Created by westcott on 11/20/09.
6  *  Copyright 2009 Schloss Lab. All rights reserved.
7  *
8  */
9
10 #include "phylotypecommand.h"
11 #include "phylotree.h"
12 #include "listvector.hpp"
13 #include "rabundvector.hpp"
14 #include "sabundvector.hpp"
15
16 //**********************************************************************************************************************
17 vector<string> PhylotypeCommand::setParameters(){       
18         try {
19                 CommandParameter ptaxonomy("taxonomy", "InputTypes", "", "", "none", "none", "none",false,true); parameters.push_back(ptaxonomy);
20                 CommandParameter pname("name", "InputTypes", "", "", "none", "none", "none",false,false); parameters.push_back(pname);
21                 CommandParameter pcutoff("cutoff", "Number", "", "-1", "", "", "",false,false); parameters.push_back(pcutoff);
22                 CommandParameter plabel("label", "String", "", "", "", "", "",false,false); parameters.push_back(plabel);
23                 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "",false,false); parameters.push_back(pinputdir);
24                 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "",false,false); parameters.push_back(poutputdir);
25                 
26                 vector<string> myArray;
27                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
28                 return myArray;
29         }
30         catch(exception& e) {
31                 m->errorOut(e, "PhylotypeCommand", "setParameters");
32                 exit(1);
33         }
34 }
35 //**********************************************************************************************************************
36 string PhylotypeCommand::getHelpString(){       
37         try {
38                 string helpString = "";
39                 helpString += "The phylotype command reads a taxonomy file and outputs a .list, .rabund and .sabund file. \n";
40                 helpString += "The phylotype command parameter options are taxonomy, cutoff and label. The taxonomy parameter is required.\n";
41                 helpString += "The cutoff parameter allows you to specify the level you want to stop at.  The default is the highest level in your taxonomy file. \n";
42                 helpString += "For example: taxonomy = Bacteria;Bacteroidetes-Chlorobi;Bacteroidetes; - cutoff=2, would truncate the taxonomy to Bacteria;Bacteroidetes-Chlorobi; \n";
43                 helpString += "For the cutoff parameter levels count up from the root of the phylotree. This enables you to look at the grouping down to a specific resolution, say the genus level.\n";
44                 helpString += "The label parameter allows you to specify which level you would like, and are separated by dashes.  The default all levels in your taxonomy file. \n";
45                 helpString += "For the label parameter, levels count down from the root to keep the output similiar to mothur's other commands which report information from finer resolution to coarser resolutions.\n";
46                 helpString += "The phylotype command should be in the following format: \n";
47                 helpString += "phylotype(taxonomy=yourTaxonomyFile, cutoff=yourCutoff, label=yourLabels) \n";
48                 helpString += "Eaxample: phylotype(taxonomy=amazon.taxonomy, cutoff=5, label=1-3-5).\n";
49                 return helpString;
50         }
51         catch(exception& e) {
52                 m->errorOut(e, "PhylotypeCommand", "getHelpString");
53                 exit(1);
54         }
55 }
56 //**********************************************************************************************************************
57 string PhylotypeCommand::getOutputFileNameTag(string type, string inputName=""){        
58         try {
59         string outputFileName = "";
60                 map<string, vector<string> >::iterator it;
61         
62         //is this a type this command creates
63         it = outputTypes.find(type);
64         if (it == outputTypes.end()) {  m->mothurOut("[ERROR]: this command doesn't create a " + type + " output file.\n"); }
65         else {
66             if (type == "list") {  outputFileName =  "list"; }
67             else if (type == "rabund") {  outputFileName =  "rabund"; }
68             else if (type == "sabund") {  outputFileName =  "sabund"; }
69             else { m->mothurOut("[ERROR]: No definition for type " + type + " output file tag.\n"); m->control_pressed = true;  }
70         }
71         return outputFileName;
72         }
73         catch(exception& e) {
74                 m->errorOut(e, "PhylotypeCommand", "getOutputFileNameTag");
75                 exit(1);
76         }
77 }
78 //**********************************************************************************************************************
79 PhylotypeCommand::PhylotypeCommand(){   
80         try {
81                 abort = true; calledHelp = true; 
82                 setParameters();
83                 vector<string> tempOutNames;
84                 outputTypes["list"] = tempOutNames;
85                 outputTypes["sabund"] = tempOutNames;
86                 outputTypes["rabund"] = tempOutNames;
87         }
88         catch(exception& e) {
89                 m->errorOut(e, "PhylotypeCommand", "PhylotypeCommand");
90                 exit(1);
91         }
92 }
93 /**********************************************************************************************************************/
94 PhylotypeCommand::PhylotypeCommand(string option)  {
95         try {
96                 abort = false; calledHelp = false;   
97                 
98                 //allow user to run help
99                 if(option == "help") { help(); abort = true; calledHelp = true; }
100                 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
101                 
102                 else {
103                         vector<string> myArray = setParameters();
104                         
105                         OptionParser parser(option);
106                         map<string, string> parameters = parser.getParameters(); 
107                         
108                         ValidParameters validParameter;
109                         map<string, string>::iterator it;
110                         
111                         //check to make sure all parameters are valid for command
112                         for (it = parameters.begin(); it != parameters.end(); it++) { 
113                                 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) {  abort = true;  }
114                         }
115                         
116                         //initialize outputTypes
117                         vector<string> tempOutNames;
118                         outputTypes["list"] = tempOutNames;
119                         outputTypes["sabund"] = tempOutNames;
120                         outputTypes["rabund"] = tempOutNames;
121                         
122                         //if the user changes the input directory command factory will send this info to us in the output parameter 
123                         string inputDir = validParameter.validFile(parameters, "inputdir", false);              
124                         if (inputDir == "not found"){   inputDir = "";          }
125                         else {
126                                 string path;
127                                 it = parameters.find("taxonomy");
128                                 //user has given a template file
129                                 if(it != parameters.end()){ 
130                                         path = m->hasPath(it->second);
131                                         //if the user has not given a path then, add inputdir. else leave path alone.
132                                         if (path == "") {       parameters["taxonomy"] = inputDir + it->second;         }
133                                 }
134                                 
135                                 it = parameters.find("name");
136                                 //user has given a template file
137                                 if(it != parameters.end()){ 
138                                         path = m->hasPath(it->second);
139                                         //if the user has not given a path then, add inputdir. else leave path alone.
140                                         if (path == "") {       parameters["name"] = inputDir + it->second;             }
141                                 }
142                         }
143
144                         taxonomyFileName = validParameter.validFile(parameters, "taxonomy", true);
145                         if (taxonomyFileName == "not found") { 
146                                 taxonomyFileName = m->getTaxonomyFile(); 
147                                 if (taxonomyFileName != "") {  m->mothurOut("Using " + taxonomyFileName + " as input file for the taxonomy parameter."); m->mothurOutEndLine(); }
148                                 else { 
149                                         m->mothurOut("No valid current files. taxonomy is a required parameter."); m->mothurOutEndLine(); 
150                                         abort = true; 
151                                 }
152                         }else if (taxonomyFileName == "not open") { taxonomyFileName = ""; abort = true; }      
153                         else { m->setTaxonomyFile(taxonomyFileName); }
154                         
155                         namefile = validParameter.validFile(parameters, "name", true);
156                         if (namefile == "not open") { namefile = ""; abort = true; }
157                         else if (namefile == "not found") { namefile = ""; }
158                         else { readNamesFile(); m->setNameFile(namefile); }     
159                         
160                         //if the user changes the output directory command factory will send this info to us in the output parameter 
161                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  
162                                 outputDir = ""; 
163                                 outputDir += m->hasPath(taxonomyFileName); //if user entered a file with a path then preserve it        
164                         }
165                         
166                         string temp = validParameter.validFile(parameters, "cutoff", false);
167                         if (temp == "not found") { temp = "-1"; }
168                         m->mothurConvert(temp, cutoff); 
169                         
170                         label = validParameter.validFile(parameters, "label", false);                   
171                         if (label == "not found") { label = ""; allLines = 1; }
172                         else { 
173                                 if(label != "all") {  m->splitAtDash(label, labels);  allLines = 0;  }
174                                 else { allLines = 1;  }
175                         }
176                         
177                         if (namefile == "") {
178                                 vector<string> files; files.push_back(taxonomyFileName);
179                                 parser.getNameFile(files);
180                         }
181                         
182                 }
183         }
184         catch(exception& e) {
185                 m->errorOut(e, "PhylotypeCommand", "PhylotypeCommand");
186                 exit(1);
187         }
188 }
189 /**********************************************************************************************************************/
190
191 int PhylotypeCommand::execute(){
192         try {
193         
194                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
195                 
196                 //reads in taxonomy file and makes all the taxonomies the same length 
197                 //by appending the last taxon to a given taxonomy as many times as needed to 
198                 //make it as long as the longest taxonomy in the file 
199                 TaxEqualizer* taxEqual = new TaxEqualizer(taxonomyFileName, cutoff, outputDir);
200                 
201                 if (m->control_pressed) { delete taxEqual; return 0; }
202                 
203                 string equalizedTaxFile = taxEqual->getEqualizedTaxFile();
204                 
205                 delete taxEqual;
206                 
207                 //build taxonomy tree from equalized file
208                 PhyloTree* tree = new PhyloTree(equalizedTaxFile);
209                 vector<int> leaves = tree->getGenusNodes();
210                 
211                 //store leaf nodes in current map
212                 for (int i = 0; i < leaves.size(); i++)         {       currentNodes[leaves[i]] = leaves[i];    }
213                 
214                 bool done = false;
215                 if (tree->get(leaves[0]).parent == -1) {  m->mothurOut("Empty Tree"); m->mothurOutEndLine();    done = true;    }
216                 
217                 if (m->control_pressed) { delete tree; return 0; }
218                 
219                 string fileroot = outputDir + m->getRootName(m->getSimpleName(taxonomyFileName));
220                 
221                 ofstream outList;
222                 string outputListFile = fileroot + "tx." + getOutputFileNameTag("list");
223                 m->openOutputFile(outputListFile, outList);
224                 ofstream outSabund;
225                 string outputSabundFile = fileroot + "tx." + getOutputFileNameTag("sabund");
226                 m->openOutputFile(outputSabundFile, outSabund);
227                 ofstream outRabund;
228                 string outputRabundFile = fileroot + "tx." + getOutputFileNameTag("rabund");
229                 m->openOutputFile(outputRabundFile, outRabund);
230                 
231                 outputNames.push_back(outputListFile); outputTypes["list"].push_back(outputListFile);
232                 outputNames.push_back(outputSabundFile); outputTypes["sabund"].push_back(outputSabundFile);
233                 outputNames.push_back(outputRabundFile); outputTypes["rabund"].push_back(outputRabundFile);
234                 
235                 int count = 1;          
236                 //start at leaves of tree and work towards root, processing the labels the user wants
237                 while((!done) && ((allLines == 1) || (labels.size() != 0))) {
238                 
239                         string level = toString(count); 
240                         count++;
241                         
242                         if (m->control_pressed) { 
243                                 outRabund.close(); outSabund.close(); outList.close();
244                                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  }
245                                 delete tree; return 0; 
246                         }
247                         
248                         //is this a level the user want output for
249                         if(allLines == 1 || labels.count(level) == 1){  
250                                 
251                                 //output level
252                                 m->mothurOut(level); m->mothurOutEndLine();
253                                 
254                                 ListVector list;
255                                 list.setLabel(level);
256                 
257                                 //go through nodes and build listvector 
258                                 for (itCurrent = currentNodes.begin(); itCurrent != currentNodes.end(); itCurrent++) {
259                         
260                                         //get parents
261                                         TaxNode node = tree->get(itCurrent->first);
262                                         parentNodes[node.parent] = node.parent;
263                                         
264                                         vector<string> names = node.accessions;
265                                         
266                                         //make the names compatable with listvector
267                                         string name = "";
268                                         for (int i = 0; i < names.size(); i++) {  
269                         
270                         if (names[i] != "unknown") {
271                             if (namefile != "") {       
272                                 map<string, string>::iterator itNames = namemap.find(names[i]);  //make sure this name is in namefile
273                                 
274                                 if (itNames != namemap.end()) {  name += namemap[names[i]] + ",";   } //you found it in namefile
275                                 else { m->mothurOut("[ERROR]: " + names[i] + " is not in your namefile, please correct."); m->mothurOutEndLine(); m->control_pressed = true;  }
276                                 
277                             }else{   name += names[i] + ",";    }
278                         }
279                                         }
280                     
281                     if (m->control_pressed) { break; }
282                     
283                                         name = name.substr(0, name.length()-1);  //rip off extra ','
284                                         //add bin to list vector
285                                         if (name != "") { list.push_back(name); } //caused by unknown
286                                 }       
287                                 
288                                 //print listvector
289                                 list.print(outList);
290                                 //print rabund
291                                 list.getRAbundVector().print(outRabund);
292                                 //print sabund
293                                 list.getSAbundVector().print(outSabund);
294                         
295                                 labels.erase(level);
296                                 
297                         }else {
298                                 
299                                 //just get parents
300                                 for (itCurrent = currentNodes.begin(); itCurrent != currentNodes.end(); itCurrent++) {
301                                         int parent = tree->get(itCurrent->first).parent;
302                                         parentNodes[parent] = parent;
303                                 }
304                         }
305                         
306                         //move up a level
307                         currentNodes = parentNodes;
308                         parentNodes.clear();
309                         
310                         //have we reached the rootnode
311                         if (tree->get(currentNodes.begin()->first).parent == -1)  {  done = true;  }
312                 }
313                         
314                 outList.close();
315                 outSabund.close();
316                 outRabund.close();      
317                 
318                 delete tree;
319                 
320                 if (m->control_pressed) { 
321                         for (int i = 0; i < outputNames.size(); i++) {  m->mothurRemove(outputNames[i]);  }
322                         return 0; 
323                 }
324                 
325                 //set list file as new current listfile
326                 string current = "";
327                 itTypes = outputTypes.find("list");
328                 if (itTypes != outputTypes.end()) {
329                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setListFile(current); }
330                 }
331                 
332                 //set rabund file as new current rabundfile
333                 itTypes = outputTypes.find("rabund");
334                 if (itTypes != outputTypes.end()) {
335                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setRabundFile(current); }
336                 }
337                 
338                 //set sabund file as new current sabundfile
339                 itTypes = outputTypes.find("sabund");
340                 if (itTypes != outputTypes.end()) {
341                         if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setSabundFile(current); }
342                 }               
343                 
344                 m->mothurOutEndLine();
345                 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
346                 for (int i = 0; i < outputNames.size(); i++) {  m->mothurOut(outputNames[i]); m->mothurOutEndLine();    }
347                 m->mothurOutEndLine();
348                 
349                 return 0;               
350         }
351
352         catch(exception& e) {
353                 m->errorOut(e, "PhylotypeCommand", "execute");
354                 exit(1);
355         }
356 }
357 /*****************************************************************/
358 int PhylotypeCommand::readNamesFile() {
359         try {
360                                 
361                 ifstream in;
362                 m->openInputFile(namefile, in);
363                 
364                 string first, second;
365                 map<string, string>::iterator itNames;
366                 
367                 while(!in.eof()) {
368                         in >> first >> second; m->gobble(in);
369                         
370                         itNames = namemap.find(first);
371                         if (itNames == namemap.end()) {  
372                                 namemap[first] = second; 
373                         }else {  m->mothurOut(first + " has already been seen in namefile, disregarding names file."); m->mothurOutEndLine(); in.close(); namemap.clear(); namefile = ""; return 1; }                   
374                 }
375                 in.close();
376                 
377                 return 0;
378         }
379         catch(exception& e) {
380                 m->errorOut(e, "PhylotypeCommand", "readNamesFile");
381                 exit(1);
382         }
383 }
384
385 /**********************************************************************************************************************/