-
Notifications
You must be signed in to change notification settings - Fork 2
/
functions_TM_new.R
2275 lines (2006 loc) · 91.4 KB
/
functions_TM_new.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
############################## Functions written for this study #######################################
##Selecting gene trees with atleast one duplication event
tree_with_duplication<- function(tree)
{
## Obtaining total internal node data, number of tips,speciation and duplication nodes for each tree
gene_tree <- tree@phylo
gene_tree_data <- tree@data
##Identifying duplication nodes
duplication_node <- gene_tree_data$node[which(gene_tree_data$Event=="Duplication")]
## If does not match the criteria returns NA
if((length(duplication_node)) > 0)
{
return(tree)
}
else{
return(NA)
}
}
## This function is written to estimate phylogenetic signals (with Blomberg's K and with Pagel's lambda methos) for each gene tree
Phylogenetic_signal<-function(tree)
{
gene_tree<-tree@phylo
gene_data<-tree@data
trait_data<-gene_data$Tau[which(is.na(gene_data$pic))]
names(trait_data)<-gene_data$label[which(is.na(gene_data$pic))]
Blomberg_K<- tryCatch(phylosig(gene_tree,trait_data,method = "K",test = T), error = function(e) {"Error"})
if(Blomberg_K=="Error")
{
K_Blomberg<-1000
P_Blomberg<-1000
}
if(Blomberg_K!="Error")
{
K_Blomberg<-Blomberg_K$K
P_Blomberg<-Blomberg_K$P
}
Pagel_lambda<-tryCatch(phylosig(gene_tree,trait_data,method = "lambda",test = T), error = function(e) {"Error"})
if(Pagel_lambda=="Error")
{
lambda_Pagel<-1000
P_pagel<-1000
}
if(Pagel_lambda!="Error")
{
lambda_Pagel<-Pagel_lambda$lambda
P_pagel<-Pagel_lambda$P
}
return(tibble
(gene=digest(tree),
K_effecient=K_Blomberg,
Pvalue_Blomberg=P_Blomberg,
lambda_estimate=lambda_Pagel,
Pvalue_pagel=P_pagel))
}
## This function is written to modify the labels of duplication nodes
## Otherwise duplication nodes with the same label name as of speciation nodes will be calibrated using the speciation time points or will interfere during the time calibration process
modify_label <- function(tree)
{
gene_tree <- tree@phylo
gene_tree_data <- tree@data
## Collecting internal clade labels of duplication nodes to modify them
Internal_clade_label <- gene_tree_data$label[which(!is.tip.nhx(tree))]
dup_node<-gene_tree_data$node[which(gene_tree_data$Event=="Duplication")]
dup_node_data_label<-gene_tree_data$label[dup_node]
tree@data$label[dup_node] <- paste(dup_node_data_label,"_d",sep = "")
return(tree)
}
## This function is to time calibrate gene trees on the basis of the speciation time points
## Modified from Dunn's script
## Maintaining the original topology of the trees
tree_calibrate <- function(tree, timeframe, model=model)
{
gene_tree <- tree@phylo
count<<-count+1
print(count)
## Create calibration matrix for speciation nodes
calibration_matrix <-
tree@data[ !is.tip.nhx( tree ), ] %>%
filter( D == "N" ) %>%
left_join( timeframe, c( "label" = "clade" ) ) %>%
mutate( age.min = age ) %>%
mutate( age.max = age ) %>%
mutate( soft.bounds = NA )
calibration_matrix <- calibration_matrix[c("node", "age.min","age.max","soft.bounds")]
## Time calibrating trees
calibrate_trees <- try(ape::chronos(gene_tree, lambda = 0, calibration = calibration_matrix, model = model))
##Trees those are not time calibrated can not be used further
##To avoid error due to non calibrated tree we did the following
if( "phylo" %in% class(calibrate_trees))
{
class(calibrate_trees) <- "phylo"
tree@phylo <- calibrate_trees
return(tree)
}
else{
return(NA)
}
}
## This function adds node depth to our dataframe of tree@data for further use in building time calibration matrix
tree_nodedepth <- function(tree)
{
gene_tree <- tree@phylo
##Computing node depth and returning it to the tree into "@data" slot
nodedepth <- ape::node.depth(gene_tree)
tree@data$node_depth<-nodedepth
return(tree)
}
## This function adds heights of each node to the '@data' slot
tree_height <- function(tree)
{
gene_tree <- tree@phylo
gene_data <- tree@data
if (class(tree) == "treedata")
{
tree@data <- tidytree::as_tibble(tree@data)
}
## Identifying nodes of a gene tree
gene_tree_nodes<-gene_data$node
height_node<-NULL
## The purpose of using node height in this study is to use it for one diagnostic test analysis, although using this node height estimate of the ape R package is not very essential
## It is recommended to use the nodeheight () of the phytools R package
## Even for the diagnostic tests, one can use the nodeheight() of the phytools R package, i.e. the root to the node distance in each tree
## We did not consider nodeheight() of the phytools R package in this case because we already included the node age, i.e., the tip to the node distance, in our diagnostic tests. This means that it will not add anything extra in our diagnostic tests.
## Hence, we added node.height() of the ape R package. If node age is already included, node height can be excluded from diagnostic tests if some one wants.
## The aim for us is to exclude all possible trees with phylogenetic dependence of any internal node parameters, hence we also kept node height but from the ape R package, not from the phytools R package. In any case (with the node height option of the phytools/ape R package or excluding the node height), the trends of results will not change
##Computing node height and returned it to the tree into "@data" slot
height_node<-ape::node.height(gene_tree)
tree@data$nodeheight<-height_node
return(tree)
}
## This function is written to change the modified labels of duplication nodes to the original one
remodify_label <- function(tree)
{
gene_tree <- tree@phylo
gene_tree_data <- tree@data
## Collecting internal clade labels of duplication nodes to modify them
Internal_clade_label <- gene_tree_data$label[which(!is.tip.nhx(tree))]
Internal_node<-gene_tree_data$node[which(!is.tip.nhx(tree))]
New_internal_clade_label<-sapply(Internal_clade_label,
function(x)
{x <- unlist(strsplit(toString(x), split='_d', fixed=TRUE))[1]})
tree@data$label[Internal_node] <-as.character(New_internal_clade_label)
#tree@data$S[dup_node] <- paste(dup_node_data_S,".d",sep = "")
return(tree)
}
##This function is written to permute Tau at the tips of the trees
shuffling_tauR<-function(tree)
{
## Reading gene tree and its data slot
gene_tree<-tree@phylo
gene_data<-tree@data
if (class(tree) == "treedata")
{
tree@data <- tidytree::as_tibble(tree@data)
}
## Collecting Tau data to randomize
#Tau.tree<-gene_data$Tau[which(is.na(gene_data$pic))]
Tau.tree<- gene_data$Tau[ is.tip.nhx( tree ) ]
## Permuting the trait data and storing the result
Tau.new<-sample(x=Tau.tree,size = length(Tau.tree), replace = FALSE)
tree@data$Tau<- c(Tau.new,rep(NA, times=gene_tree$Nnode))
return(tree)
}
## This function is writting to modify Ensembl protein id to gene id
modify_tiplabel<-function(tree)
{
## Reading data
gene_tree<-tree@phylo
gene_data<-tree@data
## Modifying tip labels
tree@phylo$tip.label<-tree@data$G[is.tip.nhx(tree)]
## Modifying tree data labels
tree_labels<-tree@data$label
internal_labels<-tree@data$label[!is.tip.nhx(tree)]
tree@data$label<-c(tree@phylo$tip.label,internal_labels)
return(tree)
}
## This function is to summarize the data of all trees
summary_function<-function(tree)
{
if(class(tree) == "treedata")
{
tree@data <- tidytree::as_tibble(tree@data)
}
gene_data<-tree@data
gene_data$gene<-digest(tree)
gene_data$pic<-abs(gene_data$pic)
tree@data<-gene_data[-c(4,5)]
return(tree@data)
}
## This function allows to perform permutation of the trait data (tau here)
shuffling_tau<-function(tree)
{
## Reading gene tree and its data slot
gene_tree<-tree@phylo
gene_data<-tree@data
if (class(tree) == "treedata")
{
tree@data <- tidytree::as_tibble(tree@data)
}
## Collecting Tau data to randomize
#Tau.tree<-gene_data$Tau[which(is.na(gene_data$pic))]
Tau.tree<- gene_data$Tau[ is.tip.nhx(tree)]
## Permuting the trait data, and returning the result
Tau.new<-sample(x=Tau.tree,size = length(Tau.tree), replace = FALSE)
tree@data$Tau_new<- c(Tau.new,rep(NA, times=gene_tree$Nnode))
return(tree)
}
## This function is written to perform permutation of the internl node events of gene trees with any trait data
shuffling_event<-function(tree)
{
## Reading gene tree and its data slot
gene_tree<-tree@phylo
gene_data<-tree@data
Internal_node<-gene_data$node[which(!is.na(gene_data$pic))]
if (class(tree) == "treedata")
{
tree@data <- tidytree::as_tibble(tree@data)
}
## Collecting event data to permute
event_tree<-gene_data$Event[which(!is.na(gene_data$pic))]
events_new<-sample(x=event_tree, size = length(event_tree), replace = FALSE )
Internal_new_event<-as.character(events_new)
#names(events.new)<-Internal_node
tree@data$event_new<- c(rep(NA,time=length(gene_tree$tip.label)),Internal_new_event)
tree@data$event_new <- factor(tree@data$event_new, levels=c( "Speciation", "Duplication"))
return(tree)
}
##This function calculates Phylogenetic Independent Contrasts (PICs) for the gene trees for any trait data (tau here)
contrast_calc<-function(tree)
{
## Collecting data for each tree
gene_tree<-tree@phylo
gene_data<-tree@data
if (class(tree) == "treedata")
{
tree@data <- tidytree::as_tibble(tree@data)
}
## Collecting trait data at the tips of each tree
Tau_tip<- gene_data$Tau[ is.tip.nhx( tree ) ]
## Initializing variable
tree@data$PIC <- NULL
tree@data$Variance <- NULL
## Calculating the PICs of the corresponding gene tree
## Returning the results to "data" frame of the tree
pic_tree <- ape::pic(Tau_tip, gene_tree, var.contrasts=TRUE)
tree@data$PIC<- c(rep(NA, length(gene_tree$tip.label)), pic_tree[,1])
tree@data$Variance <- c(rep(NA, length(gene_tree$tip.label)), pic_tree[,2])
tree@data$pic<- abs(tree@data$PIC) ## absolute PIC values
return(tree)
}
##This function calculates PICs for each tree with randomized trait data (Tau here)
contrast_random<-function(tree)
{
## Tree data
gene_tree<-tree@phylo
gene_data<-tree@data
## Collecting trait data at the tips of each tree
Tau_tip<- gene_data$Tau_new[is.tip.nhx(tree)]
## Initializing variable
tree@data$PIC_random <- NULL
tree@data$Variance <- NULL
## Calculating the phylogenetic independent contrasts for each tree
## Returning the results to "data" frame of the tree
pic_tree <- ape::pic(Tau_tip, gene_tree, var.contrasts=TRUE)
tree@data$PIC_random <- c(rep(NA, length(gene_tree$tip.label)), pic_tree[,1])
tree@data$Variance <- c(rep(NA, length(gene_tree$tip.label)), pic_tree[,2])
tree@data$pic_abs_random <- abs(tree@data$PIC_random) ## absolute PIC values
return(tree)
}
## Identification of calibrated time trees with negative branch lengths
negative_edgelength<-function(tree)
{
## Initialization
index_negative<-vector()
## Returning the indices of the lists of gene trees with negative edge lengths
for(i in 1:length(tree))
{
calibrated_tree <-tree[[i]]@phylo
edgelength<-calibrated_tree$edge.length
negative <- which(edgelength<=0)
if(length(negative) > 0)
{
index_negative <- append(index_negative,i)
}
}
return(index_negative)
}
## This function helps to identify, and to exclude gene trees for which contrast is not properly standarized
## crunch () of the Caper R package is used for this purpose
## We used two traits here (Tau and Mean expression level) to perform the phylogenetic regression for each tree
## The output for each tree also provides the contrasts for both the traits
diagnostic_plot_test <- function(tree)
{
gene_tree<-tree@phylo
gene_tree$node.label<-NULL
count<<-count+1
print(count)
if(class(tree) == "treedata")
{
tree@data <- tidytree::as_tibble(tree@data)
}
data<-tree@data
data_new<-data[which(!is.na(data$Tau)),]
data_new1<-data.frame(label=data_new$label,Tau=data_new$Tau, Mean_Exp=data_new$Mean)
rownames(data_new1)<-data_new1$label
treedata<-comparative.data(gene_tree,data_new1,label)
test<-tryCatch(crunch(Mean_Exp~Tau,data=treedata,equal.branch.length=F), error = function(e) {"Error"})
if((test=="Error") || (is.na(test$mod[1]$coefficients[1])))
{ print ("Error obtained in crunch")
return(NA)
}
if(test!="Error")
{
## We need to check for diagnostic plots for the expected variance and node age with the absolute PICs from the Caper R package
contrast<-caic.table(test)
contrast$node<-as.numeric(rownames(contrast))
contrast$height<-data$nodeheight[which(!is.na(data$pic))]
diagnostic<-caic.diagnostics(test)
## Adding the node depth and the node height to the diagnstic tests
test_depth<-summary(lm(contrast$Tau~contrast$nodeDepth))
test_height<-summary(lm(contrast$Tau~contrast$height))
## We aim to remove the trees for which PICs show any phylogenetic dependence, assessed by the significant correlation(s) between the absolute PICs and either of the four internal parameters considered in this study
## Collecting the P values of the diagnostic tests
p.SDT<-caic.diagnostics(test)[2,4,1]
p.AgeT<-caic.diagnostics(test)[3,4,1]
p.depthT<-test_depth$coefficients[2,4]
p.heightT<-test_height$coefficients[2,4]
##If PICs show a significant correlation with any of the four internal phylogenetic parameters, we return 'NA'
if((p.SDT < 0.05) || (p.AgeT < 0.05) || (p.depthT < 0.05) || (p.heightT < 0.05)){return (NA) }
## Collecting the PICs in a different variable name
if((p.SDT >= 0.05) && (p.AgeT >= 0.05) && (p.depthT >= 0.05) && (p.heightT >= 0.05))
{
tree@data$pic_Tau<-NULL
tree@data$variance<-NULL
## Now we return the trees dataframe
tree@data$pic_Tau <- c(rep(NA, length(gene_tree$tip.label)), (contrast$Tau))
tree@data$variance<- c(rep(NA, length(gene_tree$tip.label)), contrast$contrVar)
return(tree)
}}
}
## This function is written to transform the branch lengths of the gene trees
branch_transform<-function(tree)
{
ct<<-ct+1
print(ct)
##Collecting gene tree and their edge lengths
gene_tree<-tree@phylo
gene_data<-tree@data
gene_tree$edge.length[which(gene_tree$edge.length <= 1)] <- 1
edge_length<-gene_tree$edge.length
ntips <-length(gene_tree$tip.label)
scale<-0 ##Initialization for each tree
if(class(tree) == "treedata")
{
tree@data <- tidytree::as_tibble(tree@data)
}
## Initializing variables
tree@data$pic_transformed<-NULL
tree@data$var_transformed<-NULL
## Transforming the branch length
tree@phylo$edge.length.new<-log(edge_length,10)+edge_length**scale
##Computing the PICs for the branch length transformed trees
transformed_tree<-contrast_br_transformed(tree)
if(ntips >= 3)
{
## Performing diagnostic test to check for the non-correlation between standard deviations and absolute PICs for each tree
## If there is a significant correlation, we need to continue the branch length transformation for that tree
## Calculating the correlation between absolute PICs and standard deviations
new_tree<-transformed_tree@phylo
new_data<-transformed_tree@data
abs_pic<-new_data$pic_transformed[which(!is.na(new_data$pic))]
var<-new_data$var_transformed[which(!is.na(new_data$pic))]
varr<-sqrt(var)
group<-new_data$Event[which(!is.na(new_data$pic))]
## When all the node contrasts are zero, we return the tree
length_pic<-length(abs_pic)
length_pic_zero <-length(abs_pic[abs_pic==0])
if(length_pic == length_pic_zero)
{
return(transformed_tree)
}
else
{
#p.SD<-cor.test(abs_pic,varr)$p.value
var.sd<-summary(lm(abs_pic~varr))
p.SD<-var.sd$coefficients[2,4]
## If no significant correlation is found, the corresponding tree is returned
if(p.SD > 0.05)
{
print(paste0("passed:",scale))
return(transformed_tree)
}
## Else, we perform recursive transformtion
if(p.SD <= 0.05)
{
if(scale < 2)
{
scale<-scale + 0.1
print(paste0("scale:",scale))
recursive_transformation(tree,scale)
}
else
{
return(NA)
}
}
}
}
else
{
return(NA)
}
}
#This function calculates PICs for the branch length transformed trees
contrast_br_transformed<-function(tree1)
{
## Tree data
gtree<-tree1@phylo
gdata<-tree1@data
tree1@phylo$edge.length<-tree1@phylo$edge.length.new
if(class(tree1) == "treedata")
{
tree1@data <- tidytree::as_tibble(tree1@data)
}
## Collecting trait data at the tips
Tau_tip<-tree1@data$Tau[which(is.na(tree1@data$pic))]
## Calculating the PICs for each tree
## Returning the results to "data" frame of the tree
pic_tree <- ape::pic(Tau_tip, tree1@phylo, var.contrasts=TRUE)
absolute_pic <- abs(pic_tree[,1]) ## absolute PIC values
##Returning PICs for the branch transformed trees
tree1@data$pic_transformed <-c(rep(NA, length(gtree$tip.label)), absolute_pic)
tree1@data$var_transformed <- c(rep(NA, length(gtree$tip.label)), pic_tree[,2])
return(tree1)
}
##This function is to perform recursive branch length transformations
recursive_transformation <- function(phy,scalelimit)
{
##Collecting gene trees and their edge lengths
data_tree<-phy@phylo
data_edge_length<-data_tree$edge.length
data_edge_length[which(data_edge_length <= 1)] <- 1
## Transforming the branch lengths
phy@phylo$edge.length.new<-log(data_edge_length,10)+data_edge_length**scalelimit
## Collecting the PICs in a different variable name
phy@data$pic_transformed<-NULL
phy@data$var_transformed<-NULL
##Computing PICs for the branch length transformed tree
transformed_tree_new<-contrast_br_transformed(phy)
## Performing diagnostic test to check for a non-significant correlation between standard deviations and absolute PICs for each tree
## Calculating the correlation between absolute PICs and standard deviations
new_tree<-transformed_tree_new@phylo
new_data<-transformed_tree_new@data
pic<-new_data$pic_transformed[which(!is.na(new_data$pic))]
var_sqrt<-sqrt(new_data$var_transformed[which(!is.na(new_data$pic))])
group.new<-new_data$Event[which(!is.na(new_data$pic))]
var.sd.new<-summary(lm(pic~var_sqrt))
p.sd<-var.sd.new$coefficients[2,4]
## If no significant correlation is found, the tree is returned
if(p.sd > 0.05)
{
print(paste0("passed recur:",scalelimit))
return(transformed_tree_new)
}
## If the P value is still significant, we perform recursive transformtion
if(p.sd <= 0.05)
{
if(scalelimit <= 2)
{
print(paste0("scale:",scalelimit))
scalelimit<-scalelimit + 0.1
recursive_transformation(phy,scalelimit)
}
}
}
## This function is written to extract phylogenetic indepedent contrasts of the speciation events for the empirical or for the randomized trees
## frame refers to the dataframe and x should is the column name (ex: 'pic' or 'pic_abs_random' for the empirical or for therandomized data))
speciation_contrast<-function(frame, x)
{
contrast_spe <- frame[[x]][which(frame$Event=="Speciation")]
return(contrast_spe)
}
##This function is written to extract phylogenetic indepedent contrasts of the duplication events for the empirical or for the randomized trees
## frame refers to the dataframe and x should is the column name (ex: 'pic' or 'pic_abs_random' for the empirical or for the randomized data))
duplication_contrast<-function(frame, x)
{
contrast_dup <- frame[[x]][which(frame$Event=="Duplication")]
return(contrast_dup)
}
##This function is written to extract phylogenetic indepedent contrasts of the young duplication events for the empirical or for the randomized trees
## frame refers to the dataframe and x should is the column name (ex: 'pic' or 'pic_abs_random' for the empirical or for the randomized data))
young_duplication_contrast<-function(frame, x)
{
contrast_dup <- frame[[x]][which(frame$Event=="Duplication" & frame$node_age <= 296)]
return(contrast_dup)
}
##This function is written to extract phylogenetic indepedent contrasts of old duplication events for the empirical or for the randomized trees
## frame refers to the dataframe and x should is the column name (ex: 'pic' or 'pic_abs_random' for the empirical or for the randomized data))
old_duplication_contrast<-function(frame, x)
{
contrast_dup <- frame[[x]][which(frame$Event=="Duplication" & frame$node_age > 296)]
return(contrast_dup)
}
## Function to compute the Wilcoxon one-tailed test
one_tailed_wilcox<-function (data1, data2)
{
wilcox_oc_one_tailed <- wilcox.test(data1,data2,alternative="greater")$p.value
#star <-stars.pval(wilcox_oc_one_tailed)
#star0<- stars.pval(0)
if((wilcox_oc_one_tailed != 0) & (wilcox_oc_one_tailed > 2.2e-16))
{
wilcox_oc_one_tailed <- format(wilcox_oc_one_tailed, digits= 3, scientific = TRUE)
label_p =paste0("P = ",wilcox_oc_one_tailed)
}
else{label_p = paste0("P < 2.2e-16")}
return(label_p)
}
## Function to compute the Wilcoxon two-tailed test
two_tailed_wilcox<-function (data1, data2)
{
wilcox_oc_two_tailed <- wilcox.test(data1,data2,alternative="two.sided")$p.value
#star <-stars.pval(wilcox_oc_two_tailed)
#star0<- stars.pval(0)
if((wilcox_oc_two_tailed != 0) & (wilcox_oc_two_tailed > 2.2e-16))
{
wilcox_oc_two_tailed <- format(wilcox_oc_two_tailed, digits= 3, scientific = TRUE)
label_p =paste0("P = ",wilcox_oc_two_tailed)
}
else{label_p = paste0("P < 2.2e-16")}
return(label_p)
}
## Function to perform two-sided Wilcoxon test on the branch transformed trees
Wilcoxon_2_sided_transformed<-function(dataframe)
{
speciation_contrast_tau <- abs(speciation_contrast(dataframe,"pic"))
duplication_contrast_tau <- abs(duplication_contrast(dataframe,"pic"))
## Performing test
wilcox_test_tau_br_transformed <- two_tailed_wilcox(duplication_contrast_tau,speciation_contrast_tau)
return(wilcox_test_tau_br_transformed)
}
##This function is written to generate boxplots
boxplot_new<-function(dataframe,pval,med,type)
{
dodge <- position_dodge(width = 0.51)
if(type=="type1") ## "type1" for the data without branch length transformation
{
plot<-ggplot(dataframe,aes(x=group, y=pic, fill=Event ) ) +
guides( colour = guide_legend( override.aes = list( shape = 16 ) ) ) +
geom_boxplot( width=0.5,outlier.colour=NA, position = dodge, notch = T) +
xlab( NULL ) +
ylab(expression(bold(paste("PICs of ",tau)))) +
coord_cartesian(ylim=c(0, 0.05)) +
theme_classic()+
theme(legend.title=element_blank(),legend.position=c(0.9,0.9)) +
theme(axis.text=element_text(size=10,face="bold")) +
theme(legend.text=element_text(size=10,face="bold"))+
theme(plot.title = element_text(face = "bold"))+
annotate("text", x = 1.00, y = 0.04, label= pval, fontface = 4)
# annotate("text", x=0.87, y=0.01, label=med$pic.round[1], fontface=2)+
# annotate("text", x=1.13, y=0.01, label=med$pic.round[2], fontface=2)
return(plot)
}
if(type=="type2") ## "type2" for the branch length transformed data
{
plot<-ggplot(dataframe,aes(x=group, y=pic, fill=Event ) ) +
guides( colour = guide_legend( override.aes = list( shape = 16 ) ) ) +
geom_boxplot( width=0.5,outlier.colour=NA, position = dodge, notch = T) +
xlab( NULL ) +
ylab(expression(bold(paste("PICs of ",tau)))) +
coord_cartesian(ylim=c(0, 0.22)) +
theme_classic()+
theme(axis.title.x=element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank())+
theme(legend.title=element_blank(),legend.position=c(0.85,0.7)) +
#theme(legend.text=element_text(size=10,face="bold"))+
theme(plot.title = element_text(face = "bold"))+
annotate("text", x = 1.00, y = 0.2, label= pval, fontface = 4)
return(plot)
}
}
##This function is written to plot histogram on the P values of the randomized data
## Frame should be the dataframe and xName should be 'pval_tau' or 'pval_event'
##groupName should be 'treeset'
histo_plot<-function(frame, xName,groupName)
{
ggplot2.histogram(data=frame, xName=xName,
groupName=groupName,legendPosition="none",groupColors = "#7CAE00",
alpha=0.8, addDensity=F,
addMeanLine=F,meanLineColor = "#C77CFF", meanLineSize=0.5, meanLineType = "solid") +
theme_classic() +
xlab(expression(bold(paste(bolditalic(P)," value"))))+
ylab("Frequency") +
theme(legend.title=element_blank(),legend.position=c(0.7,0.8),legend.text=element_text(size=8)) +
theme(legend.position="none")+
theme(plot.title = element_text (face="bold",
colour="black", lineheight=1.0),
axis.title.x=element_text( face="bold",
colour="black", hjust=0.5),
axis.title.y=element_text(face="bold",
colour="black", vjust=0.5, angle=90))
}
##This function is written to collect median data required for jitter plot
## Frame should be dataframe,x and y should be defined (for example pic and Event)
median_jitter<-function(frame,x,y)
{
median_data<-NULL
median_data<- aggregate(frame[[x]]~frame[[y]], frame, median) ## aggregate function format
median_data$pic.round<-paste0("Median = ",round(median_data$`frame[[x]]`,4),sep="")
return(median_data)
}
## The following function is taken from easyGgplot2 R package (https://github.com/kassambara/easyGgplot2)
## and modified to add median trendline in the histogram plot instead of adding meanline
ggplot2_histogram_mod<-function (data, xName = NULL, groupName = NULL, position = c("identity",
"stack", "dodge"), addMedianLine = FALSE, medianLineColor = NULL,
medianLineType = "dashed", medianLineSize = 1, addDensityCurve = FALSE,
densityFill = "#FF6666", densityAlpha = 0.2, densityLineType = "solid",
densityLineColor = "#2F2F2F", scale = c("frequency", "density"),
groupColors = NULL, brewerPalette = NULL, fill = "black",
color = "black", linetype = "solid", ...)
{
## The following function .hish_params() taken from easyGgplot2 package
.hist_params <- function(...){
x <- list(...)
res <- list()
res$binwidth <- x$binwidth
res$bins <- x$bins
return(res)
}
pms <- .hist_params(...)
alpha <- ifelse(is.null(groupName), 1, 0.5)
if (is.null(xName) & !is.numeric(data))
stop("xName is missing or NULL. In this case data should be a numeric vector")
else if (is.numeric(data)) {
data = cbind(x = data, grp = rep(1, length(data)))
xName = "x"
}
data = data.frame(data)
if (is.null(groupName))
p <- ggplot(data = data, aes_string(x = xName))
else {
data[, groupName] = factor(data[, groupName])
p <- ggplot(data = data, aes_string(x = xName, fill = groupName,
colour = groupName))
}
if (addDensityCurve) {
if (!is.null(groupName)) {
p <- ggplot(data = data, aes_string(x = xName, fill = groupName,
colour = groupName))
p <- p + geom_histogram(aes_string(y = "..density.."),
position = position[1], binwidth = pms$binwidth,
bins = pms$bins, alpha = alpha)
p <- p + geom_density(alpha = densityAlpha, linetype = densityLineType)
}
else {
p <- p + geom_histogram(aes_string(y = "..density.."),
position = position[1], binwidth = pms$binwidth,
bins = pms$bins, color = color, fill = fill,
linetype = linetype)
p <- p + geom_density(fill = densityFill, alpha = densityAlpha,
linetype = densityLineType, colour = densityLineColor)
}
}
else {
if (scale[1] == "density")
p <- p + geom_histogram(aes_string(y = "..density.."),
position = position[1], binwidth = pms$binwidth,
bins = pms$bins)
else p <- p + geom_histogram(aes_string(y = "..count.."),
position = position[1], binwidth = pms$binwidth,
bins = pms$bins, alpha = alpha)
}
if (addMedianLine) {
if (is.null(groupName)) {
if (is.null(meanLineColor))
medianLineColor = "red"
m = median(data[, xName], na.rm = T) ## Getting median value
p <- p + geom_vline(aes_string(xintercept = m), color = medianLineColor,
linetype = medianLineType, size = medianLineSize)
}
else {
df <- data.frame(grp = factor(data[, groupName]),
x = data[, xName])
df.m <- stats::aggregate(df[, "x"], by = list(grp = df[,
"grp"]), median) ## Adding median value to different groups
names(df.m) <- c(groupName, "x.median")
if (is.null(medianLineColor))
p <- p + geom_vline(data = df.m, aes_string(xintercept = "x.median",
colour = groupName), linetype = medianLineType,
size = medianLineSize)
else p <- p + geom_vline(data = df.m, aes_string(xintercept = "x.median"),
linetype = medianLineType, color = medianLineColor,
size = medianLineSize)
}
}
if (!is.null(groupColors)) {
p <- p + scale_fill_manual(values = groupColors)
p <- p + scale_colour_manual(values = groupColors)
}
else if (!is.null(brewerPalette)) {
p <- p + scale_fill_brewer(palette = brewerPalette)
p <- p + scale_colour_brewer(palette = brewerPalette,
guide = "none")
}
p <- ggplot2.customize(p, ...)
p
}
## This function generates a dataframe with median data
median_df<-function(Frame)
{
median_data<-Frame %>%
group_by(Event) %>%
summarise(Median=median(pic),
count=n())
median_data$pic.round<-paste0(round(median_data$Median,4))
return(median_data)
}
## This function is written to generate dataframe for plotting
plot_frame<-function(dataframe,estimate,type)
{
plot_df <- data.frame(pic=NA,group=NA, Event=NA) ## declaring data frame
if(type=="type1" && estimate=="pic_Tau")
{
plot_df <- rbind(plot_df, data.frame(pic=abs(dataframe$pic_Tau), group="Age <= 296 My", Event=dataframe$Event))
}
if(type=="type2" && estimate=="pic")
{
plot_df <- rbind(plot_df, data.frame(pic=abs(dataframe$pic), group="No age limit", Event=dataframe$Event))
}
plot_df <- plot_df[-1,]
plot_df$Event <- factor(plot_df$Event, levels=c("Speciation", "Duplication"))
return(plot_df)
}
##This function is written to generate jitter plot
## Frame should be dataframe
## df_median is the dataframe with median data
jitter_plot_tau<-function(frame,df_median,pvalue)
{
ggplot(frame,aes(x=Event, y=pic_Tau, fill=Event)) +
geom_jitter(aes(colour = Event),position=position_jitter(0.02), alpha=0.5) +
geom_text(data = df_median, aes(label = pic.round),fontface = 2,size = 3,
hjust=0.5,vjust =-2.5)+
geom_crossbar(data=df_median, aes(ymin = pic_Tau, ymax = pic_Tau),
size=0.2,col= "black", width = .2)+
xlab( NULL ) +
ylab(expression(bold("PIC"))) +
ylim(0, 0.2) +
theme_classic()+
theme(legend.title=element_blank(),legend.position=c(1.9,1.9)) +
theme(axis.text=element_text(size=10,face="bold")) +
theme(legend.text=element_text(size=10,face="bold")) +
annotate("text", x = 1.5, y = 0.17, label= pvalue, fontface = 4)
}
## This function is written to calculate the proportions of duplication, and speciation events
tree_data_collection<-function(tree)
{
##Collecting gene tree data
gene_tree<-tree@phylo
gene_data<-tree@data
ntips <-length(gene_tree$tip.label) ## Number of tips
root<-as.numeric(ntips+1)
root_event<-gene_data$Event[root]
root_age<-gene_data$node_age[root]
Internal_event_number<-as.numeric(length(gene_data$node[which(!is.na(gene_data$pic))]))
## initializing variables
pdup<-0
pspe<-0
pNA<-0
##Since, many internal node events are assigned as "NA", sum of proportion of speciation and duplication may not be equal to 1
dup<-as.numeric(length(gene_data$node[which((!is.na(gene_data$pic)) & (gene_data$Event %in% "Duplication"))]))
pdup<-round(dup/Internal_event_number,2) ## proportion of duplication
spe<-as.numeric(length(gene_data$node[which((!is.na(gene_data$pic)) & (gene_data$Event %in% "Speciation"))]))
pspe<-round(spe/Internal_event_number,2) ## proportion of speciation
NA_event<-as.numeric(length(gene_data$node[which((!is.na(gene_data$pic)) & (is.na(gene_data$Event)))]))
pNA<-round(NA_event/Internal_event_number,2) ## proportion of speciation
spe_var<-round(median(gene_data$var_exp[which((!is.na(gene_data$pic)) & (gene_data$Event %in% "Speciation"))]),0) ## variance of speciation
dup_var<-round(median(gene_data$var_exp[which((!is.na(gene_data$pic)) & (gene_data$Event %in% "Duplication"))]),0) ## variance of speciation
if(pdup==0){dup_var<-NA}
return(tibble(tip_num=ntips,
internal_events=Internal_event_number,
dup_num=dup,
dup_prop=pdup,
spe_prop=pspe,
NA_prop=pNA,
dup_var=dup_var,
spe_var=spe_var,
root_age=root_age,
root_event=root_event))
}
## This function is written to calculate the proportions of duplication (according to age), speciation and NA events after the model fitting
tree_data_statistics<-function(tree, duplication_type)
{
##Reading gene tree data slot
gene_tree<-tree@phylo
gene_data<-tree@data
ntips <-length(gene_tree$tip.label) ## Number of tips
root<-as.numeric(ntips+1)
root_event<-gene_data$Event[root]
root_age<-gene_data$node_age[root]
Internal_event_number<-as.numeric(length(gene_data$node[which(!is.na(gene_data$pic))])) ##Length of internal nodes excluding nodes assigned to tips
## Initializing variables
pdup<-0
pspe<-0
pNA<-0
##Since many internal node events are assigned as "NA", sum of proportion of speciation and duplication may not be equal to 1
if(duplication_type=="young")
{
dup<-NULL
dup<-as.numeric(length(gene_data$node[which((!is.na(gene_data$pic)) & (gene_data$Event %in% "Duplication") &(gene_data$node_age <= 296) )]))
}
if(duplication_type=="old")
{
dup<-NULL
dup<-as.numeric(length(gene_data$node[which((!is.na(gene_data$pic)) & (gene_data$Event %in% "Duplication") &(gene_data$node_age > 296))]))
}
if(duplication_type=="all")
{
dup<-NULL
dup<-as.numeric(length(gene_data$node[which((!is.na(gene_data$pic)) & (gene_data$Event %in% "Duplication"))]))
}
pdup<-round(dup/Internal_event_number,2) ## Proportion of duplication event
spe<-as.numeric(length(gene_data$node[which((!is.na(gene_data$pic)) & (gene_data$Event %in% "Speciation"))]))
pspe<-round(spe/Internal_event_number,2) ## Proportion of speciation events
NA_event<-as.numeric(length(gene_data$node[which((!is.na(gene_data$pic)) & (is.na(gene_data$Event)))]))
pNA<-round(NA_event/Internal_event_number,2) ## Proportion of NA event
## Returning the tibble
return(tibble(tip_num=ntips,
internal_events=Internal_event_number,
dup_num=dup,
dup_prop=pdup,
spe_num=spe,
spe_prop=pspe,
NA_prop=pNA,
root_age=root_age,
root_event=root_event))
}
## This function is written to paint trees using plotSimmap R function for three different states (speciation, duplication and NA)
paint_tree_mod<-function(tree)
{
## Considering empirical gene tree data
gene_tree<-tree@phylo
gene_data<-tree@data
ntips <- length(gene_tree$tip.label)
Internal_node_data <- nrow(gene_data)-ntips
Duplication_node_length <- length(gene_data$Event[which(gene_data$Event == "Duplication")])
NA_node_length <- length(gene_data$Event[which(is.na(gene_data$Event))])
Speciation_node_length <- length(gene_data$Event[which(gene_data$Event == "Speciation")])
## Now checking for trees with at least a duplication and a speciation events
## If does not match the criteria returns NA
if((Internal_node_data - Duplication_node_length == 0) | (Internal_node_data - Speciation_node_length == 0))
{
return(NA)
}
else
{
if(NA_node_length > 0)
{
##Identifying duplication nodes and edges to paint them
dup_nodes <- gene_data$node[which(gene_data$Event=="Duplication")]
NA_nodes <- gene_data$node[which(is.na(gene_data$Event))]
NA_edges <- unique(gene_tree$edge[which(gene_tree$edge[,1] %in% NA_nodes), 2])
tree_painted <- paintBranches (gene_tree, edge=NA_edges, "NA", anc.state="S")
}
if(NA_node_length == 0)
{
## Identifiying duplication nodes and edges to paint them
dup_nodes <- gene_data$node[which(gene_data$Event=="Duplication")]
dup_edges <- unique(gene_tree$edge[which(gene_tree$edge[,1] %in% dup_nodes), 2])
tree_painted<-paintBranches (gene_tree, edge=dup_edges, "D", anc.state="S")
}
if("phylo" %in% class(tree_painted))
{
return(list(tree_painted, gene_tree, gene_data))
}