]> git.donarmstrong.com Git - mothur.git/blob - readtree.cpp
fixed bug in unifrac commands with nexus translation if files don't match
[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                 m->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                         m->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                 m->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                 m->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                                 m->gobble(filehandle);
129                         }
130                 //if you are a nexus file
131                 }else if ((c = filehandle.peek()) == '#') {
132                         //get right number of seqs from nexus file.
133                         Tree* temp = new Tree();  delete temp;
134                         
135                         nexusTranslation();  //reads file through the translation and updates treemap
136                         while((c = filehandle.peek()) != EOF) { 
137                                 // get past comments
138                                 while ((c = filehandle.peek()) != EOF) {        
139                                         if(holder == "[" || holder == "[!"){
140                                                 comment = 1;
141                                         }
142                                         if(holder == "]"){
143                                                 comment = 0;
144                                         }
145                                         if((holder == "tree" || holder == "end;") && comment != 1){ holder = ""; comment = 0; break;}
146                                         filehandle >> holder;
147                                 }
148                         
149                                 //pass over the "tree rep.6878900 = "
150                                 while (((c = filehandle.get()) != '(') && ((c = filehandle.peek()) != EOF) ) {;}
151                                         
152                                 if (c == EOF ) { break; }
153                                 filehandle.putback(c);  //put back first ( of tree.
154                                 
155                                 //make new tree
156                                 T = new Tree(); 
157                                 numNodes = T->getNumNodes();
158                                 numLeaves = T->getNumLeaves();
159                                 
160                                 //read tree info
161                                 error = readTreeString(); 
162                                  
163                                 //save trees for later commands
164                                 globaldata->gTree.push_back(T); 
165                         }
166                 }
167                 
168                 if (error != 0) { readOk = error; } 
169                 
170                 filehandle.close();
171
172                 return readOk;
173         }
174         catch(exception& e) {
175                 m->errorOut(e, "ReadNewickTree", "read");
176                 exit(1);
177         }
178 }
179 /**************************************************************************************************/
180 //This function read the file through the translation of the sequences names and updates treemap.
181 string ReadNewickTree::nexusTranslation() {
182         try {
183                 
184                 holder = "";
185                 int numSeqs = globaldata->Treenames.size(); //must save this some when we clear old names we can still know how many sequences there were
186                 int comment = 0;
187                 
188                 // get past comments
189                 while(holder != "translate" && holder != "Translate"){  
190                         if(holder == "[" || holder == "[!"){
191                                 comment = 1;
192                         }
193                         if(holder == "]"){
194                                 comment = 0;
195                         }
196                         filehandle >> holder; 
197                         if(holder == "tree" && comment != 1){return holder;}
198                 }
199                 
200                 //update treemap
201                 globaldata->gTreemap->namesOfSeqs.clear();
202                 
203                 /*char c;
204                 string number, name;
205                 while ((c = filehandle.peek()) != EOF) {        
206                         
207                         filehandle >> number; 
208                         
209                         if ((number == "tree") || (number == ";") ) {  name = number; break;  }
210                         
211                         filehandle >> name; 
212                         
213                         char lastChar;
214                         if (name.length() != 0) { lastChar = name[name.length()-1]; }
215                         
216                         if ((name == "tree") || (name == ";") ) {  break;  }
217                         
218                         if (lastChar == ',') {  name.erase(name.end()-1); } //erase the comma
219                         */      
220                 cout << "numseqs = " << numSeqs << endl;
221                 string number, name;
222                 for(int i=0;i<numSeqs;i++){
223                         
224                         filehandle >> number;
225                         filehandle >> name;
226                         name.erase(name.end()-1);  //erase the comma
227                         
228                         //insert new one with new name
229                         string group = globaldata->gTreemap->getGroup(name);
230                         globaldata->gTreemap->treemap[toString(number)].groupname = group;
231                         globaldata->gTreemap->treemap[toString(number)].vectorIndex = globaldata->gTreemap->getIndex(name);
232                         //erase old one.  so treemap[sarah].groupnumber is now treemap[1].groupnumber. if number is 1 and name is sarah.
233                         globaldata->gTreemap->treemap.erase(name);
234                         globaldata->gTreemap->namesOfSeqs.push_back(number);
235                 }
236                 
237                 return name;
238         }
239         catch(exception& e) {
240                 m->errorOut(e, "ReadNewickTree", "nexusTranslation");
241                 exit(1);
242         }
243 }
244
245 /**************************************************************************************************/
246 int ReadNewickTree::readTreeString() {
247         try {
248                 
249                 int n = 0;
250                 int lc, rc; 
251                 
252                 int rooted = 0;
253         
254                 int ch = filehandle.peek();     
255                 
256                 if(ch == '('){
257                         n = numLeaves;  //number of leaves / sequences, we want node 1 to start where the leaves left off
258
259                         lc = readNewickInt(filehandle, n, T);
260                         if (lc == -1) { m->mothurOut("error with lc"); m->mothurOutEndLine(); return -1; } //reports an error in reading
261         
262                         if(filehandle.peek()==','){                                                     
263                                 readSpecialChar(filehandle,',',"comma");
264                         }
265                         // ';' means end of tree.                                                                                               
266                         else if((ch=filehandle.peek())==';' || ch=='['){                
267                                 rooted = 1;                                                                     
268                         }       
269                 
270                         if(rooted != 1){                                                                
271                                 rc = readNewickInt(filehandle, n, T);
272                                 if (rc == -1) { m->mothurOut("error with rc"); m->mothurOutEndLine(); return -1; } //reports an error in reading
273                                 if(filehandle.peek() == ')'){                                   
274                                         readSpecialChar(filehandle,')',"right parenthesis");
275                                 }                                                                                       
276                         }       
277                 }
278                 //note: treeclimber had the code below added - not sure why?
279                 else{
280                         filehandle.putback(ch);
281                         char name[MAX_LINE];
282                         filehandle.get(name, MAX_LINE,'\n');
283                         SKIPLINE(filehandle, ch);
284                 
285                         n = T->getIndex(name);
286
287                         if(n!=0){
288                                 m->mothurOut("Internal error: The only taxon is not taxon 0.\n");
289                                 //exit(1);
290                                 readOk = -1; return -1;
291                         }
292                         lc = rc = -1;
293                 } 
294                 
295                 while(((ch=filehandle.get())!=';') && (filehandle.eof() != true)){;}    
296                                                         
297                 if(rooted != 1){                                                                        
298                         T->tree[n].setChildren(lc,rc);
299                         T->tree[n].setBranchLength(0);
300                         T->tree[n].setParent(-1);
301                         if(lc!=-1){             T->tree[lc].setParent(n);               }
302                         if(rc!=-1){             T->tree[rc].setParent(n);               }
303                 }
304                 
305                 //T->printTree(); cout << endl;
306                 return 0;
307         
308         }
309         catch(exception& e) {
310                 m->errorOut(e, "ReadNewickTree", "readTreeString");
311                 exit(1);
312         }
313 }
314 /**************************************************************************************************/
315
316 int ReadNewickTree::readNewickInt(istream& f, int& n, Tree* T) {
317         try {
318                 
319                 if (m->control_pressed) { return -1; } 
320                 
321                 int c = readNodeChar(f);
322
323                 if(c == '('){
324                 
325                         //to account for multifurcating trees generated by fasttree, we are forcing them to be bifurcating
326                         //read all children
327                         vector<int> childrenNodes;
328                         while(f.peek() != ')'){
329                                 int child = readNewickInt(f, n, T);
330                                 if (child == -1) { return -1; } //reports an error in reading
331                 //cout << "child = " << child << endl;          
332                                 childrenNodes.push_back(child);
333                                 
334                                 //after a child you either have , or ), check for both
335                                 if(f.peek()==')'){  break;  }
336                                 else if (f.peek()==',') {   readSpecialChar(f,',',"comma");  }
337                                 else {;}
338                         }
339         //cout << childrenNodes.size() << endl;         
340                         if (childrenNodes.size() < 2) {  m->mothurOut("Error in tree, please correct."); m->mothurOutEndLine(); return -1; }
341                         
342                         //then force into 2 node structure
343                         for (int i = 1; i < childrenNodes.size(); i++) {
344                         
345                                 int lc, rc;
346                                 if (i == 1) { lc = childrenNodes[i-1]; rc = childrenNodes[i]; }
347                                 else { lc = n-1; rc = childrenNodes[i]; }
348                         //cout << i << '\t' << lc << '\t' << rc << endl;        
349                                 T->tree[n].setChildren(lc,rc);
350                                 T->tree[lc].setParent(n);
351                                 T->tree[rc].setParent(n);
352                                 
353                                 //T->printTree(); cout << endl;
354                                 n++;
355                         }
356                         
357                         //to account for extra ++ in looping
358                         n--;
359                         
360                         if(f.peek()==')'){      
361                                 readSpecialChar(f,')',"right parenthesis");     
362                                 //to pass over labels in trees
363                                 c=filehandle.get();
364                                 while((c!=',') && (c != -1) && (c!= ':') && (c!=';')&& (c!=')')){ c=filehandle.get(); }
365                                 filehandle.putback(c);
366                         }                       
367                 
368                         if(f.peek() == ':'){                                                                          
369                                 readSpecialChar(f,':',"colon"); 
370                                                                                 
371                                 if(n >= numNodes){ m->mothurOut("Error: Too many nodes in input tree\n");  readOk = -1; return -1; }
372                                 
373                                 T->tree[n].setBranchLength(readBranchLength(f));
374                         }else{
375                                 T->tree[n].setBranchLength(0.0); 
376                         }                                               
377                         
378                         //T->tree[n].setChildren(lc,rc);
379                         //T->tree[lc].setParent(n);
380                         //T->tree[rc].setParent(n);
381                         //T->printTree();  cout << endl;
382                         
383                         return n++;
384                 
385                 }else{
386                         f.putback(c);
387                         string name = "";
388                         char d=f.get();
389                         while(d != ':' && d != ',' && d!=')' && d!='\n'){                                       
390                                 name += d;
391                                 d=f.get();
392                         }
393 //cout << name << endl;
394                         int blen = 0;
395                         if(d == ':')    {               blen = 1;       }               
396                 
397                         f.putback(d);
398                 
399                         //set group info
400                         string group = globaldata->gTreemap->getGroup(name);
401                         
402                         //find index in tree of name
403                         int n1 = T->getIndex(name);
404                         
405                         //adds sequence names that are not in group file to the "xxx" group
406                         if(group == "not found") {
407                                 m->mothurOut("Name: " + name + " is not in your groupfile, and will be disregarded. \n");  //readOk = -1; return n1;
408                                 
409                                 globaldata->gTreemap->namesOfSeqs.push_back(name);
410                                 globaldata->gTreemap->treemap[name].groupname = "xxx";
411                                 
412                                 map<string, int>::iterator it;
413                                 it = globaldata->gTreemap->seqsPerGroup.find("xxx");
414                                 if (it == globaldata->gTreemap->seqsPerGroup.end()) { //its a new group
415                                         globaldata->gTreemap->namesOfGroups.push_back("xxx");
416                                         globaldata->gTreemap->seqsPerGroup["xxx"] = 1;
417                                 }else {
418                                         globaldata->gTreemap->seqsPerGroup["xxx"]++;
419                                 }
420                                 
421                                 group = "xxx";
422                         }
423                         
424                         vector<string> tempGroup; tempGroup.push_back(group);
425                         
426                         T->tree[n1].setGroup(tempGroup);
427                         T->tree[n1].setChildren(-1,-1);
428                 
429                         if(blen == 1){  
430                                 f.get();
431                                 T->tree[n1].setBranchLength(readBranchLength(f));
432                         }else{
433                                 T->tree[n1].setBranchLength(0.0);
434                         }
435                 
436                         while((c=f.get())!=0 && (c != ':' && c != ',' && c!=')') )              {;}             
437         
438                         f.putback(c);
439                 
440                         return n1;
441                 }
442         }
443         catch(exception& e) {
444                 m->errorOut(e, "ReadNewickTree", "readNewickInt");
445                 exit(1);
446         }
447 }
448 /**************************************************************************************************/
449 /**************************************************************************************************/
450