5 * Created by Pat Schloss on 6/17/09.
6 * Copyright 2009 Patrick D. Schloss. All rights reserved.
10 #include "phylotree.h"
12 /**************************************************************************************************/
14 PhyloTree::PhyloTree(){
16 m = MothurOut::getInstance();
19 tree.push_back(TaxNode("Root"));
20 tree[0].heirarchyID = "0";
23 addSeqToTree("unknown", "unknown;");
26 m->errorOut(e, "PhyloTree", "PhyloTree");
30 /**************************************************************************************************/
32 PhyloTree::PhyloTree(ifstream& in, string filename){
34 m = MothurOut::getInstance();
44 char inFileName[1024];
45 strcpy(inFileName, filename.c_str());
47 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI);
48 MPI_File_get_size(inMPI, &size);
50 char* buffer = new char[size];
51 MPI_File_read(inMPI, buffer, size, MPI_CHAR, &status);
53 string tempBuf = buffer;
54 if (tempBuf.length() > size) { tempBuf = tempBuf.substr(0, size); }
55 istringstream iss (tempBuf,istringstream::in);
59 m->getline(iss); m->gobble(iss);
61 iss >> numNodes; m->gobble(iss);
63 tree.resize(numNodes);
65 for (int i = 0; i < tree.size(); i++) {
66 iss >> tree[i].name >> tree[i].level >> tree[i].parent; m->gobble(iss);
71 iss >> numGenus; m->gobble(iss);
75 for (int i = 0; i < numGenus; i++) {
76 iss >> gnode >> gsize; m->gobble(iss);
78 uniqueTaxonomies.insert(gnode);
79 totals.push_back(gsize);
82 MPI_File_close(&inMPI);
86 string line = m->getline(in); m->gobble(in);
88 in >> numNodes; m->gobble(in);
90 tree.resize(numNodes);
92 for (int i = 0; i < tree.size(); i++) {
93 in >> tree[i].name >> tree[i].level >> tree[i].parent; m->gobble(in);
98 in >> numGenus; m->gobble(in);
102 for (int i = 0; i < numGenus; i++) {
103 in >> gnode >> gsize; m->gobble(in);
105 uniqueTaxonomies.insert(gnode);
106 totals.push_back(gsize);
114 catch(exception& e) {
115 m->errorOut(e, "PhyloTree", "PhyloTree");
119 /**************************************************************************************************/
121 PhyloTree::PhyloTree(string tfile){
123 m = MothurOut::getInstance();
126 tree.push_back(TaxNode("Root"));
127 tree[0].heirarchyID = "0";
133 int pid, num, processors;
134 vector<unsigned long long> positions;
138 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
139 MPI_Comm_size(MPI_COMM_WORLD, &processors);
141 char inFileName[1024];
142 strcpy(inFileName, tfile.c_str());
144 MPI_File_open(MPI_COMM_WORLD, inFileName, MPI_MODE_RDONLY, MPI_INFO_NULL, &inMPI); //comm, filename, mode, info, filepointer
147 positions = m->setFilePosEachLine(tfile, num);
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);
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);
161 for(int i=0;i<num;i++){
163 int length = positions[i+1] - positions[i];
164 char* buf4 = new char[length];
166 MPI_File_read_at(inMPI, positions[i], buf4, length, MPI_CHAR, &status);
168 string tempBuf = buf4;
169 if (tempBuf.length() > length) { tempBuf = tempBuf.substr(0, length); }
172 istringstream iss (tempBuf,istringstream::in);
174 addSeqToTree(name, tax);
177 MPI_File_close(&inMPI);
178 MPI_Barrier(MPI_COMM_WORLD); //make everyone wait - just in case
181 map<string, string> temp;
182 m->readTax(tfile, temp);
184 for (map<string, string>::iterator itTemp = temp.begin(); itTemp != temp.end();) {
185 addSeqToTree(itTemp->first, itTemp->second);
186 temp.erase(itTemp++);
190 assignHeirarchyIDs(0);
193 string unknownTax = "unknown;";
194 //added last taxon until you get desired level
195 for (int i = 1; i < maxLevel; i++) {
196 unknownTax += "unclassfied;";
199 addSeqToTree("unknown", unknownTax);
201 //create file for summary if needed
204 catch(exception& e) {
205 m->errorOut(e, "PhyloTree", "PhyloTree");
210 /**************************************************************************************************/
212 string PhyloTree::getNextTaxon(string& heirarchy, string seqname){
214 string currentLevel = "";
216 int pos = heirarchy.find_first_of(';');
218 if (pos == -1) { //you can't find another ;
219 currentLevel = heirarchy;
221 m->mothurOut(seqname + " is missing a ;, please check for other errors."); m->mothurOutEndLine();
223 currentLevel=heirarchy.substr(0,pos);
224 if (pos != (heirarchy.length()-1)) { heirarchy=heirarchy.substr(pos+1); }
225 else { heirarchy = ""; }
231 catch(exception& e) {
232 m->errorOut(e, "PhyloTree", "getNextTaxon");
237 /**************************************************************************************************/
239 int PhyloTree::addSeqToTree(string seqName, string seqTaxonomy){
243 map<string, int>::iterator childPointer;
248 tree[0].accessions.push_back(seqName);
249 m->removeConfidences(seqTaxonomy);
251 string taxon;// = getNextTaxon(seqTaxonomy);
253 while(seqTaxonomy != ""){
257 if (m->control_pressed) { return 0; }
259 //somehow the parent is getting one too many accnos
260 //use print to reassign the taxa id
261 taxon = getNextTaxon(seqTaxonomy, seqName);
263 if (m->debug) { m->mothurOut(seqName +'\t' + taxon +'\n'); }
265 if (taxon == "") { m->mothurOut(seqName + " has an error in the taxonomy. This may be due to a ;;"); m->mothurOutEndLine(); if (currentNode != 0) { uniqueTaxonomies.insert(currentNode); } break; }
267 childPointer = tree[currentNode].children.find(taxon);
269 if(childPointer != tree[currentNode].children.end()){ //if the node already exists, move on
270 currentNode = childPointer->second;
271 tree[currentNode].accessions.push_back(seqName);
272 name2Taxonomy[seqName] = currentNode;
274 else{ //otherwise, create it
275 tree.push_back(TaxNode(taxon));
277 tree[currentNode].children[taxon] = numNodes-1;
278 tree[numNodes-1].parent = currentNode;
280 currentNode = tree[currentNode].children[taxon];
281 tree[currentNode].accessions.push_back(seqName);
282 name2Taxonomy[seqName] = currentNode;
285 if (seqTaxonomy == "") { uniqueTaxonomies.insert(currentNode); }
290 catch(exception& e) {
291 m->errorOut(e, "PhyloTree", "addSeqToTree");
295 /**************************************************************************************************/
296 vector<int> PhyloTree::getGenusNodes() {
299 //generate genusIndexes
300 set<int>::iterator it2;
302 for (it2=uniqueTaxonomies.begin(); it2!=uniqueTaxonomies.end(); it2++) { genusIndex.push_back(*it2); temp[*it2] = genusIndex.size()-1; }
304 for (map<string, int>::iterator itName = name2Taxonomy.begin(); itName != name2Taxonomy.end(); itName++) {
305 map<int, int>::iterator itTemp = temp.find(itName->second);
306 if (itTemp != temp.end()) { name2GenusNodeIndex[itName->first] = itTemp->second; }
307 else { m->mothurOut("[ERROR]: trouble making name2GenusNodeIndex, aborting.\n"); m->control_pressed = true; }
312 catch(exception& e) {
313 m->errorOut(e, "PhyloTree", "getGenusNodes");
317 /**************************************************************************************************/
318 vector<int> PhyloTree::getGenusTotals() {
323 //reset counts because we are on a new word
324 for (int j = 0; j < genusIndex.size(); j++) {
325 totals.push_back(tree[genusIndex[j]].accessions.size());
333 catch(exception& e) {
334 m->errorOut(e, "PhyloTree", "getGenusNodes");
338 /**************************************************************************************************/
340 void PhyloTree::assignHeirarchyIDs(int index){
342 map<string,int>::iterator it;
345 for(it=tree[index].children.begin();it!=tree[index].children.end();it++){
347 if (m->debug) { m->mothurOut(toString(index) +'\t' + tree[it->second].name +'\n'); }
349 tree[it->second].heirarchyID = tree[index].heirarchyID + '.' + toString(counter);
351 tree[it->second].level = tree[index].level + 1;
353 //save maxLevel for binning the unclassified seqs
354 if (tree[it->second].level > maxLevel) { maxLevel = tree[it->second].level; }
356 assignHeirarchyIDs(it->second);
359 catch(exception& e) {
360 m->errorOut(e, "PhyloTree", "assignHeirarchyIDs");
364 /**************************************************************************************************/
365 void PhyloTree::setUp(string tfile){
367 string taxFileNameTest = tfile.substr(0,tfile.find_last_of(".")+1) + "tree.sum";
371 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
373 if (pid == 0) { binUnclassified(taxFileNameTest); }
376 binUnclassified(taxFileNameTest);
379 catch(exception& e) {
380 m->errorOut(e, "PhyloTree", "setUp");
384 /**************************************************************************************************/
385 void PhyloTree::binUnclassified(string file){
389 m->openOutputFile(file, out);
391 map<string, int>::iterator itBin;
392 map<string, int>::iterator childPointer;
394 vector<TaxNode> copy = tree;
397 fillOutTree(0, copy);
399 //get leaf nodes that may need extension
400 for (int i = 0; i < copy.size(); i++) {
402 if (copy[i].children.size() == 0) {
407 if (m->debug) { m->mothurOut("maxLevel = " + toString(maxLevel) +'\n'); }
409 int copyNodes = copy.size();
411 //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
412 map<int, int>::iterator itLeaf;
413 for (itLeaf = leafNodes.begin(); itLeaf != leafNodes.end(); itLeaf++) {
415 if (m->control_pressed) { out.close(); break; }
417 int level = copy[itLeaf->second].level;
418 int currentNode = itLeaf->second;
420 if (m->debug) { m->mothurOut(copy[currentNode].name +'\n'); }
422 //this sequence is unclassified at some levels
423 while(level < maxLevel){
426 if (m->debug) { m->mothurOut("level = " + toString(level) +'\n'); }
428 string taxon = "unclassified";
430 //does the parent have a child names 'unclassified'?
431 childPointer = copy[currentNode].children.find(taxon);
433 if(childPointer != copy[currentNode].children.end()){ //if the node already exists, move on
434 currentNode = childPointer->second; //currentNode becomes 'unclassified'
436 else{ //otherwise, create it
437 copy.push_back(TaxNode(taxon));
439 copy[currentNode].children[taxon] = copyNodes-1;
440 copy[copyNodes-1].parent = currentNode;
441 copy[copyNodes-1].level = copy[currentNode].level + 1;
443 currentNode = copy[currentNode].children[taxon];
448 if (!m->control_pressed) {
454 catch(exception& e) {
455 m->errorOut(e, "PhyloTree", "binUnclassified");
459 /**************************************************************************************************/
460 void PhyloTree::fillOutTree(int index, vector<TaxNode>& copy) {
463 map<string,int>::iterator it;
465 it = copy[index].children.find("unclassified");
466 if (it == copy[index].children.end()) { //no unclassified at this level
467 string taxon = "unclassified";
468 copy.push_back(TaxNode(taxon));
469 copy[index].children[taxon] = copy.size()-1;
470 copy[copy.size()-1].parent = index;
471 copy[copy.size()-1].level = copy[index].level + 1;
474 if (tree[index].level < maxLevel) {
475 for(it=tree[index].children.begin();it!=tree[index].children.end();it++){ //check your children
476 fillOutTree(it->second, copy);
481 catch(exception& e) {
482 m->errorOut(e, "PhyloTree", "fillOutTree");
486 /**************************************************************************************************/
487 string PhyloTree::getFullTaxonomy(string seqName) {
491 int currentNode = name2Taxonomy[seqName];
493 while (tree[currentNode].parent != -1) {
494 tax = tree[currentNode].name + ";" + tax;
495 currentNode = tree[currentNode].parent;
500 catch(exception& e) {
501 m->errorOut(e, "PhyloTree", "getFullTaxonomy");
505 /**************************************************************************************************/
507 void PhyloTree::print(ofstream& out, vector<TaxNode>& copy){
510 //output mothur version
511 out << "#" << m->getVersion() << endl;
513 out << copy.size() << endl;
515 out << maxLevel << endl;
517 for (int i = 0; i < copy.size(); i++) {
519 out << copy[i].level << '\t'<< copy[i].name << '\t' << copy[i].children.size() << '\t';
521 map<string,int>::iterator it;
522 for(it=copy[i].children.begin();it!=copy[i].children.end();it++){
523 out << it->first << '\t' << it->second << '\t';
530 catch(exception& e) {
531 m->errorOut(e, "PhyloTree", "print");
535 /**************************************************************************************************/
536 void PhyloTree::printTreeNodes(string treefilename) {
541 MPI_Comm_rank(MPI_COMM_WORLD, &pid); //find out who we are
548 m->openOutputFile(treefilename, outTree);
550 //output mothur version
551 outTree << "#" << m->getVersion() << endl;
554 outTree << tree.size() << endl;
555 for (int i = 0; i < tree.size(); i++) {
556 outTree << tree[i].name << '\t' << tree[i].level << '\t' << tree[i].parent << endl;
560 outTree << endl << uniqueTaxonomies.size() << endl;
561 set<int>::iterator it2;
562 for (it2=uniqueTaxonomies.begin(); it2!=uniqueTaxonomies.end(); it2++) { outTree << *it2 << '\t' << tree[*it2].accessions.size() << endl; }
573 catch(exception& e) {
574 m->errorOut(e, "PhyloTree", "printTreeNodes");
578 /**************************************************************************************************/
579 TaxNode PhyloTree::get(int i ){
581 if (i < tree.size()) { return tree[i]; }
582 else { cout << i << '\t' << tree.size() << endl ; m->mothurOut("Mismatch with taxonomy and template files. Cannot continue."); m->mothurOutEndLine(); exit(1); }
584 catch(exception& e) {
585 m->errorOut(e, "PhyloTree", "get");
589 /**************************************************************************************************/
590 TaxNode PhyloTree::get(string seqName){
592 map<string, int>::iterator itFind = name2Taxonomy.find(seqName);
594 if (itFind != name2Taxonomy.end()) { return tree[name2Taxonomy[seqName]]; }
595 else { m->mothurOut("Cannot find " + seqName + ". Mismatch with taxonomy and template files. Cannot continue."); m->mothurOutEndLine(); exit(1);}
597 catch(exception& e) {
598 m->errorOut(e, "PhyloTree", "get");
602 /**************************************************************************************************/
603 string PhyloTree::getName(int i ){
605 if (i < tree.size()) { return tree[i].name; }
606 else { m->mothurOut("Mismatch with taxonomy and template files. Cannot continue."); m->mothurOutEndLine(); exit(1); }
608 catch(exception& e) {
609 m->errorOut(e, "PhyloTree", "get");
613 /**************************************************************************************************/
614 int PhyloTree::getGenusIndex(string seqName){
616 map<string, int>::iterator itFind = name2GenusNodeIndex.find(seqName);
618 if (itFind != name2GenusNodeIndex.end()) { return itFind->second; }
619 else { m->mothurOut("Cannot find " + seqName + ". Could be a mismatch with taxonomy and template files. Cannot continue."); m->mothurOutEndLine(); exit(1);}
621 catch(exception& e) {
622 m->errorOut(e, "PhyloTree", "get");
626 /**************************************************************************************************/
627 bool PhyloTree::ErrorCheck(vector<string> templateFileNames){
631 templateFileNames.push_back("unknown");
633 map<string, int>::iterator itFind;
634 map<string, int> taxonomyFileNames = name2Taxonomy;
636 if (m->debug) { m->mothurOut("[DEBUG]: in error check. Numseqs in template = " + toString(templateFileNames.size()) + ". Numseqs in taxonomy = " + toString(taxonomyFileNames.size()) + ".\n"); }
638 for (int i = 0; i < templateFileNames.size(); i++) {
639 itFind = taxonomyFileNames.find(templateFileNames[i]);
641 if (itFind != taxonomyFileNames.end()) { //found it so erase it
642 taxonomyFileNames.erase(itFind);
644 m->mothurOut("'" +templateFileNames[i] + "' is in your template file and is not in your taxonomy file. Please correct."); m->mothurOutEndLine();
648 //templateFileNames.erase(templateFileNames.begin()+i);
651 templateFileNames.clear();
653 if (taxonomyFileNames.size() > 0) { //there are names in tax file that are not in template
656 for (itFind = taxonomyFileNames.begin(); itFind != taxonomyFileNames.end(); itFind++) {
657 m->mothurOut(itFind->first + " is in your taxonomy file and is not in your template file. Please correct."); m->mothurOutEndLine();
663 catch(exception& e) {
664 m->errorOut(e, "PhyloTree", "ErrorCheck");
668 /**************************************************************************************************/