-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathfossilBM_lib.R
1590 lines (1344 loc) · 52.3 KB
/
fossilBM_lib.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
library(scales)
require(phytools)
library(geiger)
library(adephylo)
read_and_transform_data <- function(treefile="", datafile="", tree_obj="", data_obj="",
rm_extinct=FALSE, tindex=1, drop_na=FALSE,
log_trait_data=0, rescale_trait_data=1,root_calibration=c(0,100),
partition_file="",zero_br=0, dist_from_the_root=c(),
state_tbl=c(), z_tranform=FALSE){
if (treefile != ""){
t<- read.nexus(treefile)
}
if (class(tree_obj)=="phylo") {
t <- tree_obj
t$edge.length <- t$edge.length + zero_br
original_simulated_tree <-t
name_tag=""
}
if (class(tree_obj) == "multiPhylo") {
t <- tree_obj[[tindex]]
original_simulated_tree <-t
t$edge.length <- t$edge.length + zero_br
name_tag=paste("_tree_",tindex, sep="")
}
#
# if (tree_obj[1] != ""){
# t = tree_obj
# t$edge.length <- t$edge.length + zero_br
# name_tag=""
# }
if (rm_extinct) {
name_tag = paste(name_tag,"_noFossil_",sep="")
print("Not using BMT and removing fossils")
useBMT=FALSE
fossil_tips <- setdiff(t$tip.label, getExtant(t))
extant_tree <- drop.tip(t, fossil_tips)
t<- extant_tree
}
fbm_obj = NULL
if (datafile != ""){
trait <- read.table(datafile, header=F,row.names=1)
}else{
trait = data_obj
}
if (drop_na){
trait <- na.omit(trait)
}
treetrait <- treedata(t,trait) # match trait data and phylogeny
tree <- treetrait$phy
tree$edge.length [which(tree$edge.length==0) ]<- 0.00000001
fbm_obj$tree <- tree
if (log_trait_data==10){
data_dataframe <- log10(treetrait$data)
} else if (log_trait_data==1){
data_dataframe <- log(treetrait$data)
} else{
data_dataframe <- treetrait$data
}
data <- as.vector(data_dataframe)
data <- data * rescale_trait_data
names(data)<- rownames(data_dataframe)
fbm_obj$data <- data
fbm_obj$ntips <- tree$Nnode+1
fbm_obj$D <- build_table(tree, fbm_obj$ntips,fbm_obj$data)
BR <- branching.times(tree) # sorted from root to most recent
if (length(dist_from_the_root) == 0){
fbm_obj$dist_from_the_root <- c(distRoot(fbm_obj$tree,tips="all",method =c( "patristic")), max(BR)-BR)
}else{
fbm_obj$dist_from_the_root = dist_from_the_root
}
fbm_obj$dist_from_midpoint <- fbm_obj$dist_from_the_root - 0.5*max(fbm_obj$dist_from_the_root)
fbm_obj$prior_tbl <- get_calibration_tbl(fbm_obj$D,root_calibration)
fbm_obj$PartitionFile <- partition_file
fbm_obj$trait_rescaling <- rescale_trait_data
fbm_obj$StateTbl = state_tbl
if (z_tranform){
fbm_obj$original_data <- fbm_obj$data
fbm_obj$z_sd <- sd(fbm_obj$data, na.rm=T)
fbm_obj$data <- fbm_obj$data / fbm_obj$z_sd
fbm_obj$z_mean <- mean(fbm_obj$data, na.rm=T)
fbm_obj$data <- fbm_obj$data - fbm_obj$z_mean
}
return(fbm_obj)
}
drop_extinct <- function(tree, rho=0.25){
dropRandomTaxa = 0.25
ex_tips <- getExtinct(tree)
rm_taxa= sample(ex_tips,size=round((1-rho) * length(ex_tips)))
tree <- drop.tip(tree, rm_taxa)
return(tree)
}
update_multiplier_proposal <- function(i,d){
u = runif(1,0,1)
l = 2*log(d)
m = exp(l*(u-0.5))
ii = i * m
U=log(m)
#if (ii>10){
# return(c(i,0))
#}else{return(c(ii, U))}
return(c(ii, U))
}
fN<-function(xa, xb, vpa, vpb, sigma2) {
#the normal density. Sigma2 is the variance. Same as log(dnorm(xa-xb, 0, sqrt(sigma * sigma * (vpa + vpb))))
return( dnorm((xa-xb),mean=0,sd= sqrt(sigma2 * (vpa + vpb)), log=T) )
}
fN2<-function(xa, xb, vpa, vpb, sigma2_a,sigma2_b, anc) {
#same as fN but with a known ancestor instead of xa-xb
return(dnorm(xa, mean=anc, sd= sqrt(vpa*sigma2_a),log=T) + dnorm(xb, mean=anc, sd= sqrt(vpb*sigma2_b),log=T) )
}
newlnLike <- function(fbm_obj, vector_tip_root_nodes_values, sigma2,mu0, a0) {
tree <- fbm_obj$tree
ntips <- fbm_obj$ntips
D <- fbm_obj$D
root_dist <- as.numeric(fbm_obj$dist_from_midpoint)
names(root_dist) <- names(vector_tip_root_nodes_values)
vec_values = vector_tip_root_nodes_values
anc_ind_v <- D[,1]
a_ind_v <- D[,2]
b_ind_v <- D[,3]
vpa_v <- D[,4]
vpb_v <- D[,5]
anc_v <- vec_values[anc_ind_v]
a_v <- vec_values[a_ind_v]
b_v <- vec_values[b_ind_v]
a_ind_v[a_ind_v>ntips] =a_ind_v[a_ind_v>ntips]-1
b_ind_v[b_ind_v>ntips] =b_ind_v[b_ind_v>ntips]-1
L1 = dnorm(a_v, mean=(anc_v+mu0[a_ind_v]*vpa_v + a0[a_ind_v]*vpa_v*root_dist[a_ind_v]), sd= sqrt(vpa_v*sigma2[a_ind_v]),log=T)
L2 = dnorm(b_v, mean=(anc_v+mu0[b_ind_v]*vpb_v + a0[b_ind_v]*vpb_v*root_dist[b_ind_v]), sd= sqrt(vpb_v*sigma2[b_ind_v]),log=T)
L = L1+L2
return(L)
}
phylo_imputation <-function(tree, vector_tip_root_nodes_values, sigma2,D,mu0,a0,ind_NAtaxa_in_D,anc_of_NAtaxa,brl_NAtaxa_in_D,root_dist,get_expected=0) {
vec_values = vector_tip_root_nodes_values
anc_v <- vec_values[anc_of_NAtaxa] # anc value
if (get_expected==0){
new_val = rnorm(length(brl_NAtaxa_in_D), mean=(anc_v+mu0[ind_NAtaxa_in_D]*brl_NAtaxa_in_D + a0[ind_NAtaxa_in_D]*root_dist[ind_NAtaxa_in_D]*brl_NAtaxa_in_D), sd= sqrt(brl_NAtaxa_in_D*sigma2[ind_NAtaxa_in_D]))
}else{
new_val = anc_v + mu0[ind_NAtaxa_in_D]*brl_NAtaxa_in_D + a0[ind_NAtaxa_in_D]*root_dist[ind_NAtaxa_in_D]*brl_NAtaxa_in_D
}
# print(c("mean", (anc_v+mu0[ind_NAtaxa_in_D]*brl_NAtaxa_in_D), "std",sqrt(brl_NAtaxa_in_D*sigma2[ind_NAtaxa_in_D]),new_val))
# print(new_val)
return(new_val)
}
build_table <- function (tree,ntips,data){
tree.edge.ordered<-tree$edge[order(tree$edge[,2]),]
# the root is at ntips+1
root<-ntips+1
# the table with ancestor, the two descendants and the two branch length
table.tree<-matrix(NA,ntips-1,5)
colnames(table.tree)<-c("ancestor","descendant1","descendant2","branch.length1", "branch.length2")
#contains the root and all the nodes
table.tree[,1]<-c(ntips+1,tree.edge.ordered[(ntips+1):(ntips+ntips-2),2])
for(i in 1:dim(table.tree)[1]){
table.tree[i,c("descendant1","descendant2")] <- tree$edge[which(tree$edge[,1]==table.tree[i,1]),2]
table.tree[i,c("branch.length1","branch.length2")] <- tree$edge.length[which(tree$edge[,1]==table.tree[i,1])]
}
return(table.tree)
}
get_calibration_tbl <- function (D,root_calibration){
calibration_tbl =NULL
for (i in 1:dim(D)[1]){
calibration_tbl = rbind(calibration_tbl,c(0,100))
}
row.names(calibration_tbl)=D[,1]
calibration_tbl[1,] = root_calibration
return(calibration_tbl)
}
################ RUN GIBBS FUNCTIONS
get_joint_mu_s2 <- function (mu_f,s2_f,mu_g,s2_g){
s2_fg = (s2_f*s2_g)/(s2_f+s2_g)
mu_fg = (mu_f/s2_f + mu_g/s2_g) * s2_fg
return(c(mu_fg,s2_fg))
}
get_mu_t <- function(t, x, mu0, b, a0=0){
return( a0*t*x + mu0*x +b )
}
runGibbs <- function(fbm_obj,sigma2, vector_tip_root_nodes_values,mu0, a0,get_expected=0) {
ntips <- fbm_obj$ntips
D <- fbm_obj$D
prior_tbl <- fbm_obj$prior_tbl
#prior_tbl = calc_prior_dist_root_calibration(D,sigma2)
root_dist <- fbm_obj$dist_from_midpoint
vec_values = vector_tip_root_nodes_values
# loop over Johnatan's tbl from most recent to root
for (i in dim(D)[1]:2){
anc_ind <- D[i,1];
a_ind <- D[i,2]; # index of descendants
b_ind <- D[i,3]; # index of descendants
vpa <- D[i,4]; # br length
vpb <- D[i,5]; # br length
anc = vec_values[anc_ind]
a = vec_values[a_ind]
b = vec_values[b_ind]
# calibration prior
calibrated_prior_mu = prior_tbl[which(rownames(prior_tbl)==anc_ind),1]
calibrated_prior_s2 = prior_tbl[which(rownames(prior_tbl)==anc_ind),2]
if (a_ind>ntips){
sig_a_ind=a_ind-1 # because no sig2 value for root
}else{sig_a_ind=a_ind}
if (b_ind>ntips){
sig_b_ind=b_ind-1
}else{sig_b_ind=b_ind}
#desc_lik = get_joint_mu_s2((a-vpa*mu0[sig_a_ind]), (vpa)*sigma2[sig_a_ind], (b-vpb*mu0[sig_b_ind]), (vpb)*sigma2[sig_b_ind])
m1 <- a - (vpa*mu0[sig_a_ind] + a0[sig_a_ind]*vpa*root_dist[a_ind])
s1 <- (vpa)*sigma2[sig_a_ind]
m2 <- b - (vpb*mu0[sig_b_ind] + a0[sig_b_ind]*vpb*root_dist[b_ind])
s2 <- (vpb)*sigma2[sig_b_ind]
desc_lik = get_joint_mu_s2(m1, s1, m2, s2)
prior_prm = prior_tbl[which(rownames(prior_tbl)==anc_ind),]
# lik from (stem) ancestral state
if (i>1){
if (anc_ind %in% D[,2]){
stem_ind = D[which(D[,2]==anc_ind),1]
stem_brl = D[which(D[,2]==anc_ind),4]
}
else{
stem_ind = D[which(D[,3]==anc_ind),1]
stem_brl = D[which(D[,3]==anc_ind),5]
}
sig_stem_ind=stem_ind-1
stem_val = vec_values[stem_ind]
stem_lik_m1 <- stem_val + stem_brl*mu0[sig_stem_ind] + a0[sig_stem_ind]*stem_brl*root_dist[anc_ind]
stem_lik_s1 <- stem_brl * sigma2[sig_stem_ind]
lik_val = get_joint_mu_s2(stem_lik_m1,stem_lik_s1,desc_lik[1],desc_lik[2])
post_prm= lik_val #get_joint_mu_s2(lik_val[1],lik_val[2],prior_prm[1], prior_prm[2])
if (get_expected==1){
vec_values[anc_ind] = post_prm[1]
}else{
vec_values[anc_ind] = rnorm(1, mean=post_prm[1], sd=sqrt(post_prm[2]))
}
}
}
return(vec_values[D[,1]] )
}
calc_prior <- function(sig2, a, y, mu0, delta_a0, prior_tbl, rate_sig2, sd_mu0) {
prior_sig2 = sum(dexp(sig2, rate_sig2, log = TRUE) ) #sum(dgamma(sig2, 2,1, log = TRUE) )
prior_root = sum(dnorm(c(a), mean = prior_tbl[,1], sd = prior_tbl[,2], log = T))
prior_mu0 = sum(dnorm(mu0[mu0 != 0], mean = 0, sd = sd_mu0, log = T)) # ignore mu0 constrained to 0
prior_da0 = sum(dnorm(delta_a0, mean = 0, sd = 1, log = T))
return(prior_sig2+prior_root+prior_mu0+prior_da0)
}
set_model_partitions <- function(fbm_obj,ind_sig2,ind_mu0){
# ind_sig2 <- rep(1, fbm_obj$tree$Nnode * 2 - 1)
# ind_mu0 <- rep(1, fbm_obj$tree$Nnode * 2 - 1)
tbl = read.table(fbm_obj$PartitionFile,h=F,stringsAsFactors=F,fill=T)
for (i in 1:dim(tbl)[1]){
tx_tmp = as.vector(unlist(tbl[i,]))
tx = tx_tmp[tx_tmp != ""]
mrca = getMRCA(fbm_obj$tree, tx)
desc = getDescendants(fbm_obj$tree, mrca)
desc[desc > fbm_obj$ntips] = desc[desc > fbm_obj$ntips] - 1
ind_sig2[desc] = i+1
ind_mu0[desc] = i+1
}
sig2 <- rep(0.05, 1+dim(tbl)[1])
mu0 <- rep(0, 1+dim(tbl)[1])
a0 <- rep(0, 1+dim(tbl)[1])
return( list(sig2, mu0, a0, ind_sig2, ind_mu0) )
}
set_model_trait_partitions <- function(fbm_obj){
ind_mu0 <- fbm_obj$StateTbl[,2]
mu0 <- rep(0, length(unique(ind_mu0)))
a0 <- rep(0, length(unique(ind_mu0)))
return( list(mu0, a0, ind_mu0) )
}
set_model_trait_partitions_sigma <- function(fbm_obj){
ind_sig2 <- fbm_obj$StateTbl[,2]
sig2 <- rep(0.05, length(unique(ind_sig2)))
return( list(sig2, ind_sig2) )
}
################ BDMCMC SAMPLER
calc_rel_prob <- function(log_lik){
rel_prob=exp(log_lik-max(log_lik))
return (rel_prob/sum(rel_prob) )
}
random_choice_P <-function(vector){
probDeath=cumsum(vector/sum(vector)) # cumulative prob (used to randomly sample one
r=runif(1,0,1) # parameter based on its deathRate)
probDeath=sort(append(probDeath, r))
ind=which(probDeath==r)
return (c(vector[ind], ind))
}
calc_deathRates <- function (fbm_obj, trait_states, sig2, ind_sig, mu0, ind_mu0, a0,IND_edge,desc_index_list,death_sig2=1){
tree <- fbm_obj$tree
D <- fbm_obj$D
ntips <- fbm_obj$ntips
list_deathrates=c(0) # can't kill first
y_temp = runGibbs(fbm_obj,sig2[ind_sig], trait_states,mu0[ind_mu0],a0[ind_mu0],get_expected=1)
y_temp_FIRST = y_temp
a= y_temp[1]
y= y_temp[-1]
trait_states_ = c(trait_states[1:length(tree$tip.label)], a, y)
current_lik = sum(newlnLike(fbm_obj, trait_states_, sig2[ind_sig],mu0[ind_mu0],a0[ind_mu0]))
if (death_sig2==1){
N=length(unique(ind_sig))
}else{N=length(unique(ind_mu0))}
for (i in 2:N){
if (death_sig2==1){
multi_ind = ind_sig
}else{
multi_ind = ind_mu0
}
multi_ind_edge = multi_ind[IND_edge]
# get edges with index i
Yi = which(multi_ind_edge==i)
crown_node_ind_i = min(tree$edge[Yi,1])
if (crown_node_ind_i==(ntips+1)){ # ROOT
ind_of_ancestor=1
} else{
ind_of_ancestor= multi_ind_edge[which(tree$edge[,2]==crown_node_ind_i)]
}
if (death_sig2==1){
new_ind_sig = ind_sig
new_ind_sig[new_ind_sig==i] = ind_of_ancestor
rates_temp= sig2[new_ind_sig]
mu0_temp = mu0[ind_mu0]
a0_temp = a0[ind_mu0]
}else{
new_ind_mu0 = ind_mu0
new_ind_mu0[new_ind_mu0==i] = ind_of_ancestor
rates_temp= sig2[ind_sig]
mu0_temp = mu0[new_ind_mu0]
a0_temp = a0[new_ind_mu0]
}
y_temp = runGibbs(fbm_obj,rates_temp, trait_states,mu0_temp,a0_temp,get_expected=1)
a= y_temp[1]
y= y_temp[-1]
trait_states_temp = c(trait_states[1:length(tree$tip.label)], a, y)
list_deathrates[i] = sum(newlnLike(fbm_obj, trait_states_temp, rates_temp,mu0_temp,a0_temp))
}
list_deathrates = exp(list_deathrates - current_lik)
#print(c(current_lik, list_deathrates))
list_deathrates[1] = 0
return(list_deathrates)
}
run_BDMCMC <- function(fbm_obj, trait_states, sig2, ind_sig, mu0, ind_mu0, a0 ,IND_edge,new_ind,desc_index_list,death_sig2=1){
tree <- fbm_obj$tree
D <- fbm_obj$D
ntips <- fbm_obj$ntips
init_lik = sum(newlnLike(fbm_obj, trait_states, sig2[ind_sig],mu0[ind_mu0],a0[ind_mu0]))
cont_time=0
len_cont_time=1
birthRate=1
# cat("\n\nSTART\n")
# print(c("initial rates",sig2))
while (cont_time<len_cont_time){
if (death_sig2==1){
deathRate = rep(0, length(unique(ind_sig)))
n_likBD = rep(0, length(unique(ind_sig)))
}else{
deathRate = rep(0, length(unique(ind_mu0)))
n_likBD = rep(0, length(unique(ind_mu0)))
}
if (length(unique(ind_sig))>1 && death_sig2==1){
deathRate = calc_deathRates(fbm_obj, trait_states, sig2, ind_sig, mu0, ind_mu0,a0, IND_edge,desc_index_list,1)
}else if (length(unique(ind_mu0))>1 && death_sig2==2){
deathRate = calc_deathRates(fbm_obj, trait_states, sig2, ind_sig, mu0, ind_mu0,a0, IND_edge,desc_index_list,2)
}
deltaRate=sum(deathRate)
# print(deltaRate)
cont_time = cont_time + rexp(1, rate = min((deltaRate+birthRate), 100000))
if ((deltaRate+birthRate)>100 && cont_time>len_cont_time){
cont_time <- len_cont_time
}
if (cont_time>len_cont_time){
"pass"
}else{
Pr_birth= birthRate/(birthRate+deltaRate)
Pr_death= 1-Pr_birth
if (runif(1)<Pr_birth){ # ADD PARAMETER
rates_temp= sig2[ind_sig]
trend_temp= mu0[ind_mu0]
if (death_sig2==1){
n_ind = sample(1:length(ind_sig),1)
multi_ind = ind_sig
}else{
n_ind = sample(1:length(ind_mu0),1)
multi_ind = ind_mu0
}
multi_ind_edge = multi_ind[IND_edge]
multi_ind_new = multi_ind_edge
# index that is being affected
split_ind = multi_ind_new[n_ind]
ind_desc = desc_index_list[[n_ind]]
if (length(ind_desc) ==1){ # NO shifts allowed on single branches (tips)
"pass"
}else{
if (death_sig2==1){
for (j in ind_desc){
if (multi_ind_new[j]==split_ind){
multi_ind_new[j] = max(ind_sig)+1
}
}
# BDMCMC PROPOSAL
sig2_original = sig2
ind_sig_original = ind_sig
sig2=c(sig2,rexp(1,0.5)) # sample from rate prior
#sig2=c(sig2,sig2[1]) # sample from rate prior
# ind_sig in the original order
ind_sig=multi_ind_new[new_ind]
if (length(sig2)>length(unique(ind_sig))){
# the new index overlaps completely with the previous
# remove unused sig2
sig2= sig2_original
ind_sig= ind_sig_original
}
}else{
for (j in ind_desc){
if (multi_ind_new[j]==split_ind){multi_ind_new[j] = max(ind_mu0)+1}
}
# BDMCMC PROPOSAL
mu0_original = mu0
ind_mu0_original = ind_mu0
a0_original = a0
mu0=c(mu0,rnorm(1,0,1)) # sample from rate prior
a0 =c(a0,rnorm(1,0,0.01))
# ind_sig in the original order
ind_mu0=multi_ind_new[new_ind]
if (length(mu0)>length(unique(ind_mu0))){
# the new index overlaps completely with the previous
# remove unused mu0
mu0= mu0_original
ind_mu0= ind_mu0_original
a0 = a0_original
}
}
}
}else{ # REMOVE PARAMETER
i=random_choice_P(deathRate)[2]
if (death_sig2==1){
multi_ind = ind_sig
}else{
multi_ind = ind_mu0
}
multi_ind_edge = multi_ind[IND_edge]
# get edges with index i
Y = which(multi_ind_edge==i)
#__ cat("\ndead edge:",Y, i)
crown_node_ind_i = min(tree$edge[Y,1])
if (crown_node_ind_i<Inf && crown_node_ind_i>-Inf){
"ok"
}else{
cat("\ndead crown:",crown_node_ind_i, i,"\n")
cat("\ndead edge:",Y,"ind:" ,i,"\nY:",tree$edge[Y,1])
}
if (crown_node_ind_i==(ntips+1)){ # ROOT
ind_sig_of_ancestor_i=1
}else{
ind_sig_of_ancestor_i= multi_ind_edge[which(tree$edge[,2]==crown_node_ind_i)]
}
if (death_sig2==1){
# update indexes
new_ind_sig = ind_sig
new_ind_sig[new_ind_sig==i] = ind_sig_of_ancestor_i
ind_sig = new_ind_sig
# remove unused sig2
sig2 = sig2[-i]
# rescale indexes
ind_sig[ind_sig>i]=ind_sig[ind_sig>i]-1
}else{
# update indexes
new_ind_mu0 = ind_mu0
new_ind_mu0[new_ind_mu0==i] = ind_sig_of_ancestor_i
ind_mu0 = new_ind_mu0
# remove unused sig2
mu0 = mu0[-i]
a0 = a0[-i]
# rescale indexes
ind_mu0[ind_mu0>i]=ind_mu0[ind_mu0>i]-1
}
}
}
}
#__ print(list(sig2,ind_sig))
return (list(sig2,ind_sig,mu0,a0,ind_mu0))
}
################################## START MCMC ###################################
run_mcmc <- function (fbm_obj,ngen = 100000, control = list(),useVCV=F, sample_f=250,
logfile="mcmc.log",update_sig_freq=0.5,dynamicPlot = F,
bdmcmc_freq=0.75,useTrend=T,print_freq=100,constRate=F,linTrend=F,
per_branch_parameters=TRUE, log_anc_states=TRUE,
update_mu0=c(), estimate_HP=FALSE, estimate_HPmu0=FALSE, rate_trend_hp=1,
init_mu0=c(), verbose=FALSE){
tree <- fbm_obj$tree
x <- fbm_obj$data
D <- fbm_obj$D
prior_tbl <- fbm_obj$prior_tbl
ntips <- fbm_obj$ntips
PartitionFile <- fbm_obj$PartitionFile
TE=as.matrix(tree$edge)
a <- mean(fbm_obj$data,na.rm=T)
y <- rep(a, tree$Nnode - 1)
sig2 <- c(0.05)
mu0 <- c(0)
a0 <- c(0)
ind_sig2 <- rep(1, length(c(x, y)))
ind_mu0 <- rep(1, length(c(x, y)))
mean_sig <- rep(0, length(c(x, y)))
mean_anc <- rep(0, length(c(a, y)))
#_ ngen = 2000
#_ control = list()
#_ useVCV=F
#_ sample_f=250
#_ logfile="mcmc.log"
#_ update_sig_freq=0.5
#_ dynamicPlot = F
#_ bdmcmc_freq=0.8
#_ useTrend=T
#_ print_freq=100
#_ constRate=F
#_ linTrend=F
if (dynamicPlot == T){dev.new()}
if (PartitionFile != ""){
bdmcmc_freq = 0
res_part <- set_model_partitions(fbm_obj,ind_sig2,ind_mu0)
sig2 <- res_part[[1]]
mu0 <- res_part[[2]]
a0 <- res_part[[3]]
ind_sig2 <- res_part[[4]]
ind_mu0 <- res_part[[5]]
part_ids <- sort(unique(ind_sig2))
part_mu_ids <- part_ids
}
if (length(fbm_obj$StateTbl) > 0){
bdmcmc_freq = 0
r_tmp <- set_model_trait_partitions(fbm_obj)
mu0 <- r_tmp[[1]]
# mu0 = c(0, 0.1, 0.2, 0.3)
a0 <- r_tmp[[2]]
ind_mu0 <- r_tmp[[3]]
part_mu_ids <- sort(unique(ind_mu0))
print(head(ind_mu0))
print(mu0)
if (PartitionFile == ""){
r_tmp <- set_model_trait_partitions_sigma(fbm_obj)
sig2 <- r_tmp[[1]]
ind_sig2 <- r_tmp[[2]]
part_ids <- sort(unique(ind_sig2))
# print(c("part_ids", part_ids))
}
PartitionFile = "TraitPartition"
}
if (length(init_mu0) > 0){
mu0 = init_mu0
}
#names(ind_sig2) = c(names(x), D[-1,1])
if (verbose){
print(table(ind_sig2))
print(table(ind_mu0))
}
x_tmp = as.vector(table(ind_mu0))
scaler_w = 1/(1 + log(x_tmp- min(x_tmp) +1))
std_mu0 <- sd(fbm_obj$data, na.rm=T)*0.025 * scaler_w
rate_sig2 <- 0.5
# print(c("std_mu0", std_mu0))
fbm_obj$ind_sig2 = ind_sig2
fbm_obj$ind_mu0 = ind_mu0
x <- x[tree$tip.label]
if (is.null(names(y))) {
names(y) <- length(tree$tip) + 2:tree$Nnode
}else {y[as.character(length(tree$tip) + 2:tree$Nnode)]}
# list NA taxa
ind_NA_taxa = which(is.na(x))
ind_NAtaxa_in_D = c()
brl_NAtaxa_in_D = c()
anc_node_of_NAtaxa = c()
anc_state_anc_node_of_NAtaxa = c()
if (per_branch_parameters){
out_tmp = c("it", "posterior","likelihood","prior", "sig2", "mu0","a0","K_sig2","K_mu0",
paste("sig2", 1:length(TE[,1]),sep="_"),paste("mu0", 1:length(TE[,1]),sep="_"),
paste("a0", 1:length(TE[,1]),sep="_"))
}else{
out_tmp = c("it", "posterior","likelihood","prior", "sig2", "mu0","a0")
if (PartitionFile != ""){
out_tmp = c(out_tmp,
paste("sig2", part_ids, sep="_"),paste("mu0", part_mu_ids,sep="_"),
paste("a0", part_mu_ids,sep="_"))
}
}
if (log_anc_states){
out_tmp = c(out_tmp, paste("anc",D[,1],sep="_"), tree$tip.label[ind_NA_taxa])
}else{
out_tmp = c(out_tmp, "root", tree$tip.label[ind_NA_taxa])
}
if (estimate_HP){
out_tmp <- c(out_tmp, "sig2_hp")
}
if (estimate_HPmu0){
out_tmp <- c(out_tmp, "mu0_hp")
}
if (logfile != 0){
cat(c(out_tmp, "\n"), sep="\t", file=logfile, append=F)
}
for (tax in 1:length(ind_NA_taxa)){
ind_NAtaxa_in_D = c(ind_NAtaxa_in_D, which(D[,2] == ind_NA_taxa[tax]), which(D[,3] == ind_NA_taxa[tax]))
brl_NAtaxa_in_D = c(brl_NAtaxa_in_D, D[which(D[,2] == ind_NA_taxa[tax]),4], D[which(D[,3] == ind_NA_taxa[tax]),5])
anc_node_of_NAtaxa = c(anc_node_of_NAtaxa, D[ind_NAtaxa_in_D[tax],1])
anc_state_anc_node_of_NAtaxa = c(anc_state_anc_node_of_NAtaxa, y[which(as.numeric(names(y)) == anc_node_of_NAtaxa[tax])])
}
# init NAs values
# phylo imputation
x[ind_NA_taxa] = NA
vector_tip_root_nodes_values = c(x, a, y)
x_imputed = phylo_imputation(tree, vector_tip_root_nodes_values, sig2[ind_sig2],D,mu0[ind_mu0],a0[ind_mu0],ind_NAtaxa_in_D,
anc_node_of_NAtaxa,brl_NAtaxa_in_D,fbm_obj$dist_from_midpoint,get_expected=1)
x[ind_NA_taxa] = x_imputed
fbm_obj$data <- x
y = runGibbs(fbm_obj,sig2[ind_sig2], c(x, a, y),mu0[ind_mu0],a0[ind_mu0],get_expected=1)[-1]
L <- newlnLike(fbm_obj, c(x, a, y), sig2[ind_sig2],mu0[ind_mu0],a0[ind_mu0])
# print(c("LIKELIHOOD:", sum(L), length(L), a, y[1:3], sig2, mu0,sum(ind_sig2), sum(ind_mu0)))
sd_mu0 = 0.1
Pr <- calc_prior(sig2, a, y,mu0, a0, prior_tbl, rate_sig2, sd_mu0)
if (estimate_HPmu0){
Pr <- Pr + dexp(sd_mu0, rate_trend_hp, log=T) # add HP probability
}
if (estimate_HP){
Pr <- Pr + dexp(rate_sig2, 1, log=T)
}
# get indexes
IND_edge = c()
for (ind_edge in tree$edge[,2]){
if (ind_edge>ntips){
ind_edge_t=ind_edge-1
}else{ind_edge_t=ind_edge}
IND_edge = append(IND_edge,ind_edge_t)
}
# indexes sorted by edge index
multi_sig = rep(0,length(IND_edge))
names(multi_sig) = 1:length(multi_sig)
multi_sig_edge = multi_sig[IND_edge]
new_ind=order(as.numeric(names(multi_sig_edge)))
# list index descendants
desc_index_list = list()
for (i in 1:length(multi_sig)){
node_ind=tree$edge[i,2]
ind_desc_nodes = getDescendants(tree, node=node_ind)
ind_desc_edges = which(tree$edge[,2]%in% ind_desc_nodes == T)
V = unique(c(i,ind_desc_edges))
desc_index_list[[i]] = unique(c(i,ind_desc_edges))
}
if (length(update_mu0) == 0){
update_mu0 <- 1:length(mu0)
}
# START MCMC
for (i in 1:ngen) {
y.prime = y
L.prime = L
Pr.prime = Pr
a.prime = a
sig2.prime = sig2
mu0.prime = mu0
a0.prime = a0
sd_mu0.prime = sd_mu0
rate_sig2.prime = rate_sig2
gibbs=0
hastings=0
# SCREEN OUTPUT / DYNAMIC PLOTS
if (i %% print_freq==0){
cat(c("\n",i,round(sum(L),2),length(sig2),length(mu0),a0,a0.prime))
}
if (dynamicPlot == T){
mean_sig = rbind(mean_sig,sig2[ind_sig2])
#mean_anc = rbind(mean_anc,c(x,a,y))
mean_anc = rbind(mean_anc,c(a,y))
if (i%%print_f == 0 || i==1) {
cat(c("\n",i,round(c(sum(L),sig2,mu0),2)))
par(mfrow=c(1,2))
start = round(dim(mean_sig)[1]*0.1)
end = dim(mean_sig)[1]
#rates_temp =sig2.prime[ind_sig2]
rates_temp = apply(mean_sig[start:end,], 2, FUN=median)
plot.phylo(tree, edge.width=rates_temp[IND_edge]*3, main="median rates",show.tip.label = F)
rates_temp =sig2.prime[ind_sig2]
plot.phylo(tree, edge.width=rates_temp[IND_edge]*3, main=paste("lik:",round(sum(L),2),
"cat:",length(unique(ind_sig2))),show.tip.label = F)
}
}
j <- (i - 1)%%(tree$Nnode + 1)
rr= runif(2,0,1)
update_sig_freq=0.95
if (rr[1]<update_sig_freq) {
if (rr[2]< 0.33 && i > 50){ # SIG2 UPDATE
s_ind = sample(1:length(sig2),1)
sig2_update <- update_multiplier_proposal(sig2.prime[s_ind],1.05)
sig2.prime[s_ind] = sig2_update[1]
hastings = sig2_update[2]
}
else if (rr[2]<0.66 && useTrend==T){ # MU0 UPDATE
if (length(update_mu0) == 1){
m_ind = update_mu0[1]
}else{
m_ind = sample(update_mu0,1) #<---- ONLY UPDATE thise within update_mu0
}
mu0_update <- mu0[m_ind] + rnorm(n = 1, sd = std_mu0[m_ind])
if (linTrend){
# update diff
# r_diff = mu0[m_ind] - a0[m_ind]
# r_diff_update <- r_diff + rnorm(n = 1, sd = sd(fbm_obj$data, na.rm=T)*0.0005)
# a0_update <- mu0_update - r_diff_update
# print(c(a0[m_ind], a0_update, r_diff_update, r_diff))
a0_update <- a0[m_ind] + rnorm(n = 1, sd = sd(fbm_obj$data, na.rm=T)*0.0005)
a0.prime[m_ind] = a0_update
}
mu0.prime[m_ind] = mu0_update
}
else{ # ROOT STATE
a.prime <- a + rnorm(n = 1, sd = 0.5) #sqrt(con$prop[j + 1]))
if (estimate_HP){
rate_sig2_update <- update_multiplier_proposal(rate_sig2, 1.05)
rate_sig2.prime <- rate_sig2_update[1]
hastings <- hastings + rate_sig2_update[2]
}
if (estimate_HPmu0){
sd_mu0_update <- update_multiplier_proposal(sd_mu0, 1.05)
sd_mu0.prime <- sd_mu0_update[1]
hastings <- hastings + sd_mu0_update[2]
}
}
}
else{
# ANC STATES
#useTrend=F
RUNIF = runif(3,0,1)
if (RUNIF[1]<bdmcmc_freq && i > 100){
trait_states=c(x, a.prime, y.prime)
if (useTrend){
death_sig2=sample(2,1)
}else{death_sig2=1}
if (constRate==T){death_sig2=2}
bdmcmc_list = run_BDMCMC(fbm_obj, trait_states, sig2.prime,ind_sig2, mu0.prime, ind_mu0, a0.prime,
IND_edge,new_ind,desc_index_list,death_sig2)
sig2.prime = bdmcmc_list[[1]]
ind_sig2 = bdmcmc_list[[2]]
mu0.prime = bdmcmc_list[[3]]
a0.prime = bdmcmc_list[[4]]
ind_mu0 = bdmcmc_list[[5]]
#print (ind_mu0)
gibbs=1
} else {
if (runif(1)<0.1){
# phylo imputation
x[ind_NA_taxa] = NA
vector_tip_root_nodes_values = c(x, a.prime, y.prime)
x_imputed = phylo_imputation(tree, vector_tip_root_nodes_values, sig2.prime[ind_sig2],D,mu0.prime[ind_mu0],a0.prime[ind_mu0],
ind_NAtaxa_in_D,anc_node_of_NAtaxa,brl_NAtaxa_in_D,fbm_obj$dist_from_midpoint,get_expected=0)
x[ind_NA_taxa] = x_imputed
fbm_obj$data <- x
gibbs=1
}else{
# gibbs update anc states
vector_tip_root_nodes_values = c(x, a.prime, y.prime)
y_temp = runGibbs(fbm_obj,sig2.prime[ind_sig2], vector_tip_root_nodes_values,mu0.prime[ind_mu0],a0.prime[ind_mu0],get_expected=0)
a.prime= y_temp[1]
y.prime= y_temp[-1]
#x[ind_NA_taxa] = NA
#vector_tip_root_nodes_values = c(x, a.prime, y.prime)
#x_imputed = phylo_imputation(tree, vector_tip_root_nodes_values, sig2.prime[ind_sig2],D,mu0.prime[ind_mu0],a0.prime[ind_mu0],
# ind_NAtaxa_in_D,anc_node_of_NAtaxa,brl_NAtaxa_in_D,fbm_obj$dist_from_midpoint,get_expected=0)
#x[ind_NA_taxa] = x_imputed
#fbm_obj$data <- x
gibbs=1
}
}
}
# calc post
L.prime <- newlnLike(fbm_obj, c(x, a.prime, y.prime), sig2.prime[ind_sig2],mu0.prime[ind_mu0],a0.prime[ind_mu0])
Pr.prime <- calc_prior(sig2.prime, a.prime, y.prime, mu0.prime, a0.prime, prior_tbl, rate_sig2.prime, sd_mu0.prime)
if (estimate_HPmu0){
Pr.prime <- Pr.prime + dexp(sd_mu0.prime,
rate=rate_trend_hp, log=T)
}
if (estimate_HP){
Pr.prime <- Pr.prime + dexp(rate_sig2.prime, 1, log=T)
}
# print( c(sum(L.prime), sum(Pr.prime), sig2.prime, a.prime, mu0.prime, x[ind_NA_taxa], sum(Pr), sum(L)) )
if ( (sum(Pr.prime) + sum(L.prime) - sum(Pr) - sum(L) + hastings) >= log(runif(1,0,1)) || gibbs==1){
y = y.prime
L = L.prime
Pr = Pr.prime
a = a.prime
sig2 = sig2.prime
mu0 = mu0.prime
a0 = a0.prime
sd_mu0 = sd_mu0.prime
rate_sig2 = rate_sig2.prime
}
if (i %% sample_f == 0) {
rates_temp=sig2[ind_sig2]
trends_temp=mu0[ind_mu0]
trend_trends = a0[ind_mu0]
if (log_anc_states){
anc_tmp = c(a, y)
}else{
anc_tmp = c(a)
}
x_imputed_looged = x_imputed
if (estimate_HP){
x_imputed_looged = c(x_imputed_looged, rate_sig2)
}
if (estimate_HPmu0){
x_imputed_looged = c(x_imputed_looged, sd_mu0)
}
if (per_branch_parameters){
if (logfile != 0){
cat(c(i,sum(L)+sum(Pr), sum(L),sum(Pr), mean(rates_temp),mean(trends_temp),mean(trend_trends), length(sig2),length(mu0),
rates_temp[IND_edge],trends_temp[IND_edge],trend_trends[IND_edge], anc_tmp, x_imputed_looged, "\n"),sep="\t", file=logfile, append=T)
}
}else{
if (PartitionFile != ""){
prm_tmp = c(sig2, mu0, a0)
}else{
prm_tmp = c()
}
if (logfile != 0){
cat(c(i,sum(L)+sum(Pr), sum(L),sum(Pr), mean(rates_temp),mean(trends_temp),mean(trend_trends), prm_tmp,
anc_tmp, x_imputed_looged, "\n"),sep="\t", file=logfile, append=T)
}
}
#print(x[ind_NA_taxa])
}
}
return (fbm_obj)
}
################################## END MCMC ###################################
## Modified traitgram
phenogram_invTime<-function(tree,x,fsize=1.0,ftype="reg",colors=NULL,axes=list(),add=FALSE,...){
## get optional arguments
if(hasArg(xlim)) xlim<-list(...)$xlim
else xlim<-NULL
if(hasArg(ylim)) ylim<-list(...)$ylim
else ylim<-NULL
if(hasArg(log)) log<-list(...)$log
else log<-""
if(hasArg(main)) main<-list(...)$main
else main<-NULL
if(hasArg(sub)) sub<-list(...)$sub
else sub<-NULL
if(hasArg(xlab)) xlab<-list(...)$xlab
else xlab<-"time"
if(hasArg(ylab)) ylab<-list(...)$ylab
else ylab<-"phenotype"
if(hasArg(asp)) asp<-list(...)$asp
else asp<-NA
if(hasArg(type)) type<-list(...)$type
else type<-"l"
if(hasArg(lty)) lty<-list(...)$lty
else lty<-1
if(hasArg(lwd)) lwd<-list(...)$lwd
else lwd<-2
if(hasArg(offset)) offset<-list(...)$offset
else offset<-0.2
if(hasArg(offsetFudge)) offsetFudge<-list(...)$offsetFudge
else offsetFudge<-1.37
if(hasArg(digits)) digits<-list(...)$digits
else digits<-2
if(hasArg(nticks)) nticks<-list(...)$nticks
else nticks<-5