5 * Created by Sarah Westcott on 1/22/09.
6 * Copyright 2009 Schloss Lab UMASS Amherst. All rights reserved.
12 /*****************************************************************/
13 Tree::Tree(int num, TreeMap* t) : tmap(t) {
15 m = MothurOut::getInstance();
18 numNodes = 2*numLeaves - 1;
20 tree.resize(numNodes);
23 m->errorOut(e, "Tree", "Tree - numNodes");
27 /*****************************************************************/
28 Tree::Tree(string g) { //do not use tree generated by this its just to extract the treenames, its a chicken before the egg thing that needs to be revisited.
30 m = MothurOut::getInstance();
31 parseTreeFile(); m->runParse = false;
34 m->errorOut(e, "Tree", "Tree - just parse");
38 /*****************************************************************/
39 Tree::Tree(TreeMap* t) : tmap(t) {
41 m = MothurOut::getInstance();
43 if (m->runParse == true) { parseTreeFile(); m->runParse = false; }
44 //for(int i = 0; i < globaldata->Treenames.size(); i++) { cout << i << '\t' << globaldata->Treenames[i] << endl; }
45 numLeaves = m->Treenames.size();
46 numNodes = 2*numLeaves - 1;
48 tree.resize(numNodes);
50 //initialize groupNodeInfo
51 for (int i = 0; i < (tmap->getNamesOfGroups()).size(); i++) {
52 groupNodeInfo[(tmap->getNamesOfGroups())[i]].resize(0);
55 //initialize tree with correct number of nodes, name and group info.
56 for (int i = 0; i < numNodes; i++) {
57 //initialize leaf nodes
58 if (i <= (numLeaves-1)) {
59 tree[i].setName(m->Treenames[i]);
62 string group = tmap->getGroup(m->Treenames[i]);
64 vector<string> tempGroups; tempGroups.push_back(group);
65 tree[i].setGroup(tempGroups);
66 groupNodeInfo[group].push_back(i);
68 //set pcount and pGroup for groupname to 1.
69 tree[i].pcount[group] = 1;
70 tree[i].pGroups[group] = 1;
72 //Treemap knows name, group and index to speed up search
73 tmap->setIndex(m->Treenames[i], i);
75 //intialize non leaf nodes
76 }else if (i > (numLeaves-1)) {
78 vector<string> tempGroups;
79 tree[i].setGroup(tempGroups);
85 m->errorOut(e, "Tree", "Tree");
89 /*****************************************************************/
90 Tree::Tree(TreeMap* t, vector< vector<double> >& sims) : tmap(t) {
92 m = MothurOut::getInstance();
94 if (m->runParse == true) { parseTreeFile(); m->runParse = false; }
95 numLeaves = m->Treenames.size();
96 numNodes = 2*numLeaves - 1;
98 tree.resize(numNodes);
100 //initialize groupNodeInfo
101 for (int i = 0; i < (tmap->getNamesOfGroups()).size(); i++) {
102 groupNodeInfo[(tmap->getNamesOfGroups())[i]].resize(0);
105 //initialize tree with correct number of nodes, name and group info.
106 for (int i = 0; i < numNodes; i++) {
107 //initialize leaf nodes
108 if (i <= (numLeaves-1)) {
109 tree[i].setName(m->Treenames[i]);
112 string group = tmap->getGroup(m->Treenames[i]);
114 vector<string> tempGroups; tempGroups.push_back(group);
115 tree[i].setGroup(tempGroups);
116 groupNodeInfo[group].push_back(i);
118 //set pcount and pGroup for groupname to 1.
119 tree[i].pcount[group] = 1;
120 tree[i].pGroups[group] = 1;
122 //Treemap knows name, group and index to speed up search
123 tmap->setIndex(m->Treenames[i], i);
125 //intialize non leaf nodes
126 }else if (i > (numLeaves-1)) {
128 vector<string> tempGroups;
129 tree[i].setGroup(tempGroups);
133 //build tree from matrix
135 map<int, int> indexes; //maps row in simMatrix to vector index in the tree
136 for (int g = 0; g < numLeaves; g++) { indexes[g] = g; }
138 //do merges and create tree structure by setting parents and children
139 //there are numGroups - 1 merges to do
140 for (int i = 0; i < (numLeaves - 1); i++) {
141 float largest = -1000.0;
143 if (m->control_pressed) { break; }
146 //find largest value in sims matrix by searching lower triangle
147 for (int j = 1; j < sims.size(); j++) {
148 for (int k = 0; k < j; k++) {
149 if (sims[j][k] > largest) { largest = sims[j][k]; row = j; column = k; }
153 //set non-leaf node info and update leaves to know their parents
155 tree[numLeaves + i].setChildren(indexes[row], indexes[column]);
158 tree[indexes[row]].setParent(numLeaves + i);
159 tree[indexes[column]].setParent(numLeaves + i);
161 //blength = distance / 2;
162 float blength = ((1.0 - largest) / 2);
165 tree[indexes[row]].setBranchLength(blength - tree[indexes[row]].getLengthToLeaves());
166 tree[indexes[column]].setBranchLength(blength - tree[indexes[column]].getLengthToLeaves());
168 //set your length to leaves to your childs length plus branchlength
169 tree[numLeaves + i].setLengthToLeaves(tree[indexes[row]].getLengthToLeaves() + tree[indexes[row]].getBranchLength());
173 indexes[row] = numLeaves+i;
174 indexes[column] = numLeaves+i;
176 //remove highest value that caused the merge.
177 sims[row][column] = -1000.0;
178 sims[column][row] = -1000.0;
180 //merge values in simsMatrix
181 for (int n = 0; n < sims.size(); n++) {
182 //row becomes merge of 2 groups
183 sims[row][n] = (sims[row][n] + sims[column][n]) / 2;
184 sims[n][row] = sims[row][n];
186 sims[column][n] = -1000.0;
187 sims[n][column] = -1000.0;
191 //adjust tree to make sure root to tip length is .5
192 int root = findRoot();
193 tree[root].setBranchLength((0.5 - tree[root].getLengthToLeaves()));
196 catch(exception& e) {
197 m->errorOut(e, "Tree", "Tree");
201 /*****************************************************************/
203 /*****************************************************************/
204 void Tree::addNamesToCounts(map<string, string> nameMap) {
206 //ex. seq1 seq2,seq3,se4
212 //before this function seq1.pcount = pasture -> 1
213 //after seq1.pcount = pasture -> 2, forest -> 1, ocean -> 1
215 //before this function seq1.pgroups = pasture -> 1
216 //after seq1.pgroups = pasture -> 1 since that is the dominant group
219 //go through each leaf and update its pcounts and pgroups
223 for (int i = 0; i < numLeaves; i++) {
225 string name = tree[i].getName();
227 map<string, string>::iterator itNames = nameMap.find(name);
229 if (itNames == nameMap.end()) { m->mothurOut(name + " is not in your name file, please correct."); m->mothurOutEndLine(); exit(1); }
231 vector<string> dupNames;
232 m->splitAtComma(nameMap[name], dupNames);
234 map<string, int>::iterator itCounts;
236 set<string> groupsAddedForThisNode;
237 for (int j = 0; j < dupNames.size(); j++) {
239 string group = tmap->getGroup(dupNames[j]);
241 if (dupNames[j] != name) {//you already added yourself in the constructor
243 if (groupsAddedForThisNode.count(group) == 0) { groupNodeInfo[group].push_back(i); groupsAddedForThisNode.insert(group); } //if you have not already added this node for this group, then add it
246 itCounts = tree[i].pcount.find(group);
247 if (itCounts == tree[i].pcount.end()) { //new group, add it
248 tree[i].pcount[group] = 1;
250 tree[i].pcount[group]++;
254 itCounts = tree[i].pGroups.find(group);
255 if (itCounts == tree[i].pGroups.end()) { //new group, add it
256 tree[i].pGroups[group] = 1;
258 tree[i].pGroups[group]++;
262 if(tree[i].pGroups[group] > maxPars){
263 maxPars = tree[i].pGroups[group];
265 }else { groupsAddedForThisNode.insert(group); } //add it so you don't add it to groupNodeInfo again
268 if (maxPars > 1) { //then we have some more dominant groups
269 //erase all the groups that are less than maxPars because you found a more dominant group.
270 for(it=tree[i].pGroups.begin();it!=tree[i].pGroups.end();){
271 if(it->second < maxPars){
272 tree[i].pGroups.erase(it++);
275 //set one remaining groups to 1
276 for(it=tree[i].pGroups.begin();it!=tree[i].pGroups.end();it++){
277 tree[i].pGroups[it->first] = 1;
281 //update groups to reflect all the groups this node represents
282 vector<string> nodeGroups;
283 map<string, int>::iterator itGroups;
284 for (itGroups = tree[i].pcount.begin(); itGroups != tree[i].pcount.end(); itGroups++) {
285 nodeGroups.push_back(itGroups->first);
287 tree[i].setGroup(nodeGroups);
293 //cout << "addNamesToCounts\t" << (B - A) / CLOCKS_PER_SEC << endl;
296 catch(exception& e) {
297 m->errorOut(e, "Tree", "addNamesToCounts");
301 /*****************************************************************/
302 int Tree::getIndex(string searchName) {
304 //Treemap knows name, group and index to speed up search
305 // getIndex function will return the vector index or -1 if seq is not found.
306 int index = tmap->getIndex(searchName);
310 catch(exception& e) {
311 m->errorOut(e, "Tree", "getIndex");
315 /*****************************************************************/
317 void Tree::setIndex(string searchName, int index) {
319 //set index in treemap
320 tmap->setIndex(searchName, index);
322 catch(exception& e) {
323 m->errorOut(e, "Tree", "setIndex");
327 /*****************************************************************/
328 int Tree::assembleTree(map<string, string> nameMap) {
333 //if user has given a names file we want to include that info in the pgroups and pcount info.
334 if(nameMap.size() != 0) { addNamesToCounts(nameMap); }
336 //build the pGroups in non leaf nodes to be used in the parsimony calcs.
337 for (int i = numLeaves; i < numNodes; i++) {
338 if (m->control_pressed) { return 1; }
340 tree[i].pGroups = (mergeGroups(i));
341 tree[i].pcount = (mergeGcounts(i));
346 catch(exception& e) {
347 m->errorOut(e, "Tree", "assembleTree");
351 /*****************************************************************
352 int Tree::assembleTree(string n) {
355 //build the pGroups in non leaf nodes to be used in the parsimony calcs.
356 for (int i = numLeaves; i < numNodes; i++) {
357 if (m->control_pressed) { return 1; }
359 tree[i].pGroups = (mergeGroups(i));
360 tree[i].pcount = (mergeGcounts(i));
363 //cout << "assembleTree\t" << (B-A) / CLOCKS_PER_SEC << endl;
366 catch(exception& e) {
367 m->errorOut(e, "Tree", "assembleTree");
371 /*****************************************************************/
372 //assumes leaf node names are in groups and no names file - used by indicator command
373 void Tree::getSubTree(Tree* Ctree, vector<string> Groups) {
376 //copy Tree since we are going to destroy it
377 Tree* copy = new Tree(tmap);
378 copy->getCopy(Ctree);
379 map<string, string> empty;
380 copy->assembleTree(empty);
382 //we want to select some of the leaf nodes to create the output tree
383 //go through the input Tree starting at parents of leaves
384 for (int i = 0; i < numNodes; i++) {
386 //initialize leaf nodes
387 if (i <= (numLeaves-1)) {
388 tree[i].setName(Groups[i]);
391 string group = tmap->getGroup(Groups[i]);
392 vector<string> tempGroups; tempGroups.push_back(group);
393 tree[i].setGroup(tempGroups);
394 groupNodeInfo[group].push_back(i);
396 //set pcount and pGroup for groupname to 1.
397 tree[i].pcount[group] = 1;
398 tree[i].pGroups[group] = 1;
400 //Treemap knows name, group and index to speed up search
401 tmap->setIndex(Groups[i], i);
403 //intialize non leaf nodes
404 }else if (i > (numLeaves-1)) {
406 vector<string> tempGroups;
407 tree[i].setGroup(tempGroups);
411 set<int> removedLeaves;
412 for (int i = 0; i < copy->getNumLeaves(); i++) {
414 if (removedLeaves.count(i) == 0) {
417 int parent = copy->tree[i].getParent();
421 if (m->inUsersGroups(copy->tree[i].getName(), Groups)) {
422 //find my siblings name
423 int parentRC = copy->tree[parent].getRChild();
424 int parentLC = copy->tree[parent].getLChild();
426 //if I am the right child, then my sib is the left child
427 int sibIndex = parentRC;
428 if (parentRC == i) { sibIndex = parentLC; }
430 string sibsName = copy->tree[sibIndex].getName();
432 //if yes, is my sibling
433 if ((m->inUsersGroups(sibsName, Groups)) || (sibsName == "")) {
434 //we both are okay no trimming required
436 //i am, my sib is not, so remove sib by setting my parent to my grandparent
437 int grandparent = copy->tree[parent].getParent();
438 int grandparentLC = copy->tree[grandparent].getLChild();
439 int grandparentRC = copy->tree[grandparent].getRChild();
441 //whichever of my granparents children was my parent now equals me
442 if (grandparentLC == parent) { grandparentLC = i; }
443 else { grandparentRC = i; }
445 copy->tree[i].setParent(grandparent);
446 copy->tree[i].setBranchLength((copy->tree[i].getBranchLength()+copy->tree[parent].getBranchLength()));
447 if (grandparent != -1) {
448 copy->tree[grandparent].setChildren(grandparentLC, grandparentRC);
450 removedLeaves.insert(sibIndex);
453 //find my siblings name
454 int parentRC = copy->tree[parent].getRChild();
455 int parentLC = copy->tree[parent].getLChild();
457 //if I am the right child, then my sib is the left child
458 int sibIndex = parentRC;
459 if (parentRC == i) { sibIndex = parentLC; }
461 string sibsName = copy->tree[sibIndex].getName();
463 //if no is my sibling
464 if ((m->inUsersGroups(sibsName, Groups)) || (sibsName == "")) {
465 //i am not, but my sib is
466 int grandparent = copy->tree[parent].getParent();
467 int grandparentLC = copy->tree[grandparent].getLChild();
468 int grandparentRC = copy->tree[grandparent].getRChild();
470 //whichever of my granparents children was my parent now equals my sib
471 if (grandparentLC == parent) { grandparentLC = sibIndex; }
472 else { grandparentRC = sibIndex; }
474 copy->tree[sibIndex].setParent(grandparent);
475 copy->tree[sibIndex].setBranchLength((copy->tree[sibIndex].getBranchLength()+copy->tree[parent].getBranchLength()));
476 if (grandparent != -1) {
477 copy->tree[grandparent].setChildren(grandparentLC, grandparentRC);
479 removedLeaves.insert(i);
481 //neither of us are, so we want to eliminate ourselves and our parent
482 //so set our parents sib to our great-grandparent
483 int parent = copy->tree[i].getParent();
484 int grandparent = copy->tree[parent].getParent();
486 if (grandparent != -1) {
487 int greatgrandparent = copy->tree[grandparent].getParent();
488 int greatgrandparentLC, greatgrandparentRC;
489 if (greatgrandparent != -1) {
490 greatgrandparentLC = copy->tree[greatgrandparent].getLChild();
491 greatgrandparentRC = copy->tree[greatgrandparent].getRChild();
494 int grandparentLC = copy->tree[grandparent].getLChild();
495 int grandparentRC = copy->tree[grandparent].getRChild();
497 parentsSibIndex = grandparentLC;
498 if (grandparentLC == parent) { parentsSibIndex = grandparentRC; }
500 //whichever of my greatgrandparents children was my grandparent
501 if (greatgrandparentLC == grandparent) { greatgrandparentLC = parentsSibIndex; }
502 else { greatgrandparentRC = parentsSibIndex; }
504 copy->tree[parentsSibIndex].setParent(greatgrandparent);
505 copy->tree[parentsSibIndex].setBranchLength((copy->tree[parentsSibIndex].getBranchLength()+copy->tree[grandparent].getBranchLength()));
506 if (greatgrandparent != -1) {
507 copy->tree[greatgrandparent].setChildren(greatgrandparentLC, greatgrandparentRC);
510 copy->tree[parent].setParent(-1);
511 //cout << "issues with making subtree" << endl;
513 removedLeaves.insert(sibIndex);
514 removedLeaves.insert(i);
522 for (int i = 0; i < copy->getNumNodes(); i++) {
524 if (copy->tree[i].getParent() == -1) { root = i; break; }
527 int nextSpot = numLeaves;
528 populateNewTree(copy->tree, root, nextSpot);
532 catch(exception& e) {
533 m->errorOut(e, "Tree", "getSubTree");
537 /*****************************************************************/
538 //assumes nameMap contains unique names as key or is empty.
539 //assumes numLeaves defined in tree constructor equals size of seqsToInclude and seqsToInclude only contains unique seqs.
540 int Tree::getSubTree(Tree* copy, vector<string> seqsToInclude, map<string, string> nameMap) {
543 if (numLeaves != seqsToInclude.size()) { m->mothurOut("[ERROR]: numLeaves does not equal numUniques, cannot create subtree.\n"); m->control_pressed = true; return 0; }
545 getSubTree(copy, seqsToInclude);
546 if (nameMap.size() != 0) { addNamesToCounts(nameMap); }
548 //build the pGroups in non leaf nodes to be used in the parsimony calcs.
549 for (int i = numLeaves; i < numNodes; i++) {
550 if (m->control_pressed) { return 1; }
552 tree[i].pGroups = (mergeGroups(i));
553 tree[i].pcount = (mergeGcounts(i));
558 catch(exception& e) {
559 m->errorOut(e, "Tree", "getSubTree");
563 /*****************************************************************/
564 int Tree::populateNewTree(vector<Node>& oldtree, int node, int& index) {
567 if (oldtree[node].getLChild() != -1) {
568 int rc = populateNewTree(oldtree, oldtree[node].getLChild(), index);
569 int lc = populateNewTree(oldtree, oldtree[node].getRChild(), index);
571 tree[index].setChildren(lc, rc);
572 tree[rc].setParent(index);
573 tree[lc].setParent(index);
575 tree[index].setBranchLength(oldtree[node].getBranchLength());
576 tree[rc].setBranchLength(oldtree[oldtree[node].getLChild()].getBranchLength());
577 tree[lc].setBranchLength(oldtree[oldtree[node].getRChild()].getBranchLength());
580 }else { //you are a leaf
581 int indexInNewTree = tmap->getIndex(oldtree[node].getName());
582 return indexInNewTree;
585 catch(exception& e) {
586 m->errorOut(e, "Tree", "populateNewTree");
590 /*****************************************************************/
591 void Tree::getCopy(Tree* copy, map<string, string> nameMap) {
594 //for each node in the tree copy its info
595 for (int i = 0; i < numNodes; i++) {
597 tree[i].setBranchLength(copy->tree[i].getBranchLength());
600 tree[i].setParent(copy->tree[i].getParent());
603 tree[i].setChildren(copy->tree[i].getLChild(), copy->tree[i].getRChild());
606 if (nameMap.size() != 0) { addNamesToCounts(nameMap); }
608 //build the pGroups in non leaf nodes to be used in the parsimony calcs.
609 for (int i = numLeaves; i < numNodes; i++) {
610 if (m->control_pressed) { break; }
612 tree[i].pGroups = (mergeGroups(i));
613 tree[i].pcount = (mergeGcounts(i));
616 catch(exception& e) {
617 m->errorOut(e, "Tree", "getCopy");
621 /*****************************************************************/
622 void Tree::getCopy(Tree* copy) {
625 //for each node in the tree copy its info
626 for (int i = 0; i < numNodes; i++) {
628 tree[i].setName(copy->tree[i].getName());
631 tree[i].setGroup(copy->tree[i].getGroup());
634 tree[i].setBranchLength(copy->tree[i].getBranchLength());
637 tree[i].setParent(copy->tree[i].getParent());
640 tree[i].setChildren(copy->tree[i].getLChild(), copy->tree[i].getRChild());
642 //copy index in node and tmap
643 tree[i].setIndex(copy->tree[i].getIndex());
644 setIndex(copy->tree[i].getName(), getIndex(copy->tree[i].getName()));
647 tree[i].pGroups = copy->tree[i].pGroups;
650 tree[i].pcount = copy->tree[i].pcount;
653 groupNodeInfo = copy->groupNodeInfo;
656 catch(exception& e) {
657 m->errorOut(e, "Tree", "getCopy");
661 /*****************************************************************/
662 //returns a map with a groupname and the number of times that group was seen in the children
663 //for instance if your children are white and black then it would return a map with 2 entries
664 // p[white] = 1 and p[black] = 1. Now go up a level and merge that with a node who has p[white] = 1
665 //and you get p[white] = 2, p[black] = 1, but you erase the p[black] because you have a p value higher than 1.
667 map<string, int> Tree::mergeGroups(int i) {
669 int lc = tree[i].getLChild();
670 int rc = tree[i].getRChild();
672 //set parsimony groups to left child
673 map<string,int> parsimony = tree[lc].pGroups;
677 //look at right child groups and update maxPars if right child has something higher for that group.
678 for(it=tree[rc].pGroups.begin();it!=tree[rc].pGroups.end();it++){
679 it2 = parsimony.find(it->first);
680 if (it2 != parsimony.end()) {
681 parsimony[it->first]++;
683 parsimony[it->first] = 1;
686 if(parsimony[it->first] > maxPars){
687 maxPars = parsimony[it->first];
691 // this is true if right child had a greater parsimony for a certain group
693 //erase all the groups that are only 1 because you found something with 2.
694 for(it=parsimony.begin();it!=parsimony.end();){
696 parsimony.erase(it++);
699 //set one remaining groups to 1
700 //so with our above example p[white] = 2 would be left and it would become p[white] = 1
701 for(it=parsimony.begin();it!=parsimony.end();it++){
702 parsimony[it->first] = 1;
709 catch(exception& e) {
710 m->errorOut(e, "Tree", "mergeGroups");
714 /*****************************************************************/
715 //returns a map with a groupname and the number of times that group was seen in the children
716 //for instance if your children are white and black then it would return a map with 2 entries
717 // p[white] = 1 and p[black] = 1. Now go up a level and merge that with a node who has p[white] = 1
718 //and you get p[white] = 2, p[black] = 1, but you erase the p[black] because you have a p value higher than 1.
720 map<string, int> Tree::mergeUserGroups(int i, vector<string> g) {
723 int lc = tree[i].getLChild();
724 int rc = tree[i].getRChild();
726 //loop through nodes groups removing the ones the user doesn't want
727 for(it=tree[lc].pGroups.begin();it!=tree[lc].pGroups.end();){
728 if (m->inUsersGroups(it->first, g) != true) {
729 tree[lc].pGroups.erase(it++);
733 //loop through nodes groups removing the ones the user doesn't want
734 for(it=tree[rc].pGroups.begin();it!=tree[rc].pGroups.end();){
735 if (m->inUsersGroups(it->first, g) != true) {
736 tree[rc].pGroups.erase(it++);
740 //set parsimony groups to left child
741 map<string,int> parsimony = tree[lc].pGroups;
745 //look at right child groups and update maxPars if right child has something higher for that group.
746 for(it=tree[rc].pGroups.begin();it!=tree[rc].pGroups.end();it++){
747 it2 = parsimony.find(it->first);
748 if (it2 != parsimony.end()) {
749 parsimony[it->first]++;
751 parsimony[it->first] = 1;
754 if(parsimony[it->first] > maxPars){
755 maxPars = parsimony[it->first];
759 // this is true if right child had a greater parsimony for a certain group
761 //erase all the groups that are only 1 because you found something with 2.
762 for(it=parsimony.begin();it!=parsimony.end();){
764 parsimony.erase(it++);
768 for(it=parsimony.begin();it!=parsimony.end();it++){
769 parsimony[it->first] = 1;
775 catch(exception& e) {
776 m->errorOut(e, "Tree", "mergeUserGroups");
782 /**************************************************************************************************/
784 map<string,int> Tree::mergeGcounts(int position) {
786 map<string,int>::iterator pos;
788 int lc = tree[position].getLChild();
789 int rc = tree[position].getRChild();
791 map<string,int> sum = tree[lc].pcount;
793 for(it=tree[rc].pcount.begin();it!=tree[rc].pcount.end();it++){
794 sum[it->first] += it->second;
798 catch(exception& e) {
799 m->errorOut(e, "Tree", "mergeGcounts");
803 /**************************************************************************************************/
804 void Tree::randomLabels(vector<string> g) {
807 //initialize groupNodeInfo
808 for (int i = 0; i < (tmap->getNamesOfGroups()).size(); i++) {
809 groupNodeInfo[(tmap->getNamesOfGroups())[i]].resize(0);
812 for(int i = 0; i < numLeaves; i++){
814 //get random index to switch with
815 z = int((float)(i+1) * (float)(rand()) / ((float)RAND_MAX+1.0));
817 //you only want to randomize the nodes that are from a group the user wants analyzed, so
818 //if either of the leaf nodes you are about to switch are not in the users groups then you don't want to switch them.
821 treez = m->inUsersGroups(tree[z].getGroup(), g);
822 treei = m->inUsersGroups(tree[i].getGroup(), g);
824 if ((treez == true) && (treei == true)) {
825 //switches node i and node z's info.
826 map<string,int> lib_hold = tree[z].pGroups;
827 tree[z].pGroups = (tree[i].pGroups);
828 tree[i].pGroups = (lib_hold);
830 vector<string> zgroup = tree[z].getGroup();
831 tree[z].setGroup(tree[i].getGroup());
832 tree[i].setGroup(zgroup);
834 string zname = tree[z].getName();
835 tree[z].setName(tree[i].getName());
836 tree[i].setName(zname);
838 map<string,int> gcount_hold = tree[z].pcount;
839 tree[z].pcount = (tree[i].pcount);
840 tree[i].pcount = (gcount_hold);
843 for (int k = 0; k < (tree[i].getGroup()).size(); k++) { groupNodeInfo[(tree[i].getGroup())[k]].push_back(i); }
844 for (int k = 0; k < (tree[z].getGroup()).size(); k++) { groupNodeInfo[(tree[z].getGroup())[k]].push_back(z); }
847 catch(exception& e) {
848 m->errorOut(e, "Tree", "randomLabels");
852 /**************************************************************************************************/
853 void Tree::randomBlengths() {
855 for(int i=numNodes-1;i>=0;i--){
856 int z = int((float)(i+1) * (float)(rand()) / ((float)RAND_MAX+1.0));
858 float bl_hold = tree[z].getBranchLength();
859 tree[z].setBranchLength(tree[i].getBranchLength());
860 tree[i].setBranchLength(bl_hold);
863 catch(exception& e) {
864 m->errorOut(e, "Tree", "randomBlengths");
868 /*************************************************************************************************/
869 void Tree::assembleRandomUnifracTree(vector<string> g) {
871 map<string, string> empty;
874 /*************************************************************************************************/
875 void Tree::assembleRandomUnifracTree(string groupA, string groupB) {
876 vector<string> temp; temp.push_back(groupA); temp.push_back(groupB);
878 map<string, string> empty;
882 /*************************************************************************************************/
883 //for now it's just random topology but may become random labels as well later that why this is such a simple function now...
884 void Tree::assembleRandomTree() {
886 map<string, string> empty;
889 /**************************************************************************************************/
891 void Tree::randomTopology() {
893 for(int i=0;i<numNodes;i++){
894 tree[i].setParent(-1);
896 for(int i=numLeaves;i<numNodes;i++){
897 tree[i].setChildren(-1, -1);
900 for(int i=numLeaves;i<numNodes;i++){
902 int rnd_index1, rnd_index2;
904 rnd_index1 = (int)(((double)rand() / (double) RAND_MAX)*i);
905 if(tree[rnd_index1].getParent() == -1){escape = 1;}
910 rnd_index2 = (int)(((double)rand() / (double) RAND_MAX)*i);
911 if(rnd_index2 != rnd_index1 && tree[rnd_index2].getParent() == -1){
916 tree[i].setChildren(rnd_index1,rnd_index2);
917 tree[i].setParent(-1);
918 tree[rnd_index1].setParent(i);
919 tree[rnd_index2].setParent(i);
922 catch(exception& e) {
923 m->errorOut(e, "Tree", "randomTopology");
927 /*****************************************************************/
928 void Tree::print(ostream& out) {
930 int root = findRoot();
931 printBranch(root, out, "branch");
934 catch(exception& e) {
935 m->errorOut(e, "Tree", "print");
939 /*****************************************************************/
940 void Tree::print(ostream& out, map<string, string> nameMap) {
942 int root = findRoot();
943 printBranch(root, out, nameMap);
946 catch(exception& e) {
947 m->errorOut(e, "Tree", "print");
951 /*****************************************************************/
952 void Tree::print(ostream& out, string mode) {
954 int root = findRoot();
955 printBranch(root, out, mode);
958 catch(exception& e) {
959 m->errorOut(e, "Tree", "print");
963 /*****************************************************************/
964 // This prints out the tree in Newick form.
965 void Tree::createNewickFile(string f) {
967 int root = findRoot();
971 m->openOutputFile(filename, out);
973 printBranch(root, out, "branch");
975 // you are at the end of the tree
979 catch(exception& e) {
980 m->errorOut(e, "Tree", "createNewickFile");
985 /*****************************************************************/
986 //This function finds the index of the root node.
988 int Tree::findRoot() {
990 for (int i = 0; i < numNodes; i++) {
992 if (tree[i].getParent() == -1) { return i; }
993 //cout << "i = " << i << endl;
994 //cout << "i's parent = " << tree[i].getParent() << endl;
998 catch(exception& e) {
999 m->errorOut(e, "Tree", "findRoot");
1003 /*****************************************************************/
1004 void Tree::printBranch(int node, ostream& out, map<string, string> names) {
1007 // you are not a leaf
1008 if (tree[node].getLChild() != -1) {
1010 printBranch(tree[node].getLChild(), out, names);
1012 printBranch(tree[node].getRChild(), out, names);
1015 //if there is a branch length then print it
1016 if (tree[node].getBranchLength() != -1) {
1017 out << ":" << tree[node].getBranchLength();
1020 }else { //you are a leaf
1021 map<string, string>::iterator itNames = names.find(tree[node].getName());
1023 string outputString = "";
1024 if (itNames != names.end()) {
1026 vector<string> dupNames;
1027 m->splitAtComma((itNames->second), dupNames);
1029 if (dupNames.size() == 1) {
1030 outputString += tree[node].getName();
1031 if (tree[node].getBranchLength() != -1) {
1032 outputString += ":" + toString(tree[node].getBranchLength());
1035 outputString += "(";
1037 for (int u = 0; u < dupNames.size()-1; u++) {
1038 outputString += dupNames[u];
1040 if (tree[node].getBranchLength() != -1) {
1041 outputString += ":" + toString(0.0);
1043 outputString += ",";
1046 outputString += dupNames[dupNames.size()-1];
1047 if (tree[node].getBranchLength() != -1) {
1048 outputString += ":" + toString(0.0);
1051 outputString += ")";
1052 if (tree[node].getBranchLength() != -1) {
1053 outputString += ":" + toString(tree[node].getBranchLength());
1057 outputString = tree[node].getName();
1058 //if there is a branch length then print it
1059 if (tree[node].getBranchLength() != -1) {
1060 outputString += ":" + toString(tree[node].getBranchLength());
1063 m->mothurOut("[ERROR]: " + tree[node].getName() + " is not in your namefile, please correct."); m->mothurOutEndLine();
1066 out << outputString;
1070 catch(exception& e) {
1071 m->errorOut(e, "Tree", "printBranch");
1075 /*****************************************************************/
1076 void Tree::printBranch(int node, ostream& out, string mode) {
1079 // you are not a leaf
1080 if (tree[node].getLChild() != -1) {
1082 printBranch(tree[node].getLChild(), out, mode);
1084 printBranch(tree[node].getRChild(), out, mode);
1086 if (mode == "branch") {
1087 //if there is a branch length then print it
1088 if (tree[node].getBranchLength() != -1) {
1089 out << ":" << tree[node].getBranchLength();
1091 }else if (mode == "boot") {
1092 //if there is a label then print it
1093 if (tree[node].getLabel() != -1) {
1094 out << tree[node].getLabel();
1096 }else if (mode == "both") {
1097 if (tree[node].getLabel() != -1) {
1098 out << tree[node].getLabel();
1100 //if there is a branch length then print it
1101 if (tree[node].getBranchLength() != -1) {
1102 out << ":" << tree[node].getBranchLength();
1105 }else { //you are a leaf
1106 string leafGroup = tmap->getGroup(tree[node].getName());
1108 if (mode == "branch") {
1110 //if there is a branch length then print it
1111 if (tree[node].getBranchLength() != -1) {
1112 out << ":" << tree[node].getBranchLength();
1114 }else if (mode == "boot") {
1116 //if there is a label then print it
1117 if (tree[node].getLabel() != -1) {
1118 out << tree[node].getLabel();
1120 }else if (mode == "both") {
1121 out << tree[node].getName();
1122 if (tree[node].getLabel() != -1) {
1123 out << tree[node].getLabel();
1125 //if there is a branch length then print it
1126 if (tree[node].getBranchLength() != -1) {
1127 out << ":" << tree[node].getBranchLength();
1133 catch(exception& e) {
1134 m->errorOut(e, "Tree", "printBranch");
1138 /*****************************************************************/
1139 void Tree::printBranch(int node, ostream& out, string mode, vector<Node>& theseNodes) {
1142 // you are not a leaf
1143 if (theseNodes[node].getLChild() != -1) {
1145 printBranch(theseNodes[node].getLChild(), out, mode);
1147 printBranch(theseNodes[node].getRChild(), out, mode);
1149 if (mode == "branch") {
1150 //if there is a branch length then print it
1151 if (theseNodes[node].getBranchLength() != -1) {
1152 out << ":" << theseNodes[node].getBranchLength();
1154 }else if (mode == "boot") {
1155 //if there is a label then print it
1156 if (theseNodes[node].getLabel() != -1) {
1157 out << theseNodes[node].getLabel();
1159 }else if (mode == "both") {
1160 if (theseNodes[node].getLabel() != -1) {
1161 out << theseNodes[node].getLabel();
1163 //if there is a branch length then print it
1164 if (theseNodes[node].getBranchLength() != -1) {
1165 out << ":" << theseNodes[node].getBranchLength();
1168 }else { //you are a leaf
1169 string leafGroup = tmap->getGroup(theseNodes[node].getName());
1171 if (mode == "branch") {
1173 //if there is a branch length then print it
1174 if (theseNodes[node].getBranchLength() != -1) {
1175 out << ":" << theseNodes[node].getBranchLength();
1177 }else if (mode == "boot") {
1179 //if there is a label then print it
1180 if (theseNodes[node].getLabel() != -1) {
1181 out << theseNodes[node].getLabel();
1183 }else if (mode == "both") {
1184 out << theseNodes[node].getName();
1185 if (theseNodes[node].getLabel() != -1) {
1186 out << theseNodes[node].getLabel();
1188 //if there is a branch length then print it
1189 if (theseNodes[node].getBranchLength() != -1) {
1190 out << ":" << theseNodes[node].getBranchLength();
1196 catch(exception& e) {
1197 m->errorOut(e, "Tree", "printBranch");
1201 /*****************************************************************/
1203 void Tree::printTree() {
1205 for(int i=0;i<numNodes;i++){
1207 tree[i].printNode();
1212 /*****************************************************************/
1213 //this code is a mess and should be rethought...-slw
1214 void Tree::parseTreeFile() {
1216 //only takes names from the first tree and assumes that all trees use the same names.
1218 string filename = m->getTreeFile();
1219 ifstream filehandle;
1220 m->openInputFile(filename, filehandle);
1225 //ifyou are not a nexus file
1226 if((c = filehandle.peek()) != '#') {
1227 while((c = filehandle.peek()) != ';') {
1228 while ((c = filehandle.peek()) != ';') {
1229 // get past comments
1236 if((c == '(') && (comment != 1)){ break; }
1240 done = readTreeString(filehandle);
1241 if (done == 0) { break; }
1243 //ifyou are a nexus file
1244 }else if((c = filehandle.peek()) == '#') {
1247 // get past comments
1248 while(holder != "translate" && holder != "Translate"){
1249 if(holder == "[" || holder == "[!"){
1255 filehandle >> holder;
1257 //if there is no translate then you must read tree string otherwise use translate to get names
1258 if((holder == "tree") && (comment != 1)){
1259 //pass over the "tree rep.6878900 = "
1260 while (((c = filehandle.get()) != '(') && ((c = filehandle.peek()) != EOF)) {;}
1262 if(c == EOF) { break; }
1263 filehandle.putback(c); //put back first ( of tree.
1264 done = readTreeString(filehandle);
1269 if (done == 0) { break; }
1272 //use nexus translation rather than parsing tree to save time
1273 if((holder == "translate") || (holder == "Translate")) {
1275 string number, name, h;
1276 h = ""; // so it enters the loop the first time
1277 while((h != ";") && (number != ";")) {
1278 filehandle >> number;
1281 //c = , until done with translation then c = ;
1282 h = name.substr(name.length()-1, name.length());
1283 name.erase(name.end()-1); //erase the comma
1284 m->Treenames.push_back(number);
1286 if(number == ";") { m->Treenames.pop_back(); } //in case ';' from translation is on next line instead of next to last name
1291 //for (int i = 0; i < globaldata->Treenames.size(); i++) {
1292 //cout << globaldata->Treenames[i] << endl; }
1293 //cout << globaldata->Treenames.size() << endl;
1295 catch(exception& e) {
1296 m->errorOut(e, "Tree", "parseTreeFile");
1300 /*******************************************************/
1302 /*******************************************************/
1303 int Tree::readTreeString(ifstream& filehandle) {
1308 while((c = filehandle.peek()) != ';') {
1310 //cout << " at beginning of while " << k << endl;
1312 //to pass over labels in trees
1314 while((c!=',') && (c != -1) && (c!= ':') && (c!=';')){ c=filehandle.get(); }
1315 filehandle.putback(c);
1317 if(c == ';') { return 0; }
1318 if(c == -1) { return 0; }
1320 if((c != '(') && (c != ')') && (c != ',') && (c != ':') && (c != '\n') && (c != '\t') && (c != 32)) { //32 is space
1322 c = filehandle.get();
1324 //cout << k << endl;
1325 while ((c != '(') && (c != ')') && (c != ',') && (c != ':') && (c != '\n') && (c != 32) && (c != '\t')) {
1327 c = filehandle.get();
1329 //cout << " in name while " << k << endl;
1332 //cout << "name = " << name << endl;
1333 m->Treenames.push_back(name);
1334 filehandle.putback(c);
1336 //cout << " after putback" << k << endl;
1339 if(c == ':') { //read until you reach the end of the branch length
1340 while ((c != '(') && (c != ')') && (c != ',') && (c != ';') && (c != '\n') && (c != '\t') && (c != 32)) {
1341 c = filehandle.get();
1343 //cout << " in branch while " << k << endl;
1345 filehandle.putback(c);
1348 c = filehandle.get();
1350 //cout << " here after get " << k << endl;
1351 if(c == ';') { return 0; }
1352 if(c == ')') { filehandle.putback(c); }
1354 //cout << k << endl;
1359 catch(exception& e) {
1360 m->errorOut(e, "Tree", "readTreeString");
1365 /*******************************************************/
1367 /*******************************************************/