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