]> git.donarmstrong.com Git - mothur.git/blob - readtree.cpp
fixed read.tree so that it can read trees generated by fasttree
[mothur.git] / readtree.cpp
1 /*
2  *  readtree.cpp
3  *  Mothur
4  *
5  *  Created by Sarah Westcott on 1/22/09.
6  *  Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
7  *
8  */
9
10 #include "readtree.h"
11
12 /***********************************************************************/
13 ReadTree::ReadTree() {
14         try {
15                 globaldata = GlobalData::getInstance();
16                 m = MothurOut::getInstance();
17                 globaldata->gTree.clear();
18         }
19         catch(exception& e) {
20                 m->errorOut(e, "ReadTree", "ReadTree");
21                 exit(1);
22         }
23 }
24 /***********************************************************************/
25 int ReadTree::readSpecialChar(istream& f, char c, string name) {
26     try {
27         
28                 gobble(f);
29                 char d = f.get();
30         
31                 if(d == EOF){
32                         m->mothurOut("Error: Input file ends prematurely, expecting a " + name + "\n");
33                         exit(1);
34                 }
35                 if(d != c){
36                         m->mothurOut("Error: Expected " + name + " in input file.  Found " + toString(d) + ".\n");
37                         exit(1);
38                 }
39                 if(d == ')' && f.peek() == '\n'){
40                         gobble(f);
41                 }       
42                 return d;
43         }
44         catch(exception& e) {
45                 m->errorOut(e, "ReadTree", "readSpecialChar");
46                 exit(1);
47         }
48 }
49 /**************************************************************************************************/
50
51 int ReadTree::readNodeChar(istream& f) {
52         try {
53 //              while(isspace(d=f.get()))               {;}
54                 gobble(f);
55                 char d = f.get();
56
57                 if(d == EOF){
58                         m->mothurOut("Error: Input file ends prematurely, expecting a left parenthesis\n");
59                         exit(1);
60                 }
61                 return d;
62         }
63         catch(exception& e) {
64                 m->errorOut(e, "ReadTree", "readNodeChar");
65                 exit(1);
66         }
67 }
68
69 /**************************************************************************************************/
70
71 float ReadTree::readBranchLength(istream& f) {
72     try {
73                 float b;
74         
75                 if(!(f >> b)){
76                         m->mothurOut("Error: Missing branch length in input tree.\n");
77                         exit(1);
78                 }
79                 gobble(f);
80                 return b;
81         }
82         catch(exception& e) {
83                 m->errorOut(e, "ReadTree", "readBranchLength");
84                 exit(1);
85         }
86 }
87
88 /***********************************************************************/
89 /***********************************************************************/
90
91 //Child Classes Below
92
93 /***********************************************************************/
94 /***********************************************************************/
95 //This class reads a file in Newick form and stores it in a tree.
96
97 int ReadNewickTree::read() {
98         try {
99                 holder = "";
100                 int c, error;
101                 int comment = 0;
102                 
103                 //if you are not a nexus file 
104                 if ((c = filehandle.peek()) != '#') {  
105                         while((c = filehandle.peek()) != EOF) { 
106                                 while ((c = filehandle.peek()) != EOF) {
107                                         // get past comments
108                                         if(c == '[') {
109                                                 comment = 1;
110                                         }
111                                         if(c == ']'){
112                                                 comment = 0;
113                                         }
114                                         if((c == '(') && (comment != 1)){ break; }
115                                         filehandle.get();
116                                 }
117
118                                 //make new tree
119                                 T = new Tree(); 
120
121                                 numNodes = T->getNumNodes();
122                                 numLeaves = T->getNumLeaves();
123                                 
124                                 error = readTreeString(); 
125                                 
126                                 //save trees for later commands
127                                 globaldata->gTree.push_back(T); 
128                                 gobble(filehandle);
129                         }
130                 //if you are a nexus file
131                 }else if ((c = filehandle.peek()) == '#') {
132                         nexusTranslation();  //reads file through the translation and updates treemap
133                         while((c = filehandle.peek()) != EOF) { 
134                                 // get past comments
135                                 while ((c = filehandle.peek()) != EOF) {        
136                                         if(holder == "[" || holder == "[!"){
137                                                 comment = 1;
138                                         }
139                                         if(holder == "]"){
140                                                 comment = 0;
141                                         }
142                                         if((holder == "tree" || holder == "end;") && comment != 1){ holder = ""; comment = 0; break;}
143                                         filehandle >> holder;
144                                 }
145                         
146                                 //pass over the "tree rep.6878900 = "
147                                 while (((c = filehandle.get()) != '(') && ((c = filehandle.peek()) != EOF) ) {;}
148                                         
149                                 if (c == EOF ) { break; }
150                                 filehandle.putback(c);  //put back first ( of tree.
151                                 
152                                 //make new tree
153                                 T = new Tree(); 
154                                 numNodes = T->getNumNodes();
155                                 numLeaves = T->getNumLeaves();
156                                 
157                                 //read tree info
158                                 error = readTreeString(); 
159                                  
160                                 //save trees for later commands
161                                 globaldata->gTree.push_back(T); 
162                         }
163                 }
164                 
165                 if (error != 0) { readOk = error; } 
166                 
167                 filehandle.close();
168
169                 return readOk;
170         }
171         catch(exception& e) {
172                 m->errorOut(e, "ReadNewickTree", "read");
173                 exit(1);
174         }
175 }
176 /**************************************************************************************************/
177 //This function read the file through the translation of the sequences names and updates treemap.
178 void ReadNewickTree::nexusTranslation() {
179         try {
180                 
181                 holder = "";
182                 int numSeqs = globaldata->gTreemap->getNumSeqs(); //must save this some when we clear old names we can still know how many sequences there were
183                 int comment = 0;
184                 
185                 // get past comments
186                 while(holder != "translate" && holder != "Translate"){  
187                         if(holder == "[" || holder == "[!"){
188                                 comment = 1;
189                         }
190                         if(holder == "]"){
191                                 comment = 0;
192                         }
193                         filehandle >> holder; 
194                         if(holder == "tree" && comment != 1){return;}
195                 }
196                 
197                 //update treemap
198                 globaldata->gTreemap->namesOfSeqs.clear();
199                 for(int i=0;i<numSeqs;i++){
200                         string number, name;
201                         filehandle >> number;
202                         filehandle >> name;
203                         name.erase(name.end()-1);  //erase the comma
204                         //insert new one with new name
205                         globaldata->gTreemap->treemap[toString(number)].groupname = globaldata->gTreemap->treemap[name].groupname;
206                         globaldata->gTreemap->treemap[toString(number)].vectorIndex = globaldata->gTreemap->treemap[name].vectorIndex;
207                         //erase old one.  so treemap[sarah].groupnumber is now treemap[1].groupnumber. if number is 1 and name is sarah.
208                         globaldata->gTreemap->treemap.erase(name);
209                         globaldata->gTreemap->namesOfSeqs.push_back(number);
210                 }
211         }
212         catch(exception& e) {
213                 m->errorOut(e, "ReadNewickTree", "nexusTranslation");
214                 exit(1);
215         }
216 }
217
218 /**************************************************************************************************/
219 int ReadNewickTree::readTreeString() {
220         try {
221                 
222                 int n = 0;
223                 int lc, rc; 
224                 
225                 int rooted = 0;
226         
227                 int ch = filehandle.peek();     
228                 
229                 if(ch == '('){
230                         n = numLeaves;  //number of leaves / sequences, we want node 1 to start where the leaves left off
231
232                         lc = readNewickInt(filehandle, n, T);
233                         if (lc == -1) { m->mothurOut("error with lc"); m->mothurOutEndLine(); return -1; } //reports an error in reading
234         
235                         if(filehandle.peek()==','){                                                     
236                                 readSpecialChar(filehandle,',',"comma");
237                         }
238                         // ';' means end of tree.                                                                                               
239                         else if((ch=filehandle.peek())==';' || ch=='['){                
240                                 rooted = 1;                                                                     
241                         }       
242                 
243                         if(rooted != 1){                                                                
244                                 rc = readNewickInt(filehandle, n, T);
245                                 if (rc == -1) { m->mothurOut("error with rc"); m->mothurOutEndLine(); return -1; } //reports an error in reading
246                                 if(filehandle.peek() == ')'){                                   
247                                         readSpecialChar(filehandle,')',"right parenthesis");
248                                 }                                                                                       
249                         }       
250                 }
251                 //note: treeclimber had the code below added - not sure why?
252                 else{
253                         filehandle.putback(ch);
254                         char name[MAX_LINE];
255                         filehandle.get(name, MAX_LINE,'\n');
256                         SKIPLINE(filehandle, ch);
257                 
258                         n = T->getIndex(name);
259
260                         if(n!=0){
261                                 m->mothurOut("Internal error: The only taxon is not taxon 0.\n");
262                                 //exit(1);
263                                 readOk = -1; return -1;
264                         }
265                         lc = rc = -1;
266                 } 
267                 
268                 while(((ch=filehandle.get())!=';') && (filehandle.eof() != true)){;}    
269                                                         
270                 if(rooted != 1){                                                                        
271                         T->tree[n].setChildren(lc,rc);
272                         T->tree[n].setBranchLength(0);
273                         T->tree[n].setParent(-1);
274                         if(lc!=-1){             T->tree[lc].setParent(n);               }
275                         if(rc!=-1){             T->tree[rc].setParent(n);               }
276                 }
277                 
278                 //T->printTree(); cout << endl;
279                 return 0;
280         
281         }
282         catch(exception& e) {
283                 m->errorOut(e, "ReadNewickTree", "readTreeString");
284                 exit(1);
285         }
286 }
287 /**************************************************************************************************/
288
289 int ReadNewickTree::readNewickInt(istream& f, int& n, Tree* T) {
290         try {
291                 
292                 if (m->control_pressed) { return -1; } 
293                 
294                 int c = readNodeChar(f);
295
296                 if(c == '('){
297                 
298                         //to account for multifurcating trees generated by fasttree, we are forcing them to be bifurcating
299                         //read all children
300                         vector<int> childrenNodes;
301                         while(f.peek() != ')'){
302                                 int child = readNewickInt(f, n, T);
303                                 if (child == -1) { return -1; } //reports an error in reading
304                 //cout << "child = " << child << endl;          
305                                 childrenNodes.push_back(child);
306                                 
307                                 //after a child you either have , or ), check for both
308                                 if(f.peek()==')'){  break;  }
309                                 else if (f.peek()==',') {   readSpecialChar(f,',',"comma");  }
310                                 else {;}
311                         }
312         //cout << childrenNodes.size() << endl;         
313                         if (childrenNodes.size() < 2) {  m->mothurOut("Error in tree, please correct."); m->mothurOutEndLine(); return -1; }
314                         
315                         //then force into 2 node structure
316                         for (int i = 1; i < childrenNodes.size(); i++) {
317                         
318                                 int lc, rc;
319                                 if (i == 1) { lc = childrenNodes[i-1]; rc = childrenNodes[i]; }
320                                 else { lc = n-1; rc = childrenNodes[i]; }
321                         //cout << i << '\t' << lc << '\t' << rc << endl;        
322                                 T->tree[n].setChildren(lc,rc);
323                                 T->tree[lc].setParent(n);
324                                 T->tree[rc].setParent(n);
325                                 
326                                 //T->printTree(); cout << endl;
327                                 n++;
328                         }
329                         
330                         //to account for extra ++ in looping
331                         n--;
332                         
333                         if(f.peek()==')'){      
334                                 readSpecialChar(f,')',"right parenthesis");     
335                                 //to pass over labels in trees
336                                 c=filehandle.get();
337                                 while((c!=',') && (c != -1) && (c!= ':') && (c!=';')&& (c!=')')){ c=filehandle.get(); }
338                                 filehandle.putback(c);
339                         }                       
340                 
341                         if(f.peek() == ':'){                                                                          
342                                 readSpecialChar(f,':',"colon"); 
343                                                                                 
344                                 if(n >= numNodes){      m->mothurOut("Error: Too many nodes in input tree\n");  readOk = -1; return -1; }
345                                 
346                                 T->tree[n].setBranchLength(readBranchLength(f));
347                         }else{
348                                 T->tree[n].setBranchLength(0.0); 
349                         }                                               
350                         
351                         //T->tree[n].setChildren(lc,rc);
352                         //T->tree[lc].setParent(n);
353                         //T->tree[rc].setParent(n);
354                         //T->printTree();  cout << endl;
355                         
356                         return n++;
357                 
358                 }else{
359                         f.putback(c);
360                         string name = "";
361                         char d=f.get();
362                         while(d != ':' && d != ',' && d!=')' && d!='\n'){                                       
363                                 name += d;
364                                 d=f.get();
365                         }
366 //cout << name << endl;
367                         int blen = 0;
368                         if(d == ':')    {               blen = 1;       }               
369                 
370                         f.putback(d);
371                 
372                         //set group info
373                         string group = globaldata->gTreemap->getGroup(name);
374                         
375                         //find index in tree of name
376                         int n1 = T->getIndex(name);
377                         
378                         //adds sequence names that are not in group file to the "xxx" group
379                         if(group == "not found") {
380                                 m->mothurOut("Name: " + name + " is not in your groupfile, and will be disregarded. \n");  //readOk = -1; return n1;
381                                 
382                                 globaldata->gTreemap->namesOfSeqs.push_back(name);
383                                 globaldata->gTreemap->treemap[name].groupname = "xxx";
384                                 
385                                 map<string, int>::iterator it;
386                                 it = globaldata->gTreemap->seqsPerGroup.find("xxx");
387                                 if (it == globaldata->gTreemap->seqsPerGroup.end()) { //its a new group
388                                         globaldata->gTreemap->namesOfGroups.push_back("xxx");
389                                         globaldata->gTreemap->seqsPerGroup["xxx"] = 1;
390                                 }else {
391                                         globaldata->gTreemap->seqsPerGroup["xxx"]++;
392                                 }
393                                 
394                                 group = "xxx";
395                         }
396                         
397                         vector<string> tempGroup; tempGroup.push_back(group);
398                         
399                         T->tree[n1].setGroup(tempGroup);
400                         T->tree[n1].setChildren(-1,-1);
401                 
402                         if(blen == 1){  
403                                 f.get();
404                                 T->tree[n1].setBranchLength(readBranchLength(f));
405                         }else{
406                                 T->tree[n1].setBranchLength(0.0);
407                         }
408                 
409                         while((c=f.get())!=0 && (c != ':' && c != ',' && c!=')') )              {;}             
410         
411                         f.putback(c);
412                 
413                         return n1;
414                 }
415         }
416         catch(exception& e) {
417                 m->errorOut(e, "ReadNewickTree", "readNewickInt");
418                 exit(1);
419         }
420 }
421 /**************************************************************************************************/
422 /**************************************************************************************************/
423