]> git.donarmstrong.com Git - mothur.git/blob - classifytreecommand.cpp
sffinfo bug with flow grams right index when clipQualRight=0
[mothur.git] / classifytreecommand.cpp
1 //
2 //  classifytreecommand.cpp
3 //  Mothur
4 //
5 //  Created by Sarah Westcott on 2/20/12.
6 //  Copyright (c) 2012 Schloss Lab. All rights reserved.
7 //
8
9 #include "classifytreecommand.h"
10 #include "phylotree.h"
11 #include "treereader.h"
12
13 //**********************************************************************************************************************
14 vector<string> ClassifyTreeCommand::setParameters(){    
15         try {
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);
24                 
25                 vector<string> myArray;
26                 for (int i = 0; i < parameters.size(); i++) {   myArray.push_back(parameters[i].name);          }
27                 return myArray;
28         }
29         catch(exception& e) {
30                 m->errorOut(e, "ClassifyTreeCommand", "setParameters");
31                 exit(1);
32         }
33 }
34 //**********************************************************************************************************************
35 string ClassifyTreeCommand::getHelpString(){    
36         try {
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"; 
47                 return helpString;
48         }
49         catch(exception& e) {
50                 m->errorOut(e, "ClassifyTreeCommand", "getHelpString");
51                 exit(1);
52         }
53 }
54 //**********************************************************************************************************************
55 string ClassifyTreeCommand::getOutputPattern(string type) {
56     try {
57         string pattern = "";
58         
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;  }
62         
63         return pattern;
64     }
65     catch(exception& e) {
66         m->errorOut(e, "ClassifyTreeCommand", "getOutputPattern");
67         exit(1);
68     }
69 }
70 //**********************************************************************************************************************
71 ClassifyTreeCommand::ClassifyTreeCommand(){     
72         try {
73                 abort = true; calledHelp = true; 
74                 setParameters();
75                 vector<string> tempOutNames;
76                 outputTypes["tree"] = tempOutNames;
77                 outputTypes["summary"] = tempOutNames;
78         }
79         catch(exception& e) {
80                 m->errorOut(e, "ClassifyTreeCommand", "ClassifyTreeCommand");
81                 exit(1);
82         }
83 }
84 //**********************************************************************************************************************
85 ClassifyTreeCommand::ClassifyTreeCommand(string option)  {
86         try {
87                 abort = false; calledHelp = false;   
88                 
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;}
92                 
93                 else {
94                         vector<string> myArray = setParameters();
95                         
96                         OptionParser parser(option);
97                         map<string, string> parameters = parser.getParameters();
98                         
99                         ValidParameters validParameter;
100                         map<string, string>::iterator it;
101                         
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;  }
105                         }
106                         
107                         vector<string> tempOutNames;
108                         outputTypes["tree"] = tempOutNames;
109                         outputTypes["summary"] = tempOutNames;
110                         
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 = "";          }
114                         else {
115                                 string path;
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;             }
122                                 }
123                                 
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;             }
130                                 }
131                                 
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;            }
138                                 }
139                                 
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;         }
146                                 }
147                 
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;            }
154                                 }
155                         }
156                         
157                         outputDir = validParameter.validFile(parameters, "outputdir", false);           if (outputDir == "not found"){  outputDir = ""; }
158             
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); } 
167             
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); } 
175                         
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); }
180                         
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); }
185             
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); }
190             
191             if ((namefile != "") && (countfile != "")) {
192                 m->mothurOut("[ERROR]: you may only use one of the following: name or count."); m->mothurOutEndLine(); abort = true;
193             }
194                         
195             if ((groupfile != "") && (countfile != "")) {
196                 m->mothurOut("[ERROR]: you may only use one of the following: group or count."); m->mothurOutEndLine(); abort=true;
197             }
198             
199             string temp = validParameter.validFile(parameters, "cutoff", false);                        if (temp == "not found") { temp = "51"; }
200                         m->mothurConvert(temp, cutoff); 
201                         
202                         if ((cutoff < 51) || (cutoff > 100)) { m->mothurOut("cutoff must be above 50, and no greater than 100."); m->mothurOutEndLine(); abort = true;  }
203             
204             if (countfile == "") {
205                 if (namefile == "") {
206                     vector<string> files; files.push_back(treefile);
207                     parser.getNameFile(files);
208                 }
209                         }
210                 }
211         }
212         catch(exception& e) {
213                 m->errorOut(e, "ClassifyTreeCommand", "ClassifyTreeCommand");           
214                 exit(1);
215         }
216 }
217 //**********************************************************************************************************************
218
219 int ClassifyTreeCommand::execute(){
220         try {
221                 
222                 if (abort == true) { if (calledHelp) { return 0; }  return 2;   }
223                 
224                 cout.setf(ios::fixed, ios::floatfield); cout.setf(ios::showpoint);
225                 
226                 int start = time(NULL);
227         
228                 /***************************************************/
229                 //    reading tree info                                                    //
230                 /***************************************************/
231         m->setTreeFile(treefile);
232         
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];
237         delete reader;
238
239         if (namefile != "") { m->readNames(namefile, nameMap, nameCount); }
240                         
241         if (m->control_pressed) { delete tmap;  delete outputTree;  return 0; }
242                 
243         m->readTax(taxonomyfile, taxMap);
244         
245         /***************************************************/
246         //              get concensus taxonomies                    //
247         /***************************************************/
248         getClassifications(outputTree);
249         delete outputTree; delete tmap;
250                         
251                 if (m->control_pressed) { for (int i = 0; i < outputNames.size(); i++) {        m->mothurRemove(outputNames[i]);        } return 0; }
252                 
253                 //set tree file as new current treefile
254                 if (treefile != "") {
255                         string current = "";
256                         itTypes = outputTypes.find("tree");
257                         if (itTypes != outputTypes.end()) {
258                                 if ((itTypes->second).size() != 0) { current = (itTypes->second)[0]; m->setTreeFile(current); }
259                         }
260                 }
261                 
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();
267         
268                 return 0;
269         }
270         catch(exception& e) {
271                 m->errorOut(e, "ClassifyTreeCommand", "execute");       
272                 exit(1);
273         }
274 }
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){
280         try {
281                 
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);
288                 
289                 ofstream out;
290                 m->openOutputFile(outputFileName, out);
291                 out.setf(ios::fixed, ios::floatfield); out.setf(ios::showpoint);
292                 
293                 //print headings
294                 out << "TreeNode\t";
295                 if (groupfile != "") { out << "Group\t"; } 
296         out << "NumRep\tTaxonomy" << endl; 
297                 
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);
302                 
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; }
307                         
308                         nodeToDescendants[i] = getDescendantList(T, i, nodeToDescendants);
309                 }
310                 
311                 //for each node
312                 for (int i = T->getNumLeaves(); i < T->getNumNodes(); i++) {
313                         
314                         if (m->control_pressed) { out.close(); return 0; }
315             
316                         string tax = "not classifed";
317             int size;
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;
323                     }
324                 }
325             }else {
326                 string group = "AllGroups";
327                 tax = getTaxonomy(nodeToDescendants[i][group], size);
328                 out << (i+1) << '\t' << size << '\t' << tax << endl;
329             }
330                                 
331                         T->tree[i].setLabel((i+1));
332                 }
333                 out.close();
334         
335                 ofstream outTree;
336                 m->openOutputFile(outputTreeFileName, outTree);
337                 outputNames.push_back(outputTreeFileName); outputTypes["tree"].push_back(outputTreeFileName);
338                 T->print(outTree, "both");
339                 outTree.close();
340         
341                 return 0;
342         }
343         catch(exception& e) {
344                 m->errorOut(e, "ClassifyTreeCommand", "GetConcensusTaxonomies");        
345                 exit(1);
346         }
347 }
348 //**********************************************************************************************************************
349 string ClassifyTreeCommand::getTaxonomy(set<string> names, int& size) {
350         try{
351                 string conTax = "";
352         size = 0;
353                         
354                 //create a tree containing sequences from this bin
355                 PhyloTree* phylo = new PhyloTree();
356                 
357                 for (set<string>::iterator it = names.begin(); it != names.end(); it++) {
358             
359             
360                         //if namesfile include the names
361                         if (namefile != "") {
362                 
363                                 //is this sequence in the name file - namemap maps seqName -> repSeqName
364                                 map<string, string>::iterator it2 = nameMap.find(*it);
365                                 
366                                 if (it2 == nameMap.end()) { //this name is not in name file, skip it
367                                         m->mothurOut((*it) + " is not in your name file.  I will not include it in the consensus."); m->mothurOutEndLine();
368                                 }else{
369                                         
370                                         //is this sequence in the taxonomy file - look for repSeqName since we are assuming the taxonomy file is unique
371                                         map<string, string>::iterator itTax = taxMap.find((it2->second));
372                     
373                                         if (itTax == taxMap.end()) { //this name is not in taxonomy file, skip it
374                         
375                                                 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(); }
376                                                 else {  m->mothurOut((*it) + " is not in your taxonomy file.  I will not include it in the consensus."); m->mothurOutEndLine(); }
377                                         }else{
378                                                 //add seq to tree
379                         int num = nameCount[(*it)]; // we know its there since we found it in nameMap
380                                                 for (int i = 0; i < num; i++) {  phylo->addSeqToTree((*it)+toString(i), it2->second);  }
381                         size += num;
382                                         }
383                                 }
384                                 
385                         }else{
386                                 //is this sequence in the taxonomy file - look for repSeqName since we are assuming the taxonomy file is unique
387                                 map<string, string>::iterator itTax = taxMap.find((*it));
388                 
389                                 if (itTax == taxMap.end()) { //this name is not in taxonomy file, skip it
390                                         m->mothurOut((*it) + " is not in your taxonomy file.  I will not include it in the consensus."); m->mothurOutEndLine();
391                                 }else{
392                                         if (countfile != "") {
393                         int numDups = ct->getNumSeqs((*it)); 
394                         for (int j = 0; j < numDups; j++) {  phylo->addSeqToTree((*it), itTax->second);  }
395                         size += numDups;
396                     }else{
397                         //add seq to tree
398                         phylo->addSeqToTree((*it), itTax->second);
399                         size++;  
400                     }                           }
401                         }
402             
403                         if (m->control_pressed) { delete phylo; return conTax; }
404                         
405                 }
406                 
407                 //build tree
408                 phylo->assignHeirarchyIDs(0);
409                 
410                 TaxNode currentNode = phylo->get(0);
411                 int myLevel = 0;        
412                 //at each level
413                 while (currentNode.children.size() != 0) { //you still have more to explore
414             
415                         TaxNode bestChild;
416                         int bestChildSize = 0;
417                         
418                         //go through children
419                         for (map<string, int>::iterator itChild = currentNode.children.begin(); itChild != currentNode.children.end(); itChild++) {
420                                 
421                                 TaxNode temp = phylo->get(itChild->second);
422                                 
423                                 //select child with largest accesions - most seqs assigned to it
424                                 if (temp.accessions.size() > bestChildSize) {
425                                         bestChild = phylo->get(itChild->second);
426                                         bestChildSize = temp.accessions.size();
427                                 }
428                                 
429                         }
430             
431                         //is this taxonomy above cutoff
432                         int consensusConfidence = ceil((bestChildSize / (float) size) * 100);
433                         
434                         if (consensusConfidence >= cutoff) { //if yes, add it
435                 conTax += bestChild.name + "(" + toString(consensusConfidence) + ");";
436                                 myLevel++;
437                         }else{ //if no, quit
438                                 break;
439                         }
440                         
441                         //move down a level
442                         currentNode = bestChild;
443                 }
444                 
445                 if (myLevel != phylo->getMaxLevel()) {
446                         while (myLevel != phylo->getMaxLevel()) {
447                                 conTax += "unclassified;";
448                                 myLevel++;
449                         }
450                 }               
451                 if (conTax == "") {  conTax = "no_consensus;";  }
452                 
453                 delete phylo;   
454         
455         return conTax;
456         
457         }
458         catch(exception& e) {
459                 m->errorOut(e, "ClassifyTreeCommand", "getTaxonomy");
460                 exit(1);
461         }
462 }
463
464 //**********************************************************************************************************************
465 map<string, set<string> > ClassifyTreeCommand::getDescendantList(Tree*& T, int i, map<int, map<string, set<string> > > descendants){
466         try {
467                 map<string ,set<string> > names;
468                 
469                 map<string ,set<string> >::iterator it;
470         map<string ,set<string> >::iterator it2;
471                 
472                 int lc = T->tree[i].getLChild();
473                 int rc = T->tree[i].getRChild();
474        // TreeMap* tmap = T->getTreeMap();
475                 
476                 if (lc == -1) { //you are a leaf your only descendant is yourself
477             vector<string> groups = T->tree[i].getGroup();
478             set<string> mynames; mynames.insert(T->tree[i].getName());
479             for (int j = 0; j < groups.size(); j++) { names[groups[j]] = mynames;   } //mygroup -> me
480             names["AllGroups"] = mynames;
481                 }else{ //your descedants are the combination of your childrens descendants
482                         names = descendants[lc];
483                         for (it = descendants[rc].begin(); it != descendants[rc].end(); it++) {
484                 it2 = names.find(it->first); //do we already have this group
485                 if (it2 == names.end()) { //nope, so add it
486                     names[it->first] = it->second;
487                 }else {
488                     for (set<string>::iterator it3 = (it->second).begin(); it3 != (it->second).end(); it3++) {
489                         names[it->first].insert(*it3);
490                     }
491                 }
492                                 
493                         }
494                 }
495                 
496                 return names;
497         }
498         catch(exception& e) {
499                 m->errorOut(e, "ClassifyTreeCommand", "getDescendantList");     
500                 exit(1);
501         }
502 }
503 /*****************************************************************/
504
505