]> git.donarmstrong.com Git - mothur.git/blob - phylotree.cpp
moved utilities out of mothur.h and into mothurOut class.
[mothur.git] / phylotree.cpp
1 /*
2  *  doTaxonomy.cpp
3  *  
4  *
5  *  Created by Pat Schloss on 6/17/09.
6  *  Copyright 2009 Patrick D. Schloss. All rights reserved.
7  *
8  */
9
10 #include "phylotree.h"
11
12 /**************************************************************************************************/
13
14 PhyloTree::PhyloTree(){
15         try {
16                 m = MothurOut::getInstance();
17                 numNodes = 1;
18                 numSeqs = 0;
19                 tree.push_back(TaxNode("Root"));
20                 tree[0].heirarchyID = "0";
21                 maxLevel = 0;
22                 calcTotals = true;
23         }
24         catch(exception& e) {
25                 m->errorOut(e, "PhyloTree", "PhyloTree");
26                 exit(1);
27         }
28 }
29 /**************************************************************************************************/
30
31 PhyloTree::PhyloTree(ifstream& in, string filename){
32         try {
33                 m = MothurOut::getInstance();
34                 calcTotals = false;
35                 numNodes = 0;
36                 numSeqs = 0;
37                 
38                 #ifdef USE_MPI
39                         MPI_File inMPI;
40                         MPI_Offset size;
41                         MPI_Status status;
42
43                         char inFileName[1024];
44                         strcpy(inFileName, filename.c_str());
45
46                         MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  
47                         MPI_File_get_size(inMPI, &size);
48                         
49                         char* buffer = new char[size];
50                         MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
51
52                         string tempBuf = buffer;
53                         if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size);  }
54                         istringstream iss (tempBuf,istringstream::in);
55                         delete buffer;
56                         
57                         //read version
58                         m->getline(iss); m->gobble(iss);
59                         
60                         iss >> numNodes; m->gobble(iss);
61                         
62                         tree.resize(numNodes);
63                         
64                         for (int i = 0; i < tree.size(); i++) {
65                                 iss >> tree[i].name >> tree[i].level >> tree[i].parent; m->gobble(iss);
66                         }
67                         
68                         //read genus nodes
69                         int numGenus = 0;
70                         iss >> numGenus; m->gobble(iss);
71                         
72                         int gnode, gsize;
73                         totals.clear();
74                         for (int i = 0; i < numGenus; i++) {
75                                 iss >> gnode >> gsize; m->gobble(iss);
76                                 
77                                 uniqueTaxonomies[gnode] = gnode;
78                                 totals.push_back(gsize);
79                         }
80                         
81                         MPI_File_close(&inMPI);
82                         
83                 #else
84                         //read version
85                         string line = m->getline(in); m->gobble(in);
86                         
87                         in >> numNodes; m->gobble(in);
88                         
89                         tree.resize(numNodes);
90                         
91                         for (int i = 0; i < tree.size(); i++) {
92                                 in >> tree[i].name >> tree[i].level >> tree[i].parent; m->gobble(in);
93                         }
94                         
95                         //read genus nodes
96                         int numGenus = 0;
97                         in >> numGenus; m->gobble(in);
98                         
99                         int gnode, gsize;
100                         totals.clear();
101                         for (int i = 0; i < numGenus; i++) {
102                                 in >> gnode >> gsize; m->gobble(in);
103                                 
104                                 uniqueTaxonomies[gnode] = gnode;
105                                 totals.push_back(gsize);
106                         }
107                         
108                         in.close();
109                         
110                 #endif
111                 
112         }
113         catch(exception& e) {
114                 m->errorOut(e, "PhyloTree", "PhyloTree");
115                 exit(1);
116         }
117 }
118 /**************************************************************************************************/
119
120 PhyloTree::PhyloTree(string tfile){
121         try {
122                 m = MothurOut::getInstance();
123                 numNodes = 1;
124                 numSeqs = 0;
125                 tree.push_back(TaxNode("Root"));
126                 tree[0].heirarchyID = "0";
127                 maxLevel = 0;
128                 calcTotals = true;
129                 string name, tax;
130
131                 
132                 #ifdef USE_MPI
133                         int pid, num, processors;
134                         vector<unsigned long int> positions;
135                         
136                         MPI_Status status; 
137                         MPI_File inMPI;
138                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
139                         MPI_Comm_size(MPI_COMM_WORLD, &processors);
140
141                         char inFileName[1024];
142                         strcpy(inFileName, tfile.c_str());
143
144                         MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);  //comm, filename, mode, info, filepointer
145
146                         if (pid == 0) {
147                                 positions = m->setFilePosEachLine(tfile, num);
148                                 
149                                 //send file positions to all processes
150                                 for(int i = 1; i < processors; i++) { 
151                                         MPI_Send(&num, 1, MPI_INT, i, 2001, MPI_COMM_WORLD);
152                                         MPI_Send(&positions[0], (num+1), MPI_LONG, i, 2001, MPI_COMM_WORLD);
153                                 }
154                         }else{
155                                 MPI_Recv(&num, 1, MPI_INT, 0, 2001, MPI_COMM_WORLD, &status);
156                                 positions.resize(num+1);
157                                 MPI_Recv(&positions[0], (num+1), MPI_LONG, 0, 2001, MPI_COMM_WORLD, &status);
158                         }
159                 
160                         //read file 
161                         for(int i=0;i<num;i++){
162                                 //read next sequence
163                                 int length = positions[i+1] - positions[i];
164                                 char* buf4 = new char[length];
165
166                                 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
167
168                                 string tempBuf = buf4;
169                                 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
170                                 delete buf4;
171
172                                 istringstream iss (tempBuf,istringstream::in);
173                                 iss >> name >> tax;
174                                 addSeqToTree(name, tax);
175                         }
176                         
177                         MPI_File_close(&inMPI);
178                         MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
179                 
180                 #else
181                         ifstream in;
182                         m->openInputFile(tfile, in);
183                         
184                         //read in users taxonomy file and add sequences to tree
185                         while(!in.eof()){
186                                 in >> name >> tax; m->gobble(in);
187                         
188                                 addSeqToTree(name, tax);
189                         }
190                         in.close();
191                 #endif
192         
193                 assignHeirarchyIDs(0);
194         
195                 //create file for summary if needed
196                 setUp(tfile);
197         }
198         catch(exception& e) {
199                 m->errorOut(e, "PhyloTree", "PhyloTree");
200                 exit(1);
201         }
202 }
203
204 /**************************************************************************************************/
205
206 string PhyloTree::getNextTaxon(string& heirarchy, string seqname){
207         try {
208                 string currentLevel = "";
209                 if(heirarchy != ""){
210                         int pos = heirarchy.find_first_of(';');
211                         
212                         if (pos == -1) { //you can't find another ;
213                                 currentLevel = heirarchy;
214                                 heirarchy = "";
215                                 m->mothurOut(seqname + " is missing a ;, please check for other errors."); m->mothurOutEndLine();
216                         }else{
217                                 currentLevel=heirarchy.substr(0,pos);
218                                 if (pos != (heirarchy.length()-1)) {  heirarchy=heirarchy.substr(pos+1);  }
219                                 else { heirarchy = ""; }
220                         }
221                         
222                 }
223                 return currentLevel;
224         }
225         catch(exception& e) {
226                 m->errorOut(e, "PhyloTree", "getNextTaxon");
227                 exit(1);
228         }
229 }
230
231 /**************************************************************************************************/
232
233 int PhyloTree::addSeqToTree(string seqName, string seqTaxonomy){
234         try {
235                         
236                 numSeqs++;
237                 
238                 map<string, int>::iterator childPointer;
239                 
240                 int currentNode = 0;
241                 int level = 1;
242                 
243                 tree[0].accessions.push_back(seqName);
244                 string taxon;// = getNextTaxon(seqTaxonomy);
245         
246                 while(seqTaxonomy != ""){
247                         
248                         level++;
249                 
250                         if (m->control_pressed) { return 0; }
251                         
252                         //somehow the parent is getting one too many accnos
253                         //use print to reassign the taxa id
254                         taxon = getNextTaxon(seqTaxonomy, seqName);
255                         
256                         if (taxon == "") {  m->mothurOut(seqName + " has an error in the taxonomy.  This may be due to a ;;"); m->mothurOutEndLine(); if (currentNode != 0) {  uniqueTaxonomies[currentNode] = currentNode; } break;  }
257                         
258                         childPointer = tree[currentNode].children.find(taxon);
259                         
260                         if(childPointer != tree[currentNode].children.end()){   //if the node already exists, move on
261                                 currentNode = childPointer->second;
262                                 tree[currentNode].accessions.push_back(seqName);
263                                 name2Taxonomy[seqName] = currentNode;
264                         }
265                         else{                                                                                   //otherwise, create it
266                                 tree.push_back(TaxNode(taxon));
267                                 numNodes++;
268                                 tree[currentNode].children[taxon] = numNodes-1;
269                                 tree[numNodes-1].parent = currentNode;
270                                 
271                                 currentNode = tree[currentNode].children[taxon];
272                                 tree[currentNode].accessions.push_back(seqName);
273                                 name2Taxonomy[seqName] = currentNode;
274                         }
275         
276                         if (seqTaxonomy == "") {   uniqueTaxonomies[currentNode] = currentNode; }
277                 }
278         }
279         catch(exception& e) {
280                 m->errorOut(e, "PhyloTree", "addSeqToTree");
281                 exit(1);
282         }
283 }
284 /**************************************************************************************************/
285 vector<int> PhyloTree::getGenusNodes()  {
286         try {
287                 genusIndex.clear();
288                 //generate genusIndexes
289                 map<int, int>::iterator it2;
290                 for (it2=uniqueTaxonomies.begin(); it2!=uniqueTaxonomies.end(); it2++) {  genusIndex.push_back(it2->first);     }
291                 
292                 return genusIndex;
293         }
294         catch(exception& e) {
295                 m->errorOut(e, "PhyloTree", "getGenusNodes");
296                 exit(1);
297         }
298 }
299 /**************************************************************************************************/
300 vector<int> PhyloTree::getGenusTotals() {
301         try {
302         
303                 if (calcTotals) {
304                         totals.clear();
305                         //reset counts because we are on a new word
306                         for (int j = 0; j < genusIndex.size(); j++) {
307                                 totals.push_back(tree[genusIndex[j]].accessions.size());
308                         }
309                         return totals;
310                 }else{
311                         return totals;
312                 }
313                 
314         }
315         catch(exception& e) {
316                 m->errorOut(e, "PhyloTree", "getGenusNodes");
317                 exit(1);
318         }
319 }
320 /**************************************************************************************************/
321
322 void PhyloTree::assignHeirarchyIDs(int index){
323         try {
324                 map<string,int>::iterator it;
325                 int counter = 1;
326                 
327                 for(it=tree[index].children.begin();it!=tree[index].children.end();it++){
328                         tree[it->second].heirarchyID = tree[index].heirarchyID + '.' + toString(counter);
329                         counter++;
330                         tree[it->second].level = tree[index].level + 1;
331                                                 
332                         //save maxLevel for binning the unclassified seqs
333                         if (tree[it->second].level > maxLevel) { maxLevel = tree[it->second].level; } 
334                         
335                         assignHeirarchyIDs(it->second);
336                 }
337         }
338         catch(exception& e) {
339                 m->errorOut(e, "PhyloTree", "assignHeirarchyIDs");
340                 exit(1);
341         }
342 }
343 /**************************************************************************************************/
344 void PhyloTree::setUp(string tfile){
345         try{
346                 string taxFileNameTest = tfile.substr(0,tfile.find_last_of(".")+1) + "tree.sum";
347                 
348                 #ifdef USE_MPI
349                         int pid;
350                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
351
352                         if (pid == 0) {  binUnclassified(taxFileNameTest);  }
353                 
354                 #else
355                         binUnclassified(taxFileNameTest); 
356                 #endif
357         }
358         catch(exception& e) {
359                 m->errorOut(e, "PhyloTree", "setUp");
360                 exit(1);
361         }
362 }
363 /**************************************************************************************************/
364 void PhyloTree::binUnclassified(string file){
365         try {
366         
367                 ofstream out;
368                 m->openOutputFile(file, out);
369                 
370                 map<string, int>::iterator itBin;
371                 map<string, int>::iterator childPointer;
372                 
373                 vector<TaxNode> copy = tree;
374                         
375                 //fill out tree
376                 fillOutTree(0, copy);
377         
378                 //get leaf nodes that may need extension
379                 for (int i = 0; i < copy.size(); i++) {  
380
381                         if (copy[i].children.size() == 0) {
382                                 leafNodes[i] = i;
383                         }
384                 }
385                 
386                 int copyNodes = copy.size();
387         
388                 //go through the seqs and if a sequence finest taxon is not the same level as the most finely defined taxon then classify it as unclassified where necessary
389                 map<int, int>::iterator itLeaf;
390                 for (itLeaf = leafNodes.begin(); itLeaf != leafNodes.end(); itLeaf++) {
391                         
392                         if (m->control_pressed) {  out.close(); break;  }
393                         
394                         int level = copy[itLeaf->second].level;
395                         int currentNode = itLeaf->second;
396                         
397                         //this sequence is unclassified at some levels
398                         while(level < maxLevel){
399                 
400                                 level++;
401                         
402                                 string taxon = "unclassified";  
403                                 
404                                 //does the parent have a child names 'unclassified'?
405                                 childPointer = copy[currentNode].children.find(taxon);
406                                 
407                                 if(childPointer != copy[currentNode].children.end()){   //if the node already exists, move on
408                                         currentNode = childPointer->second; //currentNode becomes 'unclassified'
409                                 }
410                                 else{                                                                                   //otherwise, create it
411                                         copy.push_back(TaxNode(taxon));
412                                         copyNodes++;
413                                         copy[currentNode].children[taxon] = copyNodes-1;
414                                         copy[copyNodes-1].parent = currentNode;
415                                         copy[copyNodes-1].level = copy[currentNode].level + 1;
416                                                                         
417                                         currentNode = copy[currentNode].children[taxon];
418                                 }
419                         }
420                 }
421                 
422                 if (!m->control_pressed) {
423                         //print copy tree
424                         print(out, copy);
425                 }
426                                 
427         }
428         catch(exception& e) {
429                 m->errorOut(e, "PhyloTree", "binUnclassified");
430                 exit(1);
431         }
432 }
433 /**************************************************************************************************/
434 void PhyloTree::fillOutTree(int index, vector<TaxNode>& copy) {
435         try {
436         
437                 map<string,int>::iterator it;
438                 
439                 it = copy[index].children.find("unclassified");
440                 if (it == copy[index].children.end()) { //no unclassified at this level
441                         string taxon = "unclassified";
442                         copy.push_back(TaxNode(taxon));
443                         copy[index].children[taxon] = copy.size()-1;
444                         copy[copy.size()-1].parent = index;
445                         copy[copy.size()-1].level = copy[index].level + 1;
446                 }
447                 
448                 if (tree[index].level < maxLevel) {
449                         for(it=tree[index].children.begin();it!=tree[index].children.end();it++){ //check your children
450                                 fillOutTree(it->second, copy);
451                         }
452                 }
453
454         }
455         catch(exception& e) {
456                 m->errorOut(e, "PhyloTree", "fillOutTree");
457                 exit(1);
458         }
459 }
460 /**************************************************************************************************/
461 string PhyloTree::getFullTaxonomy(string seqName) {
462         try {
463                 string tax = "";
464                 
465                 int currentNode = name2Taxonomy[seqName];
466                 
467                 while (tree[currentNode].parent != -1) {
468                         tax = tree[currentNode].name + ";" + tax;
469                         currentNode = tree[currentNode].parent;
470                 }
471                 
472                 return tax;
473         }
474         catch(exception& e) {
475                 m->errorOut(e, "PhyloTree", "getFullTaxonomy");
476                 exit(1);
477         }
478 }
479 /**************************************************************************************************/
480
481 void PhyloTree::print(ofstream& out, vector<TaxNode>& copy){
482         try {
483         
484                 //output mothur version
485                 out << "#" << m->getVersion() << endl;
486                 
487                 out << copy.size() << endl;
488                 
489                 out << maxLevel << endl;
490                 
491                 for (int i = 0; i < copy.size(); i++) {
492         
493                         out << copy[i].level << '\t'<< copy[i].name << '\t' << copy[i].children.size() << '\t';
494                         
495                         map<string,int>::iterator it;
496                         for(it=copy[i].children.begin();it!=copy[i].children.end();it++){
497                                 out << it->first << '\t' << it->second << '\t';
498                         }
499                         out << endl;
500                 }
501                 
502                 out.close();
503         }
504         catch(exception& e) {
505                 m->errorOut(e, "PhyloTree", "print");
506                 exit(1);
507         }
508 }
509 /**************************************************************************************************/
510 void PhyloTree::printTreeNodes(string treefilename) {
511         try {
512         
513                 #ifdef USE_MPI
514                         int pid;
515                         MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
516
517                         if (pid == 0) {  
518                 
519                 #endif
520
521                         ofstream outTree;
522                         m->openOutputFile(treefilename, outTree);
523                         
524                         //output mothur version
525                         outTree << "#" << m->getVersion() << endl;
526                         
527                         //print treenodes
528                         outTree << tree.size() << endl;
529                         for (int i = 0; i < tree.size(); i++) {
530                                 outTree << tree[i].name << '\t' << tree[i].level << '\t' << tree[i].parent << endl;
531                         }
532                         
533                         //print genus nodes
534                         outTree << endl << uniqueTaxonomies.size() << endl;
535                         map<int, int>::iterator it2;
536                         for (it2=uniqueTaxonomies.begin(); it2!=uniqueTaxonomies.end(); it2++) {  outTree << it2->first << '\t' << tree[it2->first].accessions.size() << endl;  }
537                         outTree << endl;
538                         
539                         outTree.close();
540                 
541                 #ifdef USE_MPI
542                         }
543                 #endif
544
545                 
546         }
547         catch(exception& e) {
548                 m->errorOut(e, "PhyloTree", "printTreeNodes");
549                 exit(1);
550         }
551 }
552 /**************************************************************************************************/
553 TaxNode PhyloTree::get(int i ){
554         try {
555                 if (i < tree.size()) {  return tree[i];  }
556                 else {  cout << i << '\t' << tree.size() << endl ; m->mothurOut("Mismatch with taxonomy and template files. Cannot continue."); m->mothurOutEndLine(); exit(1); }
557         }
558         catch(exception& e) {
559                 m->errorOut(e, "PhyloTree", "get");
560                 exit(1);
561         }
562 }
563 /**************************************************************************************************/
564 TaxNode PhyloTree::get(string seqName){
565         try {
566                 map<string, int>::iterator itFind = name2Taxonomy.find(seqName);
567         
568                 if (itFind != name2Taxonomy.end()) {  return tree[name2Taxonomy[seqName]];  }
569                 else { m->mothurOut("Cannot find " + seqName + ". Mismatch with taxonomy and template files. Cannot continue."); m->mothurOutEndLine(); exit(1);}
570         }
571         catch(exception& e) {
572                 m->errorOut(e, "PhyloTree", "get");
573                 exit(1);
574         }
575 }
576 /**************************************************************************************************/
577 string PhyloTree::getName(int i ){
578         try {
579                 if (i < tree.size()) {  return tree[i].name;     }
580                 else { m->mothurOut("Mismatch with taxonomy and template files. Cannot continue."); m->mothurOutEndLine(); exit(1); }
581         }
582         catch(exception& e) {
583                 m->errorOut(e, "PhyloTree", "get");
584                 exit(1);
585         }
586 }
587 /**************************************************************************************************/
588 int PhyloTree::getIndex(string seqName){
589         try {
590                 map<string, int>::iterator itFind = name2Taxonomy.find(seqName);
591         
592                 if (itFind != name2Taxonomy.end()) {  return name2Taxonomy[seqName];  }
593                 else { m->mothurOut("Cannot find " + seqName + ". Mismatch with taxonomy and template files. Cannot continue."); m->mothurOutEndLine(); exit(1);}
594         }
595         catch(exception& e) {
596                 m->errorOut(e, "PhyloTree", "get");
597                 exit(1);
598         }
599 }
600 /**************************************************************************************************/
601 bool PhyloTree::ErrorCheck(vector<string> templateFileNames){
602         try {
603         
604                 bool okay = true;
605                 
606                 map<string, int>::iterator itFind;
607                 map<string, int> taxonomyFileNames = name2Taxonomy;
608                 
609                 for (int i = 0; i < templateFileNames.size(); i++) {
610                         itFind = taxonomyFileNames.find(templateFileNames[i]);
611                         
612                         if (itFind != taxonomyFileNames.end()) { //found it so erase it
613                                 taxonomyFileNames.erase(itFind);
614                         }else {
615                                 m->mothurOut(templateFileNames[i] + " is in your template file and is not in your taxonomy file. Please correct."); m->mothurOutEndLine();
616                                 okay = false;
617                         }
618                         
619                         templateFileNames.erase(templateFileNames.begin()+i);
620                         i--;
621                 }
622                 
623                 if (taxonomyFileNames.size() > 0) { //there are names in tax file that are not in template
624                         okay = false;
625                         
626                         for (itFind = taxonomyFileNames.begin(); itFind != taxonomyFileNames.end(); itFind++) {
627                                 m->mothurOut(itFind->first + " is in your taxonomy file and is not in your template file. Please correct."); m->mothurOutEndLine();
628                         }
629                 }
630                 
631                 return okay;
632         }
633         catch(exception& e) {
634                 m->errorOut(e, "PhyloTree", "ErrorCheck");
635                 exit(1);
636         }
637 }
638 /**************************************************************************************************/
639         
640
641
642