/archive/source.archive/bm.only/trait.rjmcmc.11172010.R

http://github.com/eastman/auteur · R · 742 lines · 623 code · 83 blank · 36 comment · 113 complexity · 8559d1d1884098c4610b656a2f5f2cf4 MD5 · raw file

  1. ## Written by LJ HARMON (2008), AL HIPP (2008), and JM EASTMAN (2010)
  2. rjMCMC.trait<-function (phy, data, ngen=1000, sampleFreq=100, probMergeSplit=0.05, probRoot=0.01, lambdaK=log(2), constrainK=FALSE, jumpsize=2, fileBase="result", simplestart=FALSE)
  3. {
  4. model="BM"
  5. heat=1
  6. # require(ouch)
  7. require(geiger)
  8. ### prepare data for rjMCMC
  9. cur.model <- model
  10. dataList <- prepare.data(phy, data)
  11. ape.tre <- cur.tre <- dataList$ape.tre
  12. orig.dat <- dataList$orig.dat
  13. nn <- length(ape.tre$edge.length)
  14. node.des <- sapply(unique(c(ape.tre$edge[1,1],ape.tre$edge[,2])), function(x) get.descendants.of.node(x, ape.tre))
  15. names(node.des) <- c(ape.tre$edge[1,1], unique(ape.tre$edge[,2]))
  16. subtrees <- subtrees(phy)
  17. subtrees.marker <- sapply(subtrees, function(x) return(min(x$node.label)))
  18. # initialize parameters
  19. if(is.numeric(constrainK) & (constrainK > length(ape.tre$edge) | constrainK < 1)) stop("Constraint on rate shifts is nonsensical. Ensure that constrainK is at least 1 and less than the number of available nodes in the tree.")
  20. if(simplestart | is.numeric(constrainK) ) {
  21. if(is.numeric(constrainK)) {
  22. init.rate <- generate.starting.point(data, ape.tre, node.des, theta=FALSE, K=constrainK, jumpsize=jumpsize)
  23. } else {
  24. init.rate <- list(values=rep(fitContinuous(phy,data)$Trait1$beta,length(phy$edge.length)),delta=rep(0,length(phy$edge.length)))
  25. }
  26. } else {
  27. init.rate <- generate.starting.point(data, ape.tre, node.des, theta=FALSE, K=constrainK, jumpsize=jumpsize )
  28. }
  29. cur.rates <- init.rate$values
  30. cur.delta.rates <- init.rate$delta
  31. cur.root <- adjust.value(mean(orig.dat), jumpsize)
  32. cur.tre <- apply.BMM.to.apetree(ape.tre, cur.rates)
  33. mod.cur = new.bm.lik.fn(cur.rates, cur.root, cur.tre, orig.dat)
  34. # proposal counts
  35. nRateProp = 0
  36. nRateSwapProp = 0
  37. nRcatProp = 0
  38. nRootProp = 0
  39. nRateOK = 0
  40. nRateSwapOK = 0
  41. nRcatOK = 0
  42. nRootOK = 0
  43. cOK=c(
  44. nRateOK,
  45. nRateSwapOK,
  46. nRcatOK,
  47. nRootOK
  48. )
  49. tickerFreq=ceiling(ngen/30)
  50. # file handling
  51. parmBase=paste(model, fileBase, "parameters/",sep=".")
  52. if(!file.exists(parmBase)) dir.create(parmBase)
  53. parlogger(model=model, init=TRUE, node.des, parmBase=parmBase)
  54. errorLog=file(paste(parmBase,paste(cur.model, fileBase, "rjTraitErrors.log",sep="."),sep="/"),open='w+')
  55. generate.error.message(i=NULL, mod.cur=NULL, mod.new=NULL, lnR=NULL, errorLog=errorLog, init=TRUE)
  56. runLog=file(paste(parmBase,paste(cur.model, fileBase, "rjTrait.log",sep="."),sep="/"),open='w+')
  57. generate.log(bundled.parms=NULL, cur.model, file=runLog, init=TRUE)
  58. ### Begin rjMCMC
  59. for (i in 1:ngen) {
  60. lnLikelihoodRatio <- lnHastingsRatio <- lnPriorRatio <- 0
  61. startparms = c(nRateProp, nRateSwapProp, nRcatProp, nRootProp)
  62. ## BM IMPLEMENTATION ##
  63. while(1) {
  64. if (runif(1) < (2 * probMergeSplit) & !constrainK) { # adjust rate categories
  65. nr=split.or.merge(cur.delta.rates, cur.rates, ape.tre, node.des, lambdaK)
  66. new.rates=nr$new.values
  67. new.delta.rates=nr$new.delta
  68. new.root=cur.root
  69. nRcatProp=nRcatProp+1
  70. lnHastingsRatio=nr$lnHastingsRatio
  71. lnPriorRatio=nr$lnPriorRatio
  72. break()
  73. } else {
  74. if(runif(1)<probRoot) { # adjust root
  75. new.root=adjust.value(cur.root, jumpsize)
  76. new.rates=cur.rates
  77. new.delta.rates=cur.delta.rates
  78. nRootProp=nRootProp+1
  79. break()
  80. } else {
  81. if(runif(1)>0.1 & length(unique(cur.rates))>1) { # swap rates classes
  82. nr=switcheroo(cur.rates)
  83. new.rates=nr$new.values ##
  84. new.delta.rates=cur.delta.rates
  85. new.root=cur.root
  86. nRateSwapProp=nRateSwapProp+1
  87. break()
  88. } else { # adjust rates
  89. new.rates=adjust.rate(cur.rates, jumpsize)
  90. new.delta.rates=cur.delta.rates
  91. new.root=cur.root
  92. nRateProp=nRateProp+1
  93. break()
  94. }
  95. }
  96. }
  97. }
  98. new.tre=apply.BMM.to.apetree(ape.tre, new.rates)
  99. mod.new=try(new.bm.lik.fn(new.rates, new.root, new.tre, orig.dat),silent=TRUE)
  100. if(inherits(mod.new, "try-error")) {mod.new=as.list(mod.new); mod.new$lnL=Inf}
  101. if(!is.infinite(mod.new$lnL)) {
  102. lnLikelihoodRatio = mod.new$lnL - mod.cur$lnL
  103. } else {
  104. lnLikelihoodRatio = -Inf
  105. failures=paste("./failed", model, "parameters/",sep=".")
  106. failed.trees=paste(failures, "trees", sep="/")
  107. failed.plots=paste(failures, "pdf", sep="/")
  108. lapply(list(failures, failed.trees, failed.plots), function(x) if(!file.exists(x)) dir.create(x))
  109. pdf(file=paste(failed.plots, paste(i,fileBase,"failed.model.pdf",sep="."),sep="/"))
  110. plot(new.tre, tip=FALSE)
  111. dev.off()
  112. write.tree(new.tre, file=paste(failed.trees, paste(i,fileBase,"tre",sep="."),sep="/"))
  113. write.table(matrix(c(i, new.rates),nrow=1),file=paste(failures,"failed.rates.txt",sep="/"),append=TRUE,col=FALSE,row=FALSE,quote=FALSE)
  114. write.table(matrix(c(i, new.root),nrow=1),file=paste(failures,"failed.root.txt",sep="/"),append=TRUE,col=FALSE,row=FALSE,quote=FALSE)
  115. }
  116. # compare likelihoods
  117. endparms = c(nRateProp=nRateProp, nRateSwapProp=nRateSwapProp, nRcatProp=nRcatProp, nRootProp=nRootProp)
  118. r=assess.lnR((heat * lnLikelihoodRatio + heat * lnPriorRatio + lnHastingsRatio)->lnR)
  119. if (runif(1) <= r$r) { # adopt proposal
  120. decision="adopt"
  121. cur.root <- new.root
  122. cur.rates <- new.rates
  123. cur.delta.rates <- new.delta.rates
  124. curr.lnL <- mod.new$lnL
  125. cur.tre <- new.tre
  126. mod.cur <- mod.new
  127. cOK <- determine.accepted.proposal(startparms, endparms, cOK)
  128. } else { # deny proposal
  129. decision="reject"
  130. curr.lnL <- mod.cur$lnL
  131. }
  132. if(is.infinite(curr.lnL)) stop("starting point has exceptionally poor likelihood")
  133. if(r$error) generate.error.message(i, mod.cur, mod.new, lnR, errorLog)
  134. if(i%%tickerFreq==0) {
  135. if(i==tickerFreq) cat("|",rep(" ",9),toupper("generations complete"),rep(" ",9),"|","\n")
  136. cat(". ")
  137. }
  138. if(i%%sampleFreq==0) {
  139. bundled.parms=list(gen=i, mrate=exp(mean(log(cur.rates))), cats=sum(cur.delta.rates)+1, root=cur.root, lnL=curr.lnL)
  140. generate.log(bundled.parms, cur.model, file=runLog)
  141. parlogger(model=model, init=FALSE, node.des=node.des, i=i, curr.lnL=curr.lnL, cur.root=cur.root, cur.rates=cur.rates, cur.delta.rates=cur.delta.rates, parmBase=parmBase)
  142. }
  143. }
  144. # End rjMCMC
  145. close(errorLog)
  146. close(runLog)
  147. summarize.run(cOK, endparms, cur.model)
  148. }
  149. ## AUXILIARY FUNCTIONS
  150. new.bm.lik.fn <- function(rates, root, ape.tre, orig.dat) { # from LJ HARMON
  151. # mod 10.18.2010 JM Eastman: using determinant()$modulus rather than det() to stay in log-space
  152. tree=ape.tre
  153. y=orig.dat
  154. b <- vcv.phylo(ape.tre)
  155. w <- rep(root, nrow(b))
  156. num <- -t(y-w)%*%solve(b)%*%(y-w)/2
  157. den <- 0.5*(length(y)*log(2*pi) + as.numeric(determinant(b)$modulus))
  158. list(
  159. root=root,
  160. lnL = (num-den)[1,1]
  161. )
  162. }
  163. split.or.merge <- function(cur.delta, cur.values, phy, node.des, lambda=lambda) {
  164. # mod 11.17.2010 JM Eastman
  165. # cur.delta=cur.delta.rates; cur.values=cur.rates; theta=FALSE; lambda=log(2); jumpsize=2
  166. bb=cur.delta
  167. vv=cur.values
  168. names(vv)<-names(bb)<-phy$edge[,2]
  169. new.bb=choose.one(bb)
  170. new.vv=vv
  171. s=names(new.bb[bb!=new.bb])
  172. all.shifts=as.numeric(names(bb[bb>0]))
  173. all.D=node.des[[which(names(node.des)==s)]]
  174. if(length(all.D)!=0) {
  175. untouchable=unlist(lapply(all.shifts[all.shifts>s], function(x)node.des[[which(names(node.des)==x)]]))
  176. remain.unchanged=union(all.shifts, untouchable)
  177. } else {
  178. untouchable=NULL
  179. remain.unchanged=list()
  180. }
  181. marker=match(s, names(new.vv))
  182. nn=length(vv)
  183. K=sum(bb)+1
  184. N=Ntip(phy)
  185. ncat=sum(bb)
  186. cur.vv=as.numeric(vv[marker])
  187. ca.vv=length(which(vv==cur.vv))
  188. if(sum(new.bb)>sum(bb)) { # add transition: SPLIT
  189. # print("s")
  190. n.desc=sum(!all.D%in%remain.unchanged)+1
  191. n.split=sum(vv==cur.vv)-n.desc
  192. if(runif(1)<0.5) {
  193. u=runif(1,min=-0.5*n.desc*cur.vv, max=0.5*n.split*cur.vv)
  194. nr.desc=cur.vv + u/n.desc
  195. nr.split=cur.vv - u/n.split
  196. # (n.desc*nr.desc+n.split*nr.split)/(n.desc+n.split); nr.desc; nr.split
  197. } else {
  198. u=runif(1,min=-0.5*n.split*cur.vv, max=0.5*n.desc*cur.vv)
  199. nr.desc=cur.vv - u/n.desc
  200. nr.split=cur.vv + u/n.split
  201. # (n.desc*nr.desc+n.split*nr.split)/(n.desc+n.split); nr.desc; nr.split
  202. }
  203. new.vv[vv==cur.vv]=nr.split
  204. if(length(remain.unchanged)==0) { # assign new value to all descendants
  205. new.vv[match(all.D,names(new.vv))] = nr.desc
  206. } else { # assign new value to all 'open' descendants
  207. new.vv[match(all.D[!(all.D%in%remain.unchanged)],names(new.vv))] = nr.desc
  208. }
  209. new.vv[match(s, names(new.vv))]=nr.desc
  210. lnHastingsRatio = log((K+1)/(2*N-2-K)) ### from Drummond and Suchard 2010: where N is tips, K is number of local parms in tree
  211. lnPriorRatio = log(ptpois(K+1,lambda,nn)/ptpois(K,lambda,nn))
  212. } else { # drop transition: MERGE
  213. # print("m")
  214. anc = get.ancestor.of.node(s, phy)
  215. if(!is.root(anc, phy)) { # base new rate on ancestral rate of selected branch
  216. anc.vv=as.numeric(vv[match(anc,names(vv))])
  217. na.vv=length(which(vv==anc.vv))
  218. nr=(anc.vv*na.vv+cur.vv*ca.vv)/(ca.vv+na.vv)
  219. new.vv[vv==cur.vv | vv==anc.vv]=nr
  220. } else { # if ancestor of selected node is root, base new rate on sister node
  221. sister.tmp=get.desc.of.node(anc,phy)
  222. sister=sister.tmp[sister.tmp!=s]
  223. sis.vv=as.numeric(vv[match(sister,names(vv))])
  224. ns.vv=length(which(vv==sis.vv))
  225. nr=(sis.vv*ns.vv+cur.vv*ca.vv)/(ca.vv+ns.vv)
  226. new.vv[vv==cur.vv | vv==sis.vv]=nr
  227. }
  228. lnHastingsRatio = log((2*N-2-K+1)/K) ### from Drummond and Suchard 2010: where N is tips, K is number of local parms in tree
  229. lnPriorRatio = log(ptpois(K-1,lambda,nn)/ptpois(K,lambda,nn))
  230. }
  231. return(list(new.delta=new.bb, new.values=new.vv, lnHastingsRatio=lnHastingsRatio, lnPriorRatio=lnPriorRatio))
  232. }
  233. switcheroo <- function(cur.values) {
  234. # mod 11.17.2010 JM Eastman
  235. # cur.delta=cur.delta.rates; cur.values=cur.rates; theta=FALSE; lambda=log(2); jumpsize=2
  236. vv=cur.values
  237. rates.sample=unique(vv)[sample(1:length(unique(vv)), 2)]
  238. new.vv=vv
  239. new.vv[which(vv==rates.sample[1])]=rates.sample[2]
  240. new.vv[which(vv==rates.sample[2])]=rates.sample[1]
  241. return(list(new.values=new.vv))
  242. }
  243. generate.starting.point <- function(data, phy, node.des, theta=FALSE, K=FALSE, jumpsize) {
  244. # updated JME 11.14.2010
  245. nn=length(phy$edge.length)
  246. ntip=Ntip(phy)
  247. if(!K) nshifts=rtpois(1,log(ntip),nn) else nshifts=K-1
  248. if(nshifts!=0) bb=sample(c(rep(1,nshifts),rep(0,nn-nshifts)),replace=FALSE) else bb=rep(0,nn)
  249. names(bb)=phy$edge[,2]
  250. shifts=as.numeric(names(bb)[bb==1])
  251. if(theta) {
  252. min.max=c(adjust.value(min(data), jumpsize), adjust.value(max(data), jumpsize))
  253. values=runif(sum(bb)+1, min=min.max[min.max==min(min.max)], max=min.max[min.max==max(min.max)])
  254. } else {
  255. init.rate=fitContinuous(phy,data)[[1]]$beta
  256. min.max=c(adjust.rate(init.rate, jumpsize), adjust.rate(init.rate, jumpsize))
  257. values=runif(sum(bb)+1, min=min.max[min.max==min(min.max)], max=min.max[min.max==max(min.max)])
  258. }
  259. internal.shifts<-tip.shifts<-numeric(0)
  260. internal.shifts=sort(shifts[shifts>ntip])
  261. tip.shifts=shifts[shifts<=ntip]
  262. if(length(internal.shifts)==0 & length(tip.shifts)==0) {
  263. vv=rep(values, nn)
  264. } else {
  265. vv=bb
  266. vv[]=values[length(values)]
  267. i=0
  268. if(length(internal.shifts)!=0) {
  269. for(i in 1:length(internal.shifts)) {
  270. d=node.des[which(names(node.des)==internal.shifts[i])]
  271. vv[match(c(internal.shifts[i], unlist(d)), names(vv))]=values[i]
  272. }
  273. }
  274. if(length(tip.shifts)!=0) {
  275. for(j in 1:length(tip.shifts)) {
  276. vv[match(tip.shifts[j], names(vv))]=values[j+i]
  277. }
  278. }
  279. }
  280. return(list(delta=unname(bb), values=unname(vv)))
  281. }
  282. assign.root.theta <- function(cur.theta, phy) {
  283. root=phy$edge[1,1]
  284. desc=phy$edge[which(phy$edge[,1]==root),2]
  285. root.theta=cur.theta[sample(which(phy$edge[,2]==desc),1)]
  286. root.theta
  287. }
  288. get.descendants.of.node <- function(node, phy) {
  289. storage=list()
  290. if(is.null(node)) node=phy$edge[1,1]
  291. if(node%in%phy$edge[,1]) {
  292. desc=c(sapply(node, function(x) {return(phy$edge[which(phy$edge[,1]==x),2])}))
  293. while(any(desc%in%phy$edge[,1])) {
  294. desc.true=desc[which(desc%in%phy$edge[,1])]
  295. desc.desc=lapply(desc.true, function(x) return(get.desc.of.node(x, phy)))
  296. storage=list(storage,union(desc,desc.desc))
  297. desc=unlist(desc.desc)
  298. }
  299. storage=sort(unique(unlist(union(desc,storage))))
  300. }
  301. return(storage)
  302. }
  303. get.desc.of.node <- function(node, phy) {
  304. return(phy$edge[which(phy$edge[,1]==node),2])
  305. }
  306. get.ancestor.of.node<-function(node, phy) {
  307. anc=phy$edge[which(phy$edge[,2]==node),1]
  308. anc
  309. }
  310. choose.one <- function(cur.delta)
  311. {
  312. bb=cur.delta
  313. s=sample(1:length(bb),1)
  314. bb[s]=1-bb[s]
  315. bb
  316. }
  317. is.root<-function(node,phy) {
  318. if(node==phy$edge[1,1]) return(TRUE) else return(FALSE)
  319. }
  320. assess.lnR <- function(lnR) {
  321. if(is.na(lnR) || abs(lnR)==Inf) {
  322. error=TRUE
  323. r=0
  324. } else {
  325. if(lnR < -20) {
  326. r=0
  327. } else if(lnR > 0) {
  328. r=1
  329. } else {
  330. r=exp(lnR)
  331. }
  332. error=FALSE
  333. }
  334. return(list(r=r, error=error))
  335. }
  336. apply.BMM.to.apetree<-function(apetree, rates) {
  337. apetree$edge.length=apetree$edge.length*rates
  338. return(apetree)
  339. }
  340. adjust.value <- function(value, jumpsize) {
  341. # mod 10.20.2010 JM Eastman
  342. vv=value
  343. rch <- runif(1, min = -jumpsize, max = jumpsize)
  344. return(vv[]+rch)
  345. }
  346. adjust.rate <- function(rate, jumpsize) {
  347. # mod 10.20.2010 JM Eastman
  348. vv=rate
  349. v=log(vv)
  350. rch <- runif(1, min = -jumpsize, max = jumpsize)
  351. v=exp(v[]+rch)
  352. v
  353. }
  354. prepare.data <- function(phy, data) {
  355. td <- treedata(phy, data, sort = T)
  356. return(list(ape.tre=td$phy, orig.dat=td$data[,1]))
  357. }
  358. summarize.run<-function(cOK, endparms, cur.model) {
  359. # end = c(nRateProp, nRateSwapProp, nRcatProp, nRootProp, nAlphaProp, nThetaProp, nThetaSwapProp, nTcatProp)
  360. if(cur.model=="BM") {
  361. names(endparms)<-names(cOK)<-c("rates", "rate.swap", "rate.catg", "root")
  362. } else {
  363. names(endparms)<-names(cOK)<-c("rates", "rate.swap", "rate.catg", "root", "alpha", "theta", "theta.swap", "theta.catg")
  364. }
  365. names(endparms)=paste("pr.",names(endparms),sep="")
  366. names(cOK)=paste("ok.",names(cOK),sep="")
  367. cat("\n")
  368. if(cur.model=="BM") {
  369. print(endparms[paste("pr.", c("rates", "rate.swap", "rate.catg", "root"),sep="")])
  370. print(cOK[paste("ok.", c("rates", "rate.swap", "rate.catg", "root"),sep="")])
  371. } else {
  372. print(endparms[paste("pr.", c("rates", "rate.swap", "rate.catg", "alpha", "theta", "theta.swap", "theta.catg"),sep="")])
  373. print(cOK[paste("ok.", c("rates", "rate.swap", "rate.catg", "alpha", "theta", "theta.swap", "theta.catg"),sep="")])
  374. }
  375. }
  376. generate.log<-function(bundled.parms, cur.model, file, init=FALSE) {
  377. # bundled.parms=list(gen=i, mrate=mean(cur.rates), cats=sum(cur.delta.rates)+1, root=cur.root, alpha=cur.alpha, reg=sum(cur.delta.theta)+1, theta=mean(cur.theta), lnL=curr.lnL)
  378. res=bundled.parms
  379. if(init) {
  380. if(cur.model=="BM") msg=paste("gen", "model", "mean.rate", "rates", "root", "lnL", sep="\t") else msg=paste("gen", "model", "mean.rate", "rates", "alpha", "regimes", "mean.theta", "lnL", sep="\t")
  381. } else {
  382. if(cur.model=="BM") {
  383. msg<-paste(res$gen, sQuote(cur.model), sprintf("%.3f", res$mrate), res$cats, sprintf("%.3f", res$root), sprintf("%.3f", res$lnL),sep="\t")
  384. } else {
  385. msg<-paste(res$gen, sQuote(cur.model), sprintf("%.3f", res$mrate), res$cats, sprintf("%.4f", res$alpha), res$reg, sprintf("%.3f", res$theta), sprintf("%.3f", res$lnL),sep="\t")
  386. }
  387. }
  388. write(msg, file=file, append=TRUE)
  389. }
  390. parlogger<-function(model, init=FALSE, node.des, i, curr.lnL, cur.root=NULL, cur.rates=NULL, cur.delta.rates=NULL, cur.alpha=NULL, cur.theta=NULL, cur.delta.theta=NULL, parmBase) {
  391. if(init) {
  392. msg.long=names(node.des[-1])
  393. if(model=="BM") {
  394. msg.short=paste("gen", "model", "lnL", sep="\t")
  395. parlogs=paste(parmBase, paste(c("summary", "root", "rates", "rate.shifts"), "txt", sep="."), sep="")
  396. sapply(parlogs[1], function(x) write.table(msg.short, x, quote=FALSE, col.names=FALSE, row.names=FALSE))
  397. sapply(parlogs[2], function(x) write.table(NULL, x, quote=FALSE, col.names=FALSE, row.names=FALSE))
  398. sapply(parlogs[3:length(parlogs)], function(x) write.table(paste(msg.long,collapse=" "), x, quote=FALSE, col.names=FALSE, row.names=FALSE))
  399. } else {
  400. msg.short=paste("gen", "model", "lnL", sep="\t")
  401. parlogs=paste(parmBase, paste(c("summary", "root", "alpha", "rates", "rate.shifts", "optima", "optima.shifts"), "txt", sep="."), sep="")
  402. sapply(parlogs[1], function(x) write.table(msg.short, x, quote=FALSE, col.names=FALSE, row.names=FALSE))
  403. sapply(parlogs[2:3], function(x) write.table(NULL, x, quote=FALSE, col.names=FALSE, row.names=FALSE))
  404. sapply(parlogs[4:length(parlogs)], function(x) write.table(paste(msg.long,collapse=" "), x, quote=FALSE, col.names=FALSE, row.names=FALSE))
  405. }
  406. } else {
  407. if(model=="BM") {
  408. parlogs=paste(parmBase, paste(c("summary", "root", "rates", "rate.shifts"), "txt", sep="."), sep="")
  409. outlist=list(paste(i, model, curr.lnL, sep="\t"), cur.root, cur.rates, cur.delta.rates)
  410. sapply(1:length(outlist), function(x) write.table(paste(outlist[[x]],collapse=" "), parlogs[[x]], quote=FALSE, col.names=FALSE, row.names=FALSE, append=TRUE))
  411. } else {
  412. parlogs=paste(parmBase, paste(c("summary", "root", "alpha", "rates", "rate.shifts", "optima", "optima.shifts"), "txt", sep="."), sep="")
  413. outlist=list(paste(i, model, curr.lnL, sep="\t"), cur.root, cur.alpha, cur.rates, cur.delta.rates, cur.theta, cur.delta.theta)
  414. sapply(1:length(outlist), function(x) write.table(paste(outlist[[x]],collapse=" "), parlogs[[x]], quote=FALSE, col.names=FALSE, row.names=FALSE, append=TRUE))
  415. }
  416. }
  417. }
  418. generate.error.message<-function(i, mod.cur, mod.new, lnR, errorLog, init=FALSE) {
  419. if(init) {
  420. initmsg = write(paste("gen", "curr.lnL", "new.lnL", "lnR", sep="\t"), file=errorLog)
  421. } else {
  422. write(paste(i, sprintf("%.3f", mod.cur$lnL), sprintf("%.3f", mod.new$lnL), sprintf("%.3f", lnR), sep="\t"), file=errorLog)
  423. }
  424. }
  425. determine.accepted.proposal<-function(startparms, endparms, cOK) {
  426. which(startparms!=endparms)->marker
  427. cOK[marker]=cOK[marker]+1
  428. cOK
  429. }
  430. rtpois<-function(N, lambda, k) {
  431. p=ppois(k, lambda, lower.tail=FALSE)
  432. out=qpois(runif(N, min=0, max=1-p), lambda)
  433. out
  434. }
  435. ptpois<-function(x, lambda, k) {
  436. p.k=ppois(k, lambda, lower.tail=FALSE)
  437. p.x=ppois(x, lambda, lower.tail=FALSE)
  438. ptp=p.x/(1-p.k)
  439. return(ptp)
  440. }
  441. ## SUMMARIZING MCMC -- PLOTTING FUNCTIONS ##
  442. shifts.plot=function(phy, base.dir, burnin=0, level=0.03, internal.only=FALSE, paint.branches=TRUE, pdf.base=NULL, verbosity.base=NULL, ...) {
  443. color.length=21
  444. require(ape)
  445. oldwd=getwd()
  446. setwd(base.dir)
  447. files=dir()
  448. # if(optima) {
  449. # shifts.file=files[grep("optima.shifts.txt", files)]
  450. # estimates.file=files[grep("optima.txt", files)]
  451. # } else {
  452. shifts.file=files[grep("rate.shifts.txt", files)]
  453. estimates.file=files[grep("rates.txt", files)]
  454. # }
  455. if(!is.null(pdf.base)) lab=paste(pdf.base, paste("bi", burnin, sep=""), paste("fq", level, sep=""), sep=".")
  456. cat("READING shifts...\n")
  457. results=read.table(shifts.file)
  458. names(results)=as.numeric(results[1,])
  459. results=results[-c(1:(burnin+1)),]
  460. if(!all(names(results)%in%phy$edge[,2])) stop("Cannot process results: check that tree matches posterior summaries")
  461. hits.tmp=apply(results,1,sum)
  462. hits=length(hits.tmp[hits.tmp>0])
  463. aa.tmp=apply(results, 2, function(x) sum(x))
  464. aa.tmp=aa.tmp/hits
  465. aa=aa.tmp[aa.tmp>=level]
  466. aa=aa[order(aa, decreasing=TRUE)]
  467. aa.nodes=aa[which(as.numeric(names(aa))>Ntip(phy))]
  468. aa.tips=aa[which(as.numeric(names(aa))<=Ntip(phy))]
  469. aa=aa.nodes
  470. print(aa.tips)
  471. nodes=as.numeric(names(aa))
  472. nodes=nodes[nodes>Ntip(phy)]
  473. desc=lapply(nodes, function(x) {
  474. foo=get.descendants.of.node(x,phy)
  475. if(length(foo)) return(phy$tip.label[foo[foo<=Ntip(phy)]]) else return(NULL)
  476. }
  477. )
  478. shifts=apply(results, 1, sum)
  479. cat("READING estimates...\n")
  480. ests=read.table(estimates.file)
  481. names(ests)=ests[1,]
  482. ests=ests[-c(1:(burnin+1)),]
  483. average.ests.tmp=apply(ests,2,mean)
  484. average.ests=average.ests.tmp-median(average.ests.tmp)
  485. if(paint.branches) {
  486. require(colorspace)
  487. # cce=diverge_hcl(color.length, c = c(100, 0), l = c(50, 90), power = 1.1)
  488. cce=diverge_hcl(2*color.length, power = 0.5)
  489. e.seq=seq(min(average.ests),max(average.ests),length=color.length)
  490. color.gamut=seq(-max(abs(e.seq)), max(abs(e.seq)), length=length(cce))
  491. colors.branches=sapply(average.ests, function(x) cce[which(min(abs(color.gamut-x))==abs(color.gamut-x))])
  492. colors.branches=colors.branches[match(as.numeric(names(colors.branches)), phy$edge[,2])]
  493. } else {
  494. colors.branches=1
  495. }
  496. if(length(nodes)) {
  497. require(colorspace)
  498. cols=sapply(nodes, function(x) {
  499. a=get.ancestor.of.node(x, phy)
  500. comp=ests[,which(names(ests)==a)]
  501. this=ests[,which(names(ests)==x)]
  502. if(!length(comp)) { # dealing with first descendant of root
  503. d=get.desc.of.node(a, phy)
  504. d=d[which(d!=x)]
  505. # find if sister descendant also experienced rate shift
  506. d.shifts=results[, which(names(results)==d)]
  507. comp=ests[,which(names(ests)==d)]
  508. x.res=sapply(1:length(d.shifts), function(y) {
  509. if(d.shifts[y]==0) {
  510. zz=this[y]-comp[y]
  511. if(zz>0) {
  512. return(1)
  513. } else {
  514. if(zz<0) return(-1) else return(0)
  515. }
  516. } else {
  517. return(0)
  518. }
  519. }
  520. )
  521. x.res=mean(x.res[x.res!=0])
  522. } else {
  523. yy=this-comp
  524. zz=yy
  525. zz[yy>0]=1
  526. zz[yy<0]=-1
  527. zz[yy==0]=0
  528. x.res=mean(zz[zz!=0])
  529. }
  530. return(x.res)
  531. }
  532. )
  533. ccx=diverge_hcl(21, c = c(100, 0), l = c(50, 90), power = 1.1)
  534. c.seq=round(seq(-1,1,by=0.1),digits=1)
  535. colors.nodes=ccx[match(round(cols,1),c.seq)]
  536. names(colors.nodes)=nodes
  537. colors.nodes=colors.nodes[which(as.numeric(names(colors.nodes))>Ntip(phy))]
  538. } else {
  539. colors.nodes=NULL
  540. cols=NULL
  541. }
  542. # send to pdf
  543. if(!is.null(pdf.base)) pdf(file=paste(oldwd, paste(lab,"pdf",sep="."),sep="/"))
  544. plot(phy, cex=0.1, lwd=0.4, edge.width=0.5, edge.color=colors.branches, ...)
  545. nn=(Ntip(phy)+1):max(phy$edge[,2])
  546. ll<-cc<-rr<-rep(0,length(nn))
  547. ll[nn%in%nodes]=1
  548. if(length(nodes)) cc[nn%in%nodes]=aa[match(nn[nn%in%nodes],nodes)]/max(aa)
  549. if(is.null(colors.nodes)) {
  550. nodelabels(pch=ifelse(ll==1, 21, NA), bg=ifelse(ll==1, "black", "white"), cex=2*cc)
  551. } else {
  552. rr[nn%in%nodes]=colors.nodes[order(names(colors.nodes))]
  553. nodelabels(pch=ifelse(ll==1, 21, NA), cex=2*cc, col=rr, bg=rr, lwd=0.5)
  554. if(length(aa.tips) & !internal.only) {
  555. tt=rep(0,Ntip(phy))
  556. tt[(1:Ntip(phy))[as.numeric(names(aa.tips))]]=1
  557. tt.cex=ifelse(tt==1, aa.tips/max(aa.tmp), 0)
  558. tt.col=sapply(names(aa.tips), function(x) {
  559. a=get.ancestor.of.node(x, phy)
  560. comp=ests[,which(names(ests)==a)]
  561. this=ests[,which(names(ests)==x)]
  562. if(!length(comp)) { # dealing with first descendant of root
  563. d=get.desc.of.node(a, phy)
  564. d=d[which(d!=x)]
  565. # find if sister descendant also experienced rate shift
  566. d.shifts=results[, which(names(results)==d)]
  567. comp=ests[,which(names(ests)==d)]
  568. x.res=sapply(1:length(d.shifts), function(y) {
  569. if(d.shifts[y]==0) {
  570. zz=this[y]-comp[y]
  571. if(zz>0) {
  572. return(1)
  573. } else {
  574. if(zz<0) return(-1) else return(0)
  575. }
  576. } else {
  577. return(0)
  578. }
  579. }
  580. )
  581. x.res=mean(x.res[x.res!=0])
  582. } else {
  583. yy=this-comp
  584. zz=yy
  585. zz[yy>0]=1
  586. zz[yy<0]=-1
  587. zz[yy==0]=0
  588. x.res=mean(zz[zz!=0])
  589. }
  590. return(x.res)
  591. }
  592. )
  593. tt.ccx=diverge_hcl(21, c = c(100, 0), l = c(50, 90), power = 1.1)
  594. tt.c.seq=round(seq(-1,1,by=0.1),digits=1)
  595. tt.colors.nodes=tt.ccx[match(round(tt.col,1),tt.c.seq)]
  596. names(tt.colors.nodes)=as.numeric(names(aa.tips))
  597. colors.tips.tmp=tt.colors.nodes[order(as.numeric(names(tt.colors.nodes)))]
  598. colors.tips=rep(NA, Ntip(phy))
  599. colors.tips[(1:Ntip(phy))[as.numeric(names(aa.tips))]]=colors.tips.tmp
  600. tiplabels(pch=ifelse(tt==1, 21, NA), cex=2*tt.cex, col=colors.tips, bg=colors.tips, lwd=0.5)
  601. }
  602. legend("bottomleft", title=toupper("direction"), cex=0.5, pt.cex=1, text.col="darkgray", legend = sprintf("%6.1f", rev(c.seq[seq(1,length(c.seq),by=2)])), pch=21, ncol=1, col = "darkgray", pt.bg = rev(ccx[seq(1,length(c.seq),by=2)]), box.lty="blank", border="white")
  603. if(length(nodes)) legend("bottomright", title=toupper("frequency"), cex=0.5, pt.cex=2*(seq(min(cc), max(cc), length=6)), text.col="darkgray", legend = sprintf("%10.3f", seq(round(min(aa),2), round(max(aa),2), length=6)), pch=21, ncol=1, col = "darkgray", pt.bg = "white", box.lty="blank", border="white")
  604. }
  605. if(!is.null(pdf.base)) dev.off()
  606. if(length(nodes)) names(cols)=names(aa)
  607. setwd(oldwd)
  608. names(desc)=paste("node",nodes,sep=".")
  609. if(!is.null(verbosity.base)) {
  610. summary.table=c(hits/nrow(results), mean(shifts), median(shifts))
  611. names(summary.table)=c("shift.prob", "mean.shift","median.shifts")
  612. write.table(summary.table, file=paste(verbosity.base, "run.summary.txt", sep="."), quote=FALSE, col.names=FALSE)
  613. if(length(nodes)) {
  614. for(nn in 1:length(nodes)) {
  615. write.table(c(nodes[nn], desc[[nn]]), file=paste(verbosity.base, "shift.descendants.txt", sep="."), append=TRUE, quote=FALSE, row.names=FALSE, col.names=FALSE)
  616. }
  617. }
  618. allres=merge(as.data.frame(aa),as.data.frame(cols),by=0)
  619. allres=allres[order(allres$aa, decreasing=TRUE),]
  620. names(allres)=c("node", "conditional.shift.probability", "relative.shift.direction")
  621. write.table(allres, file=paste(verbosity.base, "estimates.summary.txt", sep="."), quote=FALSE, row.names=FALSE)
  622. }
  623. return(list(desc=desc, shift.prob=hits/nrow(results), mean.shifts=mean(shifts), median.shifts=median(shifts), shift.prop=aa, shift.direction=cols, mean.rates=average.ests.tmp, mean.shifts=aa.tmp/nrow(results)))
  624. }
  625. plot.quant<-function(phy, data, data.names, shrinker=1, relative=TRUE, cex=0.5, adj=c(15,5), lwd=0.5, font=1, ...){
  626. std=function(x,max,min){return((x-min)/(max-min))}
  627. if(relative) {
  628. data=sapply(data, function(x) std(x, max(data), min(data)))
  629. }
  630. f=match(phy$tip.label, data.names)
  631. if(is.na(sum(f))) {
  632. stop("tips cannot be matched to tree")
  633. }
  634. else {
  635. data=data[f]
  636. phy$trait=data
  637. plot.phylo(phy, show.tip.label=T, label.offset=adj[1], cex=cex, font=font, ...)
  638. tiplabels(text=NULL, pch=21, adj=adj[2], cex=c(phy$trait/shrinker), bg="white",lwd=lwd)
  639. }
  640. }
  641. branchcol.plot=function(phy, cur.rates, color.length=4, ...) {
  642. color.length=color.length
  643. require(ape)
  644. require(colorspace)
  645. ests=cur.rates
  646. names(ests)=phy$edge[,2]
  647. cce=diverge_hcl(color.length, power = 0.5)
  648. e.seq=seq(min(ests),max(ests),length=color.length)
  649. colors.branches=sapply(ests, function(x) cce[which(min(abs(e.seq-x))==abs(e.seq-x))])
  650. names(colors.branches)=names(ests)
  651. colors.branches=colors.branches[match(as.numeric(names(colors.branches)), phy$edge[,2])]
  652. plot(phy, cex=0.1, lwd=0.4, edge.width=0.5, edge.color=colors.branches, ...)
  653. }
  654. prior.posterior.plot=function(data, rpois.lambda) {
  655. # data should be a vector of number of shifts, for instance, for all interations across the MCMC sampling (post-burnin)
  656. require(ggplot2)
  657. dataset <- data.frame(variable = gl(2, length(data), labels = c("posterior", "prior")), value = c(data, rpois(length(data),rpois.lambda)))
  658. ggplot(data = dataset, aes(x = value, fill = variable)) + geom_histogram(position = "dodge") + scale_fill_manual(values = c("gray", "black"))
  659. }