2 // classifytreecommand.cpp
5 // Created by Sarah Westcott on 2/20/12.
6 // Copyright (c) 2012 Schloss Lab. All rights reserved.
9 #include "classifytreecommand.h"
10 #include "phylotree.h"
11 #include "treereader.h"
13 //**********************************************************************************************************************
14 vector<string> ClassifyTreeCommand::setParameters(){
16 CommandParameter ptree("tree", "InputTypes", "", "", "", "", "none","tree-summary",false,true,true); parameters.push_back(ptree);
17 CommandParameter ptaxonomy("taxonomy", "InputTypes", "", "", "", "", "none","",false,true,true); parameters.push_back(ptaxonomy);
18 CommandParameter pname("name", "InputTypes", "", "", "NameCount", "none", "none","",false,false,true); parameters.push_back(pname);
19 CommandParameter pcount("count", "InputTypes", "", "", "NameCount-CountGroup", "none", "none","",false,false,true); parameters.push_back(pcount);
20 CommandParameter pgroup("group", "InputTypes", "", "", "CountGroup", "none", "none","",false,false,true); parameters.push_back(pgroup);
21 CommandParameter pcutoff("cutoff", "Number", "", "51", "", "", "","",false,true); parameters.push_back(pcutoff);
22 CommandParameter pinputdir("inputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(pinputdir);
23 CommandParameter poutputdir("outputdir", "String", "", "", "", "", "","",false,false); parameters.push_back(poutputdir);
25 vector<string> myArray;
26 for (int i = 0; i < parameters.size(); i++) { myArray.push_back(parameters[i].name); }
30 m->errorOut(e, "ClassifyTreeCommand", "setParameters");
34 //**********************************************************************************************************************
35 string ClassifyTreeCommand::getHelpString(){
37 string helpString = "";
38 helpString += "The classify.tree command reads a tree and taxonomy file and output the consensus taxonomy for each node on the tree. \n";
39 helpString += "If you provide a group file, the concensus for each group will also be provided. \n";
40 helpString += "The new tree contains labels at each internal node. The label is the node number so you can relate the tree to the summary file.\n";
41 helpString += "The count parameter allows you add a count file so you can have the summary totals broken up by group.\n";
42 helpString += "The summary file lists the concensus taxonomy for the descendants of each node.\n";
43 helpString += "The classify.tree command parameters are tree, group, name, count and taxonomy. The tree and taxonomy files are required.\n";
44 helpString += "The cutoff parameter allows you to specify a consensus confidence threshold for your taxonomy. The default is 51, meaning 51%. Cutoff cannot be below 51.\n";
45 helpString += "The classify.tree command should be used in the following format: classify.tree(tree=test.tre, group=test.group, taxonomy=test.taxonomy)\n";
46 helpString += "Note: No spaces between parameter labels (i.e. tree), '=' and parameters (i.e.yourTreefile).\n";
50 m->errorOut(e, "ClassifyTreeCommand", "getHelpString");
54 //**********************************************************************************************************************
55 string ClassifyTreeCommand::getOutputPattern(string type) {
59 if (type == "summary") { pattern = "[filename],taxonomy.summary"; } //makes file like: amazon.0.03.fasta
60 else if (type == "tree") { pattern = "[filename],taxonomy.tre"; }
61 else { m->mothurOut("[ERROR]: No definition for type " + type + " output pattern.\n"); m->control_pressed = true; }
66 m->errorOut(e, "ClassifyTreeCommand", "getOutputPattern");
70 //**********************************************************************************************************************
71 ClassifyTreeCommand::ClassifyTreeCommand(){
73 abort = true; calledHelp = true;
75 vector<string> tempOutNames;
76 outputTypes["tree"] = tempOutNames;
77 outputTypes["summary"] = tempOutNames;
80 m->errorOut(e, "ClassifyTreeCommand", "ClassifyTreeCommand");
84 //**********************************************************************************************************************
85 ClassifyTreeCommand::ClassifyTreeCommand(string option) {
87 abort = false; calledHelp = false;
89 //allow user to run help
90 if(option == "help") { help(); abort = true; calledHelp = true; }
91 else if(option == "citation") { citation(); abort = true; calledHelp = true;}
94 vector<string> myArray = setParameters();
96 OptionParser parser(option);
97 map<string, string> parameters = parser.getParameters();
99 ValidParameters validParameter;
100 map<string, string>::iterator it;
102 //check to make sure all parameters are valid for command
103 for (it = parameters.begin(); it != parameters.end(); it++) {
104 if (validParameter.isValidParameter(it->first, myArray, it->second) != true) { abort = true; }
107 vector<string> tempOutNames;
108 outputTypes["tree"] = tempOutNames;
109 outputTypes["summary"] = tempOutNames;
111 //if the user changes the input directory command factory will send this info to us in the output parameter
112 string inputDir = validParameter.validFile(parameters, "inputdir", false);
113 if (inputDir == "not found"){ inputDir = ""; }
116 it = parameters.find("tree");
117 //user has given a template file
118 if(it != parameters.end()){
119 path = m->hasPath(it->second);
120 //if the user has not given a path then, add inputdir. else leave path alone.
121 if (path == "") { parameters["tree"] = inputDir + it->second; }
124 it = parameters.find("name");
125 //user has given a template file
126 if(it != parameters.end()){
127 path = m->hasPath(it->second);
128 //if the user has not given a path then, add inputdir. else leave path alone.
129 if (path == "") { parameters["name"] = inputDir + it->second; }
132 it = parameters.find("group");
133 //user has given a template file
134 if(it != parameters.end()){
135 path = m->hasPath(it->second);
136 //if the user has not given a path then, add inputdir. else leave path alone.
137 if (path == "") { parameters["group"] = inputDir + it->second; }
140 it = parameters.find("taxonomy");
141 //user has given a template file
142 if(it != parameters.end()){
143 path = m->hasPath(it->second);
144 //if the user has not given a path then, add inputdir. else leave path alone.
145 if (path == "") { parameters["taxonomy"] = inputDir + it->second; }
148 it = parameters.find("count");
149 //user has given a template file
150 if(it != parameters.end()){
151 path = m->hasPath(it->second);
152 //if the user has not given a path then, add inputdir. else leave path alone.
153 if (path == "") { parameters["count"] = inputDir + it->second; }
157 outputDir = validParameter.validFile(parameters, "outputdir", false); if (outputDir == "not found"){ outputDir = ""; }
159 //check for required parameters
160 treefile = validParameter.validFile(parameters, "tree", true);
161 if (treefile == "not open") { treefile = ""; abort = true; }
162 else if (treefile == "not found") { treefile = "";
163 treefile = m->getTreeFile();
164 if (treefile != "") { m->mothurOut("Using " + treefile + " as input file for the tree parameter."); m->mothurOutEndLine(); }
165 else { m->mothurOut("No valid current files. You must provide a tree file."); m->mothurOutEndLine(); abort = true; }
166 }else { m->setTreeFile(treefile); }
168 taxonomyfile = validParameter.validFile(parameters, "taxonomy", true);
169 if (taxonomyfile == "not open") { taxonomyfile = ""; abort = true; }
170 else if (taxonomyfile == "not found") { taxonomyfile = "";
171 taxonomyfile = m->getTaxonomyFile();
172 if (taxonomyfile != "") { m->mothurOut("Using " + taxonomyfile + " as input file for the taxonomy parameter."); m->mothurOutEndLine(); }
173 else { m->mothurOut("No valid current files. You must provide a taxonomy file."); m->mothurOutEndLine(); abort = true; }
174 }else { m->setTaxonomyFile(taxonomyfile); }
176 namefile = validParameter.validFile(parameters, "name", true);
177 if (namefile == "not open") { namefile = ""; abort = true; }
178 else if (namefile == "not found") { namefile = ""; }
179 else { m->setNameFile(namefile); }
181 groupfile = validParameter.validFile(parameters, "group", true);
182 if (groupfile == "not open") { groupfile = ""; abort = true; }
183 else if (groupfile == "not found") { groupfile = ""; }
184 else { m->setGroupFile(groupfile); }
186 countfile = validParameter.validFile(parameters, "count", true);
187 if (countfile == "not open") { countfile = ""; abort = true; }
188 else if (countfile == "not found") { countfile = ""; }
189 else { m->setCountTableFile(countfile); }
191 if ((namefile != "") && (countfile != "")) {
192 m->mothurOut("[ERROR]: you may only use one of the following: name or count."); m->mothurOutEndLine(); abort = true;
195 if ((groupfile != "") && (countfile != "")) {
196 m->mothurOut("[ERROR]: you may only use one of the following: group or count."); m->mothurOutEndLine(); abort=true;
199 string temp = validParameter.validFile(parameters, "cutoff", false); if (temp == "not found") { temp = "51"; }
200 m->mothurConvert(temp, cutoff);
202 if ((cutoff < 51) || (cutoff > 100)) { m->mothurOut("cutoff must be above 50, and no greater than 100."); m->mothurOutEndLine(); abort = true; }
204 if (countfile == "") {
205 if (namefile == "") {
206 vector<string> files; files.push_back(treefile);
207 parser.getNameFile(files);
212 catch(exception& e) {
213 m->errorOut(e, "ClassifyTreeCommand", "ClassifyTreeCommand");
217 //**********************************************************************************************************************
219 int ClassifyTreeCommand::execute(){
222 if (abort == true) { if (calledHelp) { return 0; } return 2; }
224 cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
226 int start = time(NULL);
228 /***************************************************/
229 // reading tree info //
230 /***************************************************/
231 m->setTreeFile(treefile);
233 TreeReader* reader = new TreeReader(treefile, groupfile, namefile);
234 vector<Tree*> T = reader->getTrees();
235 CountTable* tmap = T[0]->getCountTable();
236 Tree* outputTree = T[0];
239 if (namefile != "") { m->readNames(namefile, nameMap, nameCount); }
241 if (m->control_pressed) { delete tmap; delete outputTree; return 0; }
243 m->readTax(taxonomyfile, taxMap);
245 /***************************************************/
246 // get concensus taxonomies //
247 /***************************************************/
248 getClassifications(outputTree);
249 delete outputTree; delete tmap;
251 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) { m->mothurRemove(outputNames[i]); } return 0; }
253 //set tree file as new current treefile
254 if (treefile != "") {
256 itTypes = outputTypes.find("tree");
257 if (itTypes != outputTypes.end()) {
258 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTreeFile(current); }
262 m->mothurOutEndLine(); m->mothurOutEndLine(); m->mothurOut("It took " + toString(time(NULL) - start) + " secs to find the concensus taxonomies."); m->mothurOutEndLine();
263 m->mothurOutEndLine();
264 m->mothurOut("Output File Names: "); m->mothurOutEndLine();
265 for (int i = 0; i < outputNames.size(); i++) { m->mothurOut(outputNames[i]); m->mothurOutEndLine(); }
266 m->mothurOutEndLine();
270 catch(exception& e) {
271 m->errorOut(e, "ClassifyTreeCommand", "execute");
275 //**********************************************************************************************************************
276 //traverse tree finding concensus taxonomy at each node
277 //label node with a number to relate to output summary file
278 //report all concensus taxonomies to file
279 int ClassifyTreeCommand::getClassifications(Tree*& T){
282 string thisOutputDir = outputDir;
283 if (outputDir == "") { thisOutputDir += m->hasPath(treefile); }
284 map<string, string> variables;
285 variables["[filename]"] = thisOutputDir + m->getRootName(m->getSimpleName(treefile));
286 string outputFileName = getOutputFileName("summary", variables);
287 outputNames.push_back(outputFileName); outputTypes["summary"].push_back(outputFileName);
290 m->openOutputFile(outputFileName, out);
291 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
295 if (groupfile != "") { out << "Group\t"; }
296 out << "NumRep\tTaxonomy" << endl;
298 string treeOutputDir = outputDir;
299 if (outputDir == "") { treeOutputDir += m->hasPath(treefile); }
300 variables["[filename]"] = treeOutputDir + m->getRootName(m->getSimpleName(treefile));
301 string outputTreeFileName = getOutputFileName("tree", variables);
303 //create a map from tree node index to names of descendants, save time later
304 map<int, map<string, set<string> > > nodeToDescendants; //node# -> (groupName -> groupMembers)
305 for (int i = 0; i < T->getNumNodes(); i++) {
306 if (m->control_pressed) { return 0; }
308 nodeToDescendants[i] = getDescendantList(T, i, nodeToDescendants);
312 for (int i = T->getNumLeaves(); i < T->getNumNodes(); i++) {
314 if (m->control_pressed) { out.close(); return 0; }
316 string tax = "not classifed";
318 if (groupfile != "") {
319 for (map<string, set<string> >::iterator itGroups = nodeToDescendants[i].begin(); itGroups != nodeToDescendants[i].end(); itGroups++) {
320 if (itGroups->first != "AllGroups") {
321 tax = getTaxonomy(itGroups->second, size);
322 out << (i+1) << '\t' << itGroups->first << '\t' << size << '\t' << tax << endl;
326 string group = "AllGroups";
327 tax = getTaxonomy(nodeToDescendants[i][group], size);
328 out << (i+1) << '\t' << size << '\t' << tax << endl;
331 T->tree[i].setLabel((i+1));
336 m->openOutputFile(outputTreeFileName, outTree);
337 outputNames.push_back(outputTreeFileName); outputTypes["tree"].push_back(outputTreeFileName);
338 T->print(outTree, "both");
343 catch(exception& e) {
344 m->errorOut(e, "ClassifyTreeCommand", "GetConcensusTaxonomies");
348 //**********************************************************************************************************************
349 string ClassifyTreeCommand::getTaxonomy(set<string> names, int& size) {
354 //create a tree containing sequences from this bin
355 PhyloTree* phylo = new PhyloTree();
357 for (set<string>::iterator it = names.begin(); it != names.end(); it++) {
359 //if namesfile include the names
360 if (namefile != "") {
362 //is this sequence in the name file - namemap maps seqName -> repSeqName
363 map<string, string>::iterator it2 = nameMap.find(*it);
365 if (it2 == nameMap.end()) { //this name is not in name file, skip it
366 m->mothurOut((*it) + " is not in your name file. I will not include it in the consensus."); m->mothurOutEndLine();
369 //is this sequence in the taxonomy file - look for repSeqName since we are assuming the taxonomy file is unique
370 map<string, string>::iterator itTax = taxMap.find((it2->second));
372 if (itTax == taxMap.end()) { //this name is not in taxonomy file, skip it
374 if ((*it) != (it2->second)) { m->mothurOut((*it) + " is represented by " + it2->second + " and is not in your taxonomy file. I will not include it in the consensus."); m->mothurOutEndLine(); }
375 else { m->mothurOut((*it) + " is not in your taxonomy file. I will not include it in the consensus."); m->mothurOutEndLine(); }
378 int num = nameCount[(*it)]; // we know its there since we found it in nameMap
379 for (int i = 0; i < num; i++) { phylo->addSeqToTree((*it)+toString(i), itTax->second); }
385 //is this sequence in the taxonomy file - look for repSeqName since we are assuming the taxonomy file is unique
386 map<string, string>::iterator itTax = taxMap.find((*it));
388 if (itTax == taxMap.end()) { //this name is not in taxonomy file, skip it
389 m->mothurOut((*it) + " is not in your taxonomy file. I will not include it in the consensus."); m->mothurOutEndLine();
391 if (countfile != "") {
392 int numDups = ct->getNumSeqs((*it));
393 for (int j = 0; j < numDups; j++) { phylo->addSeqToTree((*it), itTax->second); }
397 phylo->addSeqToTree((*it), itTax->second);
402 if (m->control_pressed) { delete phylo; return conTax; }
407 phylo->assignHeirarchyIDs(0);
409 TaxNode currentNode = phylo->get(0);
412 while (currentNode.children.size() != 0) { //you still have more to explore
415 int bestChildSize = 0;
417 //go through children
418 for (map<string, int>::iterator itChild = currentNode.children.begin(); itChild != currentNode.children.end(); itChild++) {
420 TaxNode temp = phylo->get(itChild->second);
422 //select child with largest accesions - most seqs assigned to it
423 if (temp.accessions.size() > bestChildSize) {
424 bestChild = phylo->get(itChild->second);
425 bestChildSize = temp.accessions.size();
430 //is this taxonomy above cutoff
431 int consensusConfidence = ceil((bestChildSize / (float) size) * 100);
433 if (consensusConfidence >= cutoff) { //if yes, add it
434 conTax += bestChild.name + "(" + toString(consensusConfidence) + ");";
441 currentNode = bestChild;
444 if (myLevel != phylo->getMaxLevel()) {
445 while (myLevel != phylo->getMaxLevel()) {
446 conTax += "unclassified;";
450 if (conTax == "") { conTax = "no_consensus;"; }
457 catch(exception& e) {
458 m->errorOut(e, "ClassifyTreeCommand", "getTaxonomy");
463 //**********************************************************************************************************************
464 map<string, set<string> > ClassifyTreeCommand::getDescendantList(Tree*& T, int i, map<int, map<string, set<string> > > descendants){
466 map<string ,set<string> > names;
468 map<string ,set<string> >::iterator it;
469 map<string ,set<string> >::iterator it2;
471 int lc = T->tree[i].getLChild();
472 int rc = T->tree[i].getRChild();
473 // TreeMap* tmap = T->getTreeMap();
475 if (lc == -1) { //you are a leaf your only descendant is yourself
476 vector<string> groups = T->tree[i].getGroup();
477 set<string> mynames; mynames.insert(T->tree[i].getName());
478 for (int j = 0; j < groups.size(); j++) { names[groups[j]] = mynames; } //mygroup -> me
479 names["AllGroups"] = mynames;
480 }else{ //your descedants are the combination of your childrens descendants
481 names = descendants[lc];
482 for (it = descendants[rc].begin(); it != descendants[rc].end(); it++) {
483 it2 = names.find(it->first); //do we already have this group
484 if (it2 == names.end()) { //nope, so add it
485 names[it->first] = it->second;
487 for (set<string>::iterator it3 = (it->second).begin(); it3 != (it->second).end(); it3++) {
488 names[it->first].insert(*it3);
497 catch(exception& e) {
498 m->errorOut(e, "ClassifyTreeCommand", "getDescendantList");
502 /*****************************************************************/