-
Notifications
You must be signed in to change notification settings - Fork 0
/
utilities.R
1972 lines (1859 loc) · 64.9 KB
/
utilities.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
## some utility functions
## written by Liam J. Revell 2011, 2012, 2013, 2014, 2015, 2016, 2017
## function to rescale a tree according to an EB model
## written by Liam J. Revell 2017
ebTree<-function(tree,r){
if(r!=0){
H<-nodeHeights(tree)
e<-(exp(r*H[,2])-exp(r*H[,1]))/r
tree$edge.length<-e
}
tree
}
## function to expand clades in a plot by a given factor
## written by Liam J. Revell 2017
expand.clade<-function(tree,node,factor=5){
cw<-reorder(tree)
tips<-setNames(rep(1,Ntip(tree)),cw$tip.label)
get.tips<-function(node,tree){
dd<-getDescendants(tree,node)
tree$tip.label[dd[dd<=Ntip(tree)]]
}
desc<-unlist(lapply(node,get.tips,tree=cw))
for(i in 2:Ntip(cw)){
tips[i]<-tips[i-1]+
if(names(tips)[i]%in%desc){
1
} else if(names(tips)[i-1]%in%desc){
1
} else 1/factor
}
obj<-list(tree=tree,tips=tips)
class(obj)<-"expand.clade"
obj
}
## S3 print method for the object class "expand.clade"
print.expand.clade<-function(x,...){
cat("An object of class \"expand.clade\" consisting of:\n")
cat(paste("(1) A phylogenetic tree (x$tree) with",Ntip(x$tree),
"tips and\n ",x$tree$Nnode,"internal nodes.\n"))
cat("(2) A vector (x$tips) containing the desired tip-spacing.\n\n")
}
## S3 plot method for the object class "expand.clade"
plot.expand.clade<-function(x,...){
args<-list(...)
args$tree<-x$tree
args$tips<-x$tips
if(inherits(args$tree,"simmap")) do.call(plotSimmap,args)
else do.call(plotTree,args)
}
## function to add a geological or other temporal legend to a plotted tree
## written by Liam J. Revell 2017
geo.legend<-function(leg=NULL,colors=NULL,alpha=0.2,...){
if(hasArg(cex)) cex<-list(...)$cex
else cex<-par()$cex
if(hasArg(plot)) plot<-list(...)$plot
else plot<-TRUE
if(hasArg(show.lines)) show.lines<-list(...)$show.lines
else show.lines<-TRUE
obj<-get("last_plot.phylo",envir=.PlotPhyloEnv)
if(is.null(colors)){
colors<-setNames(c(
rgb(255,242,127,255,maxColorValue=255),
rgb(255,230,25,255,maxColorValue=255),
rgb(253,154,82,255,maxColorValue=255),
rgb(127,198,78,255,maxColorValue=255),
rgb(52,178,201,255,maxColorValue=255),
rgb(129,43,146,255,maxColorValue=255),
rgb(240,64,40,255,maxColorValue=255),
rgb(103,165,153,255,maxColorValue=255),
rgb(203,140,55,255,maxColorValue=255),
rgb(179,225,182,255,maxColorValue=255),
rgb(0,146,112,255,maxColorValue=255),
rgb(127,160,86,255,maxColorValue=255),
rgb(247,67,112,255,maxColorValue=255)),
c("Quaternary","Neogene","Paleogene",
"Cretaceous","Jurassic","Triassic",
"Permian","Carboniferous","Devonian",
"Silurian","Ordovician","Cambrian",
"Precambrian"))
}
if(is.null(leg)){
leg<-rbind(c(2.588,0),
c(23.03,2.588),
c(66.0,23.03),
c(145.0,66.0),
c(201.3,145.0),
c(252.17,201.3),
c(298.9,252.17),
c(358.9,298.9),
c(419.2,358.9),
c(443.8,419.2),
c(485.4,443.8),
c(541.0,485.4),
c(4600,541.0))
rownames(leg)<-c("Quaternary","Neogene","Paleogene",
"Cretaceous","Jurassic","Triassic",
"Permian","Carboniferous","Devonian",
"Silurian","Ordovician","Cambrian",
"Precambrian")
t.max<-max(obj$xx)
ii<-which(leg[,2]<=t.max)
leg<-leg[ii,]
leg[max(ii),1]<-t.max
}
colors<-sapply(colors,make.transparent,alpha=alpha)
if(plot){
y<-c(rep(0,2),rep(par()$usr[4],2))
ylabel<--1/25*obj$Ntip
for(i in 1:nrow(leg)){
strh<-strheight(rownames(leg)[i])
polygon(c(leg[i,1:2],leg[i,2:1]),y,
col=colors[rownames(leg)[i]],border=NA)
if(show.lines){
lines(x=rep(leg[i,1],2),y=c(0,par()$usr[4]),
lty="dotted",col="grey")
lines(x=c(leg[i,1],mean(leg[i,])-0.8*cex*
get.asp()*strheight(rownames(leg)[i])),
y=c(0,ylabel),lty="dotted",col="grey")
lines(x=c(leg[i,2],mean(leg[i,])+0.8*cex*
get.asp()*strheight(rownames(leg)[i])),
y=c(0,ylabel),lty="dotted",col="grey")
lines(x=rep(mean(leg[i,])-0.8*cex*
get.asp()*strheight(rownames(leg)[i]),2),
y=c(ylabel,par()$usr[3]),lty="dotted",col="grey")
lines(x=rep(mean(leg[i,])+0.8*cex*
get.asp()*strheight(rownames(leg)[i]),2),
y=c(ylabel,par()$usr[3]),lty="dotted",col="grey")
}
polygon(x=c(leg[i,1],
mean(leg[i,])-0.8*cex*get.asp()*strh,
mean(leg[i,])-0.8*cex*get.asp()*strh,
mean(leg[i,])+0.8*cex*get.asp()*strh,
mean(leg[i,])+0.8*cex*get.asp()*strh,
leg[i,2]),y=c(0,ylabel,par()$usr[3],
par()$usr[3],ylabel,0),
col=colors[rownames(leg)[i]],border=NA)
text(x=mean(leg[i,])+
if(obj$direction=="leftwards") 0.12*strh else -0.12*strh,
y=ylabel,labels=rownames(leg)[i],
srt=90,adj=c(1,0.5),cex=cex)
}
}
invisible(list(leg=leg,colors=colors))
}
## borrowed from mapplots
get.asp<-function(){
pin<-par("pin")
usr<-par("usr")
asp<-(pin[2]/(usr[4]-usr[3]))/(pin[1]/(usr[2]-usr[1]))
asp
}
round.polygon<-function(x,y,col="transparent"){
## just space holding for now
}
## draw a box around a clade
## written by Liam J. Revell 2017
cladebox<-function(tree,node,color=NULL,...){
if(is.null(color)) color<-make.transparent("yellow",0.2)
obj<-get("last_plot.phylo",envir=.PlotPhyloEnv)
h<-max(nodeHeights(tree))
parent<-tree$edge[which(tree$edge[,2]==node),1]
x0<-max(c(obj$xx[node]+obj$xx[parent])/2,obj$xx[node]-0.05*h)
x1<-obj$x.lim[2]
dd<-getDescendants(tree,node)
y0<-min(range(obj$yy[dd]))-0.5
y1<-max(range(obj$yy[dd]))+0.5
polygon(c(x0,x1,x1,x0),c(y0,y0,y1,y1),col=color,
border=0)
}
## draw tip labels as linking lines to text
## written by Liam J. Revell 2017
linklabels<-function(text,tips,link.type=c("bent","curved","straight"),
...){
lastPP<-get("last_plot.phylo",envir=.PlotPhyloEnv)
if(!(lastPP$direction%in%c("leftwards","rightwards")))
stop("direction should be \"rightwards\" or \"leftwards\".")
if(hasArg(cex)) cex<-list(...)$cex
else cex<-1
if(hasArg(col)) col<-list(...)$col
else col<-"black"
if(hasArg(lty)) lty<-list(...)$lty
else lty<-"dashed"
if(hasArg(lwd)) lwd<-list(...)$lwd
else lwd<-1
if(hasArg(link.offset)) link.offset<-list(...)$link.offset
else link.offset<-0.1*max(lastPP$xx)
if(hasArg(font)) font<-list(...)$font
else font<-3
link.type<-link.type[1]
xpos<-lastPP$xx[tips]+strwidth("i")
ypos<-lastPP$yy[tips]
xmax<-rep(max(lastPP$xx),length(tips))+link.offset
ylab<-seq(min(lastPP$yy),max(lastPP$yy),
by=(max(lastPP$yy)-min(lastPP$yy))/(length(tips)-1))
ylab<-ylab[rank(ypos)]
text(xmax,ylab,gsub("_"," ",text),pos=4,font=font,cex=cex,
offset=0)
if(link.type=="curved"){
for(i in 1:length(tips))
drawCurve(c(xpos[i],xmax[i]),c(ypos[i],ylab[i]),
scale=0.05,lty=lty,col=col,lwd=lwd)
} else if(link.type=="bent"){
tipmax<-max(lastPP$xx)
for(i in 1:length(tips)){
ff<-strwidth("W")
segments(xpos[i],ypos[i],tipmax+link.offset/2,ypos[i],
lty=lty,col=col,lwd=lwd)
segments(tipmax+link.offset/2,ypos[i],tipmax+
link.offset/2+ff,ylab[i],lty=lty,col=col,lwd=lwd)
segments(tipmax+link.offset/2+ff,ylab[i],xmax[i],ylab[i],
lty=lty,col=col,lwd=lwd)
}
} else if(link.type=="straight")
segments(xpos,ypos,xmax,ylab,lty=lty,col=col)
}
## function forces a tree to be ultrametric using two different methods
## written by Liam J. Revell 2017
force.ultrametric<-function(tree,method=c("nnls","extend")){
method<-method[1]
if(method=="nnls") tree<-nnls.tree(cophenetic(tree),tree,
rooted=TRUE,trace=0)
else if(method=="extend"){
h<-diag(vcv(tree))
d<-max(h)-h
ii<-sapply(1:Ntip(tree),function(x,y) which(y==x),
y=tree$edge[,2])
tree$edge.length[ii]<-tree$edge.length[ii]+d
} else
cat("method not recognized: returning input tree\n\n")
tree
}
## function to create curved clade labels for a fan tree
## written by Liam J. Revell 2017
arc.cladelabels<-function(tree=NULL,text,node=NULL,ln.offset=1.02,
lab.offset=1.06,cex=1,orientation="curved",...){
obj<-get("last_plot.phylo",envir=.PlotPhyloEnv)
if(obj$type!="fan") stop("method works only for type=\"fan\"")
h<-max(sqrt(obj$xx^2+obj$yy^2))
if(hasArg(mark.node)) mark.node<-list(...)$mark.node
else mark.node<-TRUE
if(hasArg(interactive)) interactive<-list(...)$interactive
else {
if(is.null(node)) interactive<-TRUE
else interactive<-FALSE
}
if(interactive) node<-getnode()
if(hasArg(lwd)) lwd<-list(...)$lwd
else lwd<-par()$lwd
if(hasArg(col)) col<-list(...)$col
else col<-par()$col
if(hasArg(lend)) lend<-list(...)$lend
else lend<-par()$lend
if(hasArg(clockwise)) clockwise<-list(...)$clockwise
else clockwise<-TRUE
if(hasArg(n)) n<-list(...)$n
else n<-0.05
if(mark.node) points(obj$xx[node],obj$yy[node],pch=21,
bg="red")
if(is.null(tree)){
tree<-list(edge=obj$edge,tip.label=1:obj$Ntip,
Nnode=obj$Nnode)
class(tree)<-"phylo"
}
d<-getDescendants(tree,node)
d<-sort(d[d<=Ntip(tree)])
deg<-atan(obj$yy[d]/obj$xx[d])*180/pi
ii<-intersect(which(obj$yy[d]>=0),which(obj$xx[d]<0))
deg[ii]<-180+deg[ii]
ii<-intersect(which(obj$yy[d]<0),which(obj$xx[d]<0))
deg[ii]<-180+deg[ii]
ii<-intersect(which(obj$yy[d]<0),which(obj$xx[d]>=0))
deg[ii]<-360+deg[ii]
draw.arc(x=0,y=0,radius=ln.offset*h,deg1=min(deg),
deg2=max(deg),lwd=lwd,col=col,lend=lend,n=n)
if(orientation=="curved")
arctext(text,radius=lab.offset*h,
middle=mean(range(deg*pi/180)),cex=cex,
clockwise=clockwise)
else if(orientation=="horizontal"){
x0<-lab.offset*cos(median(deg)*pi/180)*h
y0<-lab.offset*sin(median(deg)*pi/180)*h
text(x=x0,y=y0,label=text,
adj=c(if(x0>=0) 0 else 1,if(y0>=0) 0 else 1),
offset=0,cex=cex)
}
}
## function to return a node index interactively from a plotted tree
## written by Liam J. Revell 2017
getnode<-function(...){
if(hasArg(env)) env<-list(...)$env
else env<-get("last_plot.phylo",envir=.PlotPhyloEnv)
if(hasArg(show.pt)) show.pt<-list(...)$show.pt
else show.pt<-FALSE
xy<-unlist(locator(n=1))
if(show.pt) points(xy[1],xy[2])
d<-sqrt((xy[1]-env$xx)^2+(xy[2]-env$yy)^2)
ii<-which(d==min(d))[1]
ii
}
## function mostly to interactively label nodes by clicking
## written by Liam J. Revell 2017
labelnodes<-function(text,node=NULL,interactive=TRUE,
shape=c("circle","ellipse","rect"),...){
shape<-shape[1]
if(hasArg(circle.exp)) circle.exp<-list(...)$circle.exp
else circle.exp<-1.3
if(hasArg(rect.exp)) rect.exp<-list(...)$rect.exp
else rect.exp<-1.6
if(hasArg(cex)) cex<-list(...)$cex
else cex<-1
obj<-get("last_plot.phylo",envir=.PlotPhyloEnv)
h<-cex*strheight("A")
w<-cex*strwidth(text)
rad<-circle.exp*h*diff(par()$usr[1:2])/diff(par()$usr[3:4])
if(is.null(node)){
if(!interactive){
cat("No nodes provided. Setting interactive mode to TRUE.\n")
interactive<-TRUE
}
node<-vector(length=length(text))
}
for(i in 1:length(text)){
if(interactive){
cat(paste("Click on the node you would like to label ",
text[i],".\n",sep=""))
flush.console()
ii<-getnode(env=obj)
node[i]<-ii
} else ii<-node[i]
if(shape=="circle")
draw.circle(obj$xx[ii],obj$yy[ii],rad,col="white")
else if(shape=="ellipse")
draw.ellipse(obj$xx[ii],obj$yy[ii],0.8*w[i],h,
col="white")
else if(shape=="rect")
rect(xleft=obj$xx[ii]-0.5*rect.exp*w[i],
ybottom=obj$yy[ii]-0.5*rect.exp*h,
xright=obj$xx[ii]+0.5*rect.exp*w[i],
ytop=obj$yy[ii]+0.5*rect.exp*h,col="white",
ljoin=1)
text(obj$xx[ii],obj$yy[ii],label=text[i],cex=cex)
}
invisible(node)
}
## convert object of class "birthdeath" into birth & death rates
bd<-function(x){
if(class(x)!="birthdeath") stop("x should be an object of class 'birthdeath'")
b<-x$para[2]/(1-x$para[1])
d<-b-x$para[2]
setNames(c(b,d),c("b","d"))
}
## compute AIC weights
aic.w<-function(aic){
d.aic<-aic-min(aic)
x<-exp(-1/2*d.aic)/sum(exp(-1/2*d.aic))
class(x)<-"aic.w"
x
}
print.aic.w<-function(x,...){
if(hasArg(signif)) signif<-list(...)$signif
else signif<-8
print(round(unclass(x),signif))
}
## function to compute all paths towards the tips from a node
## written by Liam J. Revell
node.paths<-function(tree,node){
d<-Descendants(tree,node,"children")
paths<-as.list(d)
while(any(d>Ntip(tree))){
jj<-1
new.paths<-list()
for(i in 1:length(paths)){
if(paths[[i]][length(paths[[i]])]<=Ntip(tree)){
new.paths[[jj]]<-paths[[i]]
jj<-jj+1
} else {
ch<-Descendants(tree,paths[[i]][length(paths[[i]])],
"children")
for(j in 1:length(ch)){
new.paths[[jj]]<-c(paths[[i]],ch[j])
jj<-jj+1
}
}
}
paths<-new.paths
d<-sapply(paths,function(x) x[length(x)])
}
paths
}
## function to compute a modification of Grafen's edge lengths
## written by Liam J. Revell 2016
modified.Grafen<-function(tree,power=2){
max.np<-function(tree,node){
np<-node.paths(tree,node)
if(length(np)>0) max(sapply(np,length)) else 0
}
nn<-1:(Ntip(tree)+tree$Nnode)
h<-sapply(nn,max.np,tree=tree)+1
h<-(h/max(h))^power
edge.length<-vector()
for(i in 1:nrow(tree$edge))
edge.length[i]<-diff(h[tree$edge[i,2:1]])
tree$edge.length<-edge.length
tree
}
## function to compute all rotations
## written by Liam J. Revell 2016
allRotations<-function(tree){
if(!is.binary.tree(tree)){
was.binary<-FALSE
if(is.null(tree$edge.length)){
tree<-compute.brlen(tree)
had.edge.lengths<-FALSE
} else had.edge.lengths<-TRUE
tree<-multi2di(tree)
} else was.binary<-TRUE
nodes<-1:tree$Nnode+Ntip(tree)
trees<-vector(mode="list",length=2^length(nodes))
ii<-2
trees[[1]]<-tree
for(i in 1:length(nodes)){
N<-ii-1
for(j in 1:N){
trees[[ii]]<-rotate(trees[[j]],nodes[i])
ii<-ii+1
}
}
trees<-lapply(trees,untangle,"read.tree")
if(!was.binary){
trees<-lapply(trees,di2multi)
if(!had.edge.lengths) trees<-lapply(trees,
function(x){
x$edge.length<-NULL
x
})
}
class(trees)<-"multiPhylo"
trees
}
## function to rotate a multifurcation in all possible ways
## written by Liam J. Revell 2016
rotate.multi<-function(tree,node){
kids<-Children(tree,node)
if(length(kids)>2){
ii<-sapply(kids,function(x,y) which(y==x),y=tree$edge[,2])
jj<-permn(ii)
foo<-function(j,i,t){
t$edge[i,]<-t$edge[j,]
if(!is.null(t$edge.length))
t$edge.length[i]<-t$edge.length[j]
untangle(t,"read.tree")
}
obj<-lapply(jj[2:length(jj)],foo,i=ii,t=tree)
class(obj)<-"multiPhylo"
} else obj<-untangle(rotate(tree,node),"read.tree")
obj
}
## wrapper for bind.tree that takes objects of class "simmap"
## written by Liam J. Revell 2016
bind.tree.simmap<-function(x,y,where="root"){
x<-reorder(x)
y<-reorder(y)
rootx<-x$edge[1,1]
rooty<-y$edge[1,1]
xy<-read.tree(text=write.tree(bind.tree(x,y,where)))
Mx<-rbind(matchLabels(x,xy),matchNodes(x,xy,"distances"))
My<-rbind(matchLabels(y,xy),matchNodes(y,xy,"distances"))
if(where!="root"&&where<=Ntip(x))
Mx[which(is.na(Mx[,2])),2]<-findMRCA(xy,y$tip.label)
xy$maps<-vector(mode="list",length=nrow(xy$edge))
ix<-sapply(Mx[-which(Mx[,1]==rootx),1],
function(x,y) which(y==x),y=x$edge[,2])
ixy<-sapply(Mx[-which(Mx[,1]==rootx),2],
function(x,y) which(y==x),y=xy$edge[,2])
xy$maps[ixy]<-x$maps[ix]
iy<-sapply(My[-which(My[,1]==rooty),1],
function(x,y) which(y==x),y=y$edge[,2])
ixy<-sapply(My[-which(My[,1]==rooty),2],
function(x,y) which(y==x),y=xy$edge[,2])
xy$maps[ixy]<-y$maps[iy]
xy$mapped.edge<-makeMappedEdge(xy$edge,xy$maps)
ns<-c(setNames(getStates(xy,"tips"),1:Ntip(xy)),
getStates(xy,"nodes"))
xy$node.states<-cbind(ns[as.character(xy$edge[,1])],
ns[as.character(xy$edge[,2])])
xy$states<-getStates(xy,"tips")
attr(xy,"class")<-c("simmap",class(xy))
xy
}
## generic function to convert an object of class "simmap" to "phylo"
## written by Liam J. Revell 2016
as.phylo.simmap<-function(x,...){
x$maps<-NULL
x$mapped.edge<-NULL
if(!is.null(x$node.states)) x$node.states<-NULL
if(!is.null(x$states)) x$states<-NULL
if(!is.null(x$Q)) x$Q<-NULL
if(!is.null(x$logL)) x$logL<-NULL
if(!is.null(attr(x,"map.order"))) attr(x,"map.order")<-NULL
class(x)<-setdiff(class(x),"simmap")
x
}
## generic function to convert an object of class "multiSimmap" to "multiPhylo"
## written by Liam J. Revell 2016
as.multiPhylo.multiSimmap<-function(x,...){
obj<-lapply(x,as.phylo)
class(obj)<-setdiff(class(x),"multiSimmap")
obj
}
## generic function to convert object of class "phylo" to "multiPhylo"
## written by Liam J. Revell 2016
as.multiPhylo.phylo<-function(x,...){
obj<-list(x)
class(obj)<-"multiPhylo"
obj
}
as.multiPhylo<-function(x,...){
if (identical(class(x),"multiPhylo")) return(x)
UseMethod("as.multiPhylo")
}
## get mapped states
## written by Liam J. Revell 2016
mapped.states<-function(tree,...){
if(!(inherits(tree,"simmap")||inherits(tree,"multiSimmap")))
stop("tree should be an object of class \"simmap\" or \"multiSimmap\".")
else {
if(inherits(tree,"simmap")){
if(!is.null(tree$mapped.edge))
obj<-sort(colnames(tree$mapped.edge))
else
obj<-sort(unique(unlist(lapply(tree$maps,function(x) names(x)))))
} else if(inherits(tree,"multiSimmap")) {
obj<-sapply(tree,mapped.states,...)
}
}
obj
}
## match labels between trees (equivalent to matchNodes)
## written by Liam J. Revell 2016
matchLabels<-function(tr1,tr2){
foo<-function(x,y) if(length(obj<-which(y==x))>0) obj else NA
M<-cbind(1:Ntip(tr1),sapply(tr1$tip.label,foo,y=tr2$tip.label))
colnames(M)<-c("tr1","tr2")
M
}
## compute the probability of states changes along edges of the tree
## written by Liam J. Revell 2015
edgeProbs<-function(trees){
if(!inherits(trees,"multiSimmap")) stop("trees should be an object of class \"multiSimmap\".")
SS<-sapply(trees,getStates,"tips")
states<-sort(unique(as.vector(SS)))
m<-length(states)
TT<-sapply(states,function(x,y) sapply(y,paste,x,sep="->"),
y=states)
nn<-c(TT[upper.tri(TT)],TT[lower.tri(TT)])
## this function computes for a given edge
fn<-function(edge,trees,states){
obj<-sapply(trees,function(x,e,s)
if(names(x$maps[[e]])[1]==
s[1]&&names(x$maps[[e]])[length(x$maps[[e]])]==s[2]) TRUE
else FALSE,e=edge,s=states)
sum(obj)/length(obj)
}
edge.probs<-matrix(0,nrow(trees[[1]]$edge),m,
dimnames=list(apply(trees[[1]]$edge,1,paste,collapse=","),nn))
k<-1
for(i in 1:m) for(j in 1:m){
if(i!=j){
edge.probs[,k]<-sapply(1:nrow(trees[[1]]$edge),fn,
trees=trees,states=states[c(i,j)])
k<-k+1
}
}
edge.probs<-cbind(edge.probs,1-rowSums(edge.probs))
colnames(edge.probs)[ncol(edge.probs)]<-"no change"
edge.probs
}
## get a position in the tree interactively
## written by Liam J. Revell 2015, 2016
get.treepos<-function(message=TRUE,...){
obj<-get("last_plot.phylo",envir=.PlotPhyloEnv)
if(obj$type=="phylogram"&&obj$direction=="rightwards"){
if(message){
cat("Click on the tree position you want to capture...\n")
flush.console()
}
if(hasArg(x)) x<-list(...)$x
else x<-NULL
if(hasArg(y)) y<-list(...)$y
else y<-NULL
if(is.null(x)||is.null(y)){
x<-unlist(locator(1))
y<-x[2]
x<-x[1]
}
d<-pos<-c()
for(i in 1:nrow(obj$edge)){
x0<-obj$xx[obj$edge[i,]]
y0<-obj$yy[obj$edge[i,2]]
if(x<x0[1]||x>x0[2]){
d[i]<-min(dist(rbind(c(x,y),c(x0[1],y0))),
dist(rbind(c(x,y),c(x0[2],y0))))
pos[i]<-if(x>x0[2]) 0 else diff(obj$xx[obj$edge[i,]])
} else {
d[i]<-abs(y0-y)
pos[i]<-obj$xx[obj$edge[i,2]]-x
}
}
ii<-which(d==min(d))
list(where=obj$edge[ii,2],pos=pos[ii])
} else stop("Does not work for the plotted tree type.")
}
## fastDist: uses fastHeight to compute patristic distance between a pair of species
fastDist<-function(tree,sp1,sp2){
if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".")
if(is.null(tree$edge.length)) stop("tree should have edge lengths.")
if(sp1==sp2) 0
else fastHeight(tree,sp1,sp1)+fastHeight(tree,sp2,sp2)-
2*fastHeight(tree,sp1,sp2)
}
# function reorders simmap tree
# written Liam Revell 2011, 2013, 2015
reorderSimmap<-function(tree,order="cladewise",index.only=FALSE,...){
if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".")
ii<-reorder.phylo(tree,order,index.only=TRUE,...)
if(!index.only){
if(inherits(ii,"phylo")) ii<-whichorder(ii$edge[,2],tree$edge[,2]) ## bug workaround
tree$edge<-tree$edge[ii,]
tree$edge.length<-tree$edge.length[ii]
if(!is.null(tree$maps)){
tree$maps<-tree$maps[ii]
tree$mapped.edge<-tree$mapped.edge[ii,]
}
attr(tree,"order")<-order
return(tree)
} else return(ii)
}
## S3 reorder method for objects of class "simmap"
reorder.simmap<-function(x,...) reorderSimmap(x,...)
# function whichorder
# written by Liam Revell 2011, 2013, 2015
whichorder<-function(x,y) sapply(x,function(x,y) which(x==y),y=y)
# function returns random state with probability given by y
# written by Liam J. Revell 2013, 2015
rstate<-function(y){
if(length(y)==1) return(names(y)[1])
else {
p<-y/sum(y)
if(any(p<0)){
warning("Some probabilities (slightly?) < 0. Setting p < 0 to zero.")
p[p<0]<-0
}
return(names(which(rmultinom(1,1,p)[,1]==1)))
}
}
## mark the changes on a plotted "simmap" object
## written by Liam J. Revell 2015
markChanges<-function(tree,colors=NULL,cex=1,lwd=2,plot=TRUE){
states<-sort(unique(getStates(tree)))
if(is.null(colors)) colors<-setNames(palette()[1:length(states)],
states)
obj<-get("last_plot.phylo",envir=.PlotPhyloEnv)
nc<-sapply(tree$maps,length)-1
ii<-which(nc>0)
nc<-nc[ii]
xx<-yy<-vector()
for(i in 1:length(ii)){
for(j in 1:nc[i]){
ss<-names(tree$maps[[ii[i]]])[j+1]
mm<-tree$edge[ii[i],1]
dd<-tree$edge[ii[i],2]
x<-rep(obj$xx[mm]+cumsum(tree$maps[[ii[i]]])[j],2)
y<-c(obj$yy[dd]-0.5*mean(strheight(LETTERS)*cex),
obj$yy[dd]+0.5*mean(strheight(LETTERS)*cex))
if(plot) lines(x,y,lwd=lwd,col=colors[ss],lend=2)
xx<-c(xx,setNames(x[1],
paste(names(tree$maps[[ii[i]]])[j:(j+1)],
collapse="->")))
yy<-c(yy,mean(y))
}
}
XY<-cbind(xx,yy)
colnames(XY)<-c("x","y")
invisible(XY)
}
## function to label clades
## written by Liam J. Revell 2014, 2015
cladelabels<-function(tree=NULL,text,node,offset=NULL,wing.length=NULL,cex=1,
orientation="vertical"){
lastPP<-get("last_plot.phylo",envir=.PlotPhyloEnv)
if(is.null(tree)){
wing.length<-1
if(is.null(offset)) offset<-8
tree<-list(edge=lastPP$edge,
tip.label=1:lastPP$Ntip,
Nnode=lastPP$Nnode)
H<-matrix(lastPP$xx[tree$edge],nrow(tree$edge),2)
tree$edge.length<-H[,2]-H[,1]
class(tree)<-"phylo"
}
if(is.null(offset)) offset<-0.5
xx<-mapply(labelSubTree,node,text,
MoreArgs=list(tree=tree,pp=lastPP,offset=offset,wl=wing.length,cex=cex,
orientation=orientation))
}
## internal function used by cladelabels
## written by Liam J. Revell 2014, 2015
labelSubTree<-function(tree,nn,label,pp,offset,wl,cex,orientation){
if(is.null(wl)) wl<-1
tree<-reorder(tree)
tips<-getDescendants(tree,nn)
tips<-tips[tips<=length(tree$tip.label)]
ec<-0.7 ## expansion constant
sw<-pp$cex*max(strwidth(tree$tip.label[tips]))
sh<-pp$cex*max(strheight(tree$tip.label))
cw<-mean(strwidth(LETTERS)*cex)
h<-max(sapply(tips,function(x,tree)
nodeHeights(tree)[which(tree$edge[,2]==x),2],
tree=tree))+sw+offset*cw
y<-range(pp$yy[tips])
lines(c(h,h),y+ec*c(-sh,sh))
lines(c(h-wl*cw,h),
c(y[1]-ec*sh,y[1]-ec*sh))
lines(c(h-wl*cw,h),
c(y[2]+ec*sh,y[2]+ec*sh))
text(h+cw,mean(y),
label,srt=if(orientation=="horizontal") 0 else 90,
adj=if(orientation=="horizontal") 0 else 0.5,cex=cex)
}
## get all the extant/extinct tip names
## written by Liam J. Revell 2012, 2015
getExtant<-function(tree,tol=1e-8){
if(!inherits(tree,"phylo")) stop("tree should be object of class \"phylo\".")
H<-nodeHeights(tree)
tl<-max(H)
x<-which(H[,2]>=(tl-tol))
y<-tree$edge[x,2]
y<-y[y<=length(tree$tip)]
z<-tree$tip.label[y]
return(z)
}
getExtinct<-function(tree,tol=1e-8) setdiff(tree$tip.label,getExtant(tree,tol))
# function splits tree at split
# written by Liam Revell 2011, 2014, 2015
splitTree<-function(tree,split){
if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".")
if(split$node>length(tree$tip.label)){
# first extract the clade given by shift$node
tr2<-extract.clade(tree,node=split$node)
tr2$root.edge<-tree$edge.length[which(tree$edge[,2]==split$node)]-split$bp
#now remove tips in tr2 from tree
tr1<-drop.clade(tree,tr2$tip.label)
nn<-if(!is.null(tree$node.label)) c(tree$node.label,"NA") else "NA"
tr1$tip.label[which(tr1$tip.label%in%nn)]<-"NA"
tr1$edge.length[match(which(tr1$tip.label=="NA"),tr1$edge[,2])]<-split$bp
} else {
# first extract the clade given by shift$node
tr2<-list(edge=matrix(c(2L,1L),1,2),tip.label=tree$tip.label[split$node],edge.length=tree$edge.length[which(tree$edge[,2]==split$node)]-split$bp,Nnode=1L)
class(tr2)<-"phylo"
# now remove tip in tr2 from tree
tr1<-tree
tr1$edge.length[match(which(tr1$tip.label==tr2$tip.label[1]),tr1$edge[,2])]<-split$bp
tr1$tip.label[which(tr1$tip.label==tr2$tip.label[1])]<-"NA"
}
trees<-list(tr1,tr2)
class(trees)<-"multiPhylo"
trees
}
# function drops entire clade
# written by Liam Revell 2011, 2015
drop.clade<-function(tree,tip){
if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".")
nn<-if(!is.null(tree$node.label)) c(tree$node.label,"NA") else "NA"
tree<-drop.tip(tree,tip,trim.internal=FALSE)
while(sum(tree$tip.label%in%nn)>1)
tree<-drop.tip(tree,tree$tip.label[tree$tip.label%in%nn],
trim.internal=FALSE)
tree
}
## function to re-root a phylogeny along an edge
## written by Liam J. Revell 2011-2016
reroot<-function(tree,node.number,position=NULL,interactive=FALSE,...){
if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".")
if(interactive){
plotTree(tree,...)
cat("Click where you would like re-root the plotted tree\n")
flush.console()
obj<-get.treepos(message=FALSE)
node.number<-obj$where
position<-tree$edge.length[which(tree$edge[,2]==node.number)]-obj$pos
}
if(is.null(position)) position<-tree$edge.length[which(tree$edge[,2]==node.number)]
tt<-splitTree(tree,list(node=node.number,bp=position))
p<-tt[[1]]
d<-tt[[2]]
tip<-if(length(which(p$tip.label=="NA"))>0) "NA" else p$tip.label[which(p$tip.label%in%tree$node.label)]
p<-root(p,outgroup=tip,resolve.root=T)
bb<-which(p$tip.label==tip)
p$tip.label[bb]<-"NA"
ee<-p$edge.length[which(p$edge[,2]==bb)]
p$edge.length[which(p$edge[,2]==bb)]<-0
cc<-p$edge[which(p$edge[,2]==bb),1]
dd<-setdiff(p$edge[which(p$edge[,1]==cc),2],bb)
p$edge.length[which(p$edge[,2]==dd)]<-p$edge.length[which(p$edge[,2]==dd)]+ee
obj<-paste.tree(p,d)
if(interactive) plotTree(obj,...)
obj
}
## function to add an arrow pointing to a tip or node in the tree
## written by Liam J. Revell 2014, 2017
add.arrow<-function(tree=NULL,tip,...){
lastPP<-get("last_plot.phylo",envir=.PlotPhyloEnv)
if(!is.null(tree)){
if(inherits(tree,"contMap")) tree<-tree$tree
else if(inherits(tree,"densityMap")) tree<-tree$tree
}
if(is.numeric(tip)){
ii<-tip
if(!is.null(tree)&&ii<=length(tree$tip.label)) tip<-tree$tip.label[ii]
else tip<-""
} else if(is.character(tip)&&!is.null(tree)) ii<-which(tree$tip.label==tip)
if(hasArg(offset)) offset<-list(...)$offset
else offset<-1
strw<-lastPP$cex*(strwidth(tip)+offset*mean(strwidth(c(LETTERS,letters))))
if(hasArg(arrl)) arrl<-list(...)$arrl
else {
if(lastPP$type=="fan") arrl<-0.3*max(lastPP$xx)
else if(lastPP$type=="phylogram") arrl<-0.15*max(lastPP$xx)
}
if(hasArg(hedl)) hedl<-list(...)$hedl
else hedl<-arrl/3
if(hasArg(angle)) angle<-list(...)$angle
else angle<-45
arra<-angle*pi/180
asp<-if(lastPP$type=="fan") 1 else (par()$usr[4]-par()$usr[3])/(par()$usr[2]-par()$usr[1])
if(hasArg(col)) col<-list(...)$col
else col<-"black"
if(hasArg(lwd)) lwd<-list(...)$lwd
else lwd<-2
if(lastPP$type=="fan") theta<-atan2(lastPP$yy[ii],lastPP$xx[ii])
else if(lastPP$type=="phylogram") theta<-0
segments(x0=lastPP$xx[ii]+cos(theta)*(strw+arrl),
y0=lastPP$yy[ii]+sin(theta)*(strw+arrl),
x1=lastPP$xx[ii]+cos(theta)*strw,
y1=lastPP$yy[ii]+sin(theta)*strw,
col=col,lwd=lwd,lend="round")
segments(x0=lastPP$xx[ii]+cos(theta)*strw+cos(theta+arra/2)*hedl,
y0=lastPP$yy[ii]+sin(theta)*strw+sin(theta+arra/2)*hedl*asp,
x1=lastPP$xx[ii]+cos(theta)*strw,
y1=lastPP$yy[ii]+sin(theta)*strw,
col=col,lwd=lwd,lend="round")
segments(x0=lastPP$xx[ii]+cos(theta)*strw+cos(theta-arra/2)*hedl,
y0=lastPP$yy[ii]+sin(theta)*strw+sin(theta-arra/2)*hedl*asp,
x1=lastPP$xx[ii]+cos(theta)*strw,
y1=lastPP$yy[ii]+sin(theta)*strw,
col=col,lwd=lwd,lend="round")
invisible(list(x0=lastPP$xx[ii]+cos(theta)*(strw+arrl),
y0=lastPP$yy[ii]+sin(theta)*(strw+arrl),
x1=lastPP$xx[ii]+cos(theta)*strw,
y1=lastPP$yy[ii]+sin(theta)*strw))
}
## function to ladderize phylogeny with mapped discrete character
## written by Liam J. Revell 2014, 2015
ladderize.simmap<-function(tree,right=TRUE){
if(!inherits(tree,"phylo")) stop("tree should be an object of class \"phylo\".")
obj<-read.tree(text=write.tree(ladderize(tree,right=right)))
rN<-Ntip(obj)+1
T<-cbind(1:Ntip(obj),sapply(obj$tip.label,function(x,y) which(y==x),y=tree$tip.label))
N<-matchNodes(obj,tree)
M<-rbind(T,N[N[,1]!=rN,])
ii<-sapply(M[,1],function(x,y) which(y==x),y=obj$edge[,2])
jj<-sapply(M[,2],function(x,y) which(y==x),y=tree$edge[,2])
obj$maps<-vector(length=nrow(tree$edge),mode="list")
obj$mapped.edge<-matrix(NA,nrow(tree$edge),ncol(tree$mapped.edge),
dimnames=list(apply(tree$edge,1,paste,collapse=","),
colnames(tree$mapped.edge)))
if(!is.null(tree$states))
obj$states<-tree$states[sapply(obj$tip.label,function(x,y) which(y==x),y=tree$tip.label)]
if(!is.null(tree$node.states)) obj$node.states<-matrix(NA,nrow(tree$edge),2)
for(i in 1:length(ii)){
obj$maps[[ii[i]]]<-tree$maps[[jj[i]]]
obj$mapped.edge[ii[i],]<-tree$mapped.edge[jj[i],]
if(!is.null(tree$node.states)) obj$node.states[ii[i],]<-tree$node.states[jj[i],]
}
obj
}
## for backward compatibility
repPhylo<-function(tree,times) rep(tree,times)
## S3 method rep for objects of class "phylo" and "multiPhylo"
## written by Liam J. Revell 2014
rep.phylo<-function(x,...){
if(hasArg(times)) times<-list(...)$times
else times<-(...)[[1]]
for(i in 1:times) obj<-if(i==1) x else if(i==2) c(obj,x) else c(obj,list(x))
class(obj)<-"multiPhylo"
obj
}
rep.multiPhylo<-function(x,...){
if(hasArg(times)) times<-list(...)$times
else times<-(...)[[1]]
for(i in 1:times) obj<-if(i==1) x else if(i>=2) c(obj,x)
class(obj)<-"multiPhylo"
obj
}
## function to rescale simmap style trees
## written by Liam J. Revell 2012, 2013, 2014, 2015, 2017
rescaleSimmap<-function(tree,...){
if(inherits(tree,"multiPhylo")){
cls<-class(tree)
trees<-unclass(tree)
trees<-lapply(trees,rescaleSimmap,...)
class(trees)<-cls
return(trees)
} else if(inherits(tree,"phylo")){
if(hasArg(lambda)) lambda<-list(...)$lambda
else lambda<-1
if(hasArg(totalDepth)) depth<-totalDepth<-list(...)$totalDepth
else if(hasArg(depth)) depth<-totalDepth<-list(...)$depth
else depth<-totalDepth<-max(nodeHeights(tree))
if(lambda!=1){
e<-lambdaTree(tree,lambda)$edge.length/tree$edge.length
tree$edge.length<-tree$edge.length*e
tree$maps<-mapply(function(x,y) x*y,tree$maps,e)
tree$mapped.edge<-tree$mapped.edge*matrix(rep(e,ncol(tree$mapped.edge)),length(e),ncol(tree$mapped.edge))
}
if(depth!=max(nodeHeights(tree))){
h<-max(nodeHeights(tree))
s<-depth/h
tree$edge.length<-tree$edge.length*s
tree$maps<-lapply(tree$maps,"*",s)
tree$mapped.edge<-tree$mapped.edge*s
}
return(tree)
} else message("tree should be an object of class \"phylo\" or \"multiPhylo\"")
}
## function to drop one or more tips from a tree but retain all ancestral nodes as singletons