rm(list=ls())
library(ape)
library(phytools)
## 載入需要的套件:maps
library(RRphylo)
## 載入需要的套件:emmeans
## 
## 載入套件:'RRphylo'
## 下列物件被遮斷自 'package:phytools':
## 
##     node.paths
library(TreeTools)
## 
## 載入套件:'TreeTools'
## 下列物件被遮斷自 'package:phytools':
## 
##     as.multiPhylo
library(TreeSim)
## 載入需要的套件:geiger
## 
## 載入套件:'geiger'
## 下列物件被遮斷自 'package:RRphylo':
## 
##     tips
size=32

# tree<-BalancedTree(size)
# tree<-compute.brlen(tree)

# tree<-rcoal(size)

#tree<-pbtree(n=size,scale=1)

tree<-sim.bd.taxa(n=size,numbsim=1,lambda=0.58,mu=0.22,complete = FALSE, stochsampling = TRUE)[[1]]


gratiset<-(length(tree$tip.label)+2):(2*length(tree$tip.label)-1)
gratiset  
##  [1] 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
## [26] 59 60 61 62 63
## A 
## RRphylo: fix.poly 
# https://cran.r-project.org/web/packages/RRphylo/vignettes/Tree-Manipulation.html

par(mfrow=c(1,3))
par(mar=c(1,1,1,1))
plot(tree,show.tip.label=F, main="Raw Tree")
#nodelabels()
for(colIndex in c(1)){# 1:8){#(length(gratiset) - floor(size/1.2))){
# colIndex<-3
  colanode<-gratiset[colIndex]
  colanode
  tree.col<-fix.poly(tree,type="collapse",node=colanode)
  plot(tree.col,show.tip.label=F,main="Polytomy on Clade")
  #nodelabels()
}

## B
## TreeTools: CollapseNode 
# tony you can make the root(star phylogeny), root +1, root +2 , root +3 
# https://rdrr.io/cran/TreeTools/man/NDescendants.html
# NDescendants() counts the number of nodes (including leaves) directly descended from each node in a tree.

#??CollapseNode
#tree<-BalancedTree(16)
#tree<-compute.brlen(tree)
#par(mfrow=c(3,3))
#par(mar=c(1,1,1,1))
#plot(tree,show.tip.label=F)
#nodelabels()
for(colIndex in c(8)){# 1:8){#(length(gratiset) - floor(size/1.2))){
  # colIndex<-3
  colanode<-gratiset[colIndex]
  colanode
  tree.col<-CollapseNode(tree, gratiset[1:(2*colIndex)])
  plot(tree.col,show.tip.label=F, main="Polytomy at Root")
  #nodelabels()
}

#NDescendants(tree.col)
#nodelabels(NDescendants(tree.col))