---
title: "Evolutionary Rates & Selection Mode (Mr.Bayes)"
date: "`r Sys.Date()`"
output:
  html_vignette:
    toc: yes
vignette: |
  %\VignetteIndexEntry{Evolutionary Rates & Selection Mode (Mr.Bayes)} 
  %\VignetteEngine{knitr::rmarkdown} 
  %\VignetteEncoding{UTF-8}
bibliography: references.bib
link-citations: true
---

This vignette explains how to extract evolutionary rate parameters estimated from relaxed clock Bayesian inference analyses produced by [Mr. Bayes](https://nbisweden.github.io/MrBayes/). It also shows how to use evolutionary rate based inference of selection mode (strength) adapted to clock-based rates, as introduced by @simões2021. See the sister vignette "Evolutionary Rates & Selection Mode (BEAST2)" for an equivalent workflow using output data produced by [BEAST2](https://www.beast2.org/)

```{r, setup, echo=FALSE}
knitr::opts_chunk$set(echo = TRUE, warning = FALSE, collapse = TRUE)
```

Load the **EvoPhylo** package

```{r, eval = FALSE}
library(EvoPhylo)
```

```{r, include=FALSE}
devtools::load_all(".")
```


## Evolutionary Rates Statistics and Plots

In this section, we will extract evolutionary rate parameters from each node from a Bayesian clock (time-calibrated) summary tree. The functions below will store them in a data frame, produce summary statistics tables, and create different plots showing how rates are distributed across morphological partitions and clades. 

   


### 1. Get rates from the clock tree and create a rate table 

First, import a Bayesian clock tree using `treeio`'s function `read.mrbayes()` (= `read.beast()`).

```{r, eval = FALSE}
## Import summary tree with three clock partitions produced by 
## Mr. Bayes (.t or .tre files) from your local directory

tree3p <- treeio::read.mrbayes("Tree3p.t")
```

Below, we use the example Mr.Bayes single multi-clock tree with 3 morphological partitions `tree3p` from @simões2021 that accompanies `EvoPhylo`.

```{r}
data(tree3p)
```

Subsequently, using `get_clockrate_table_MrBayes()`, users can extract mean or median rate values for each node in the summary tree that were annotated by [Mr. Bayes](https://nbisweden.github.io/MrBayes/) when creating the summary tree with [Mr. Bayes](https://nbisweden.github.io/MrBayes/) "sumt" command. These mean or median rate values are calculated by [Mr. Bayes](https://nbisweden.github.io/MrBayes/) taking into account all trees from the posterior sample. This works for any summary tree produced by [Mr. Bayes](https://nbisweden.github.io/MrBayes/): a majority rule consensus or the fully resolved maximum compatible tree (the latter is used in the examples here).

Please note that analyses must have reached the stationarity phase and independent runs converging for the summary statistics in each node to be meaningful summaries of the posterior sample.

```{r}
## Get table of clock rates with summary stats for each node in 
## the tree for each relaxed clock partition (3 partitions in this tree file)
RateTable_Means_3p <- get_clockrate_table_MrBayes(tree3p, summary = "mean")
```

&nbsp;  


### 2. Export the rate table and plot tree with node values

Once a rate table has been obtained from [Mr. Bayes](https://nbisweden.github.io/MrBayes/) it is necessary to export it. This is a necessary step to subsequently open the rate table spreadsheet locally (e.g., using Microsoft Office Excel) and customize the table with clade names associated with with each node in the tree for downstream analyses. Note that the root node may include "NA" for rate value, so it must be removed from the rate table.

```{r, eval = FALSE}
## Export the rate tables (using Mr. Bayes example with 3 partitions)
write.csv(RateTable_Means_3p, file = "RateTable_Means_3p.csv")
```


## Plot tree node labels to customize clade names

To visualize the node values in the tree, you can use `ggtree()`.

```{r, fig.width=8, fig.height=8, fig.align = "center", out.width = "70%", message=FALSE,warning=FALSE}
## Plot tree node labels
library(ggtree)
tree_nodes <- ggtree(tree3p, branch.length = "none", size = 0.05) +
  geom_tiplab(size = 2, linesize = 0.01, color = "black", offset = 0.5) +
  geom_label(aes(label = node), size = 2, color="purple")
tree_nodes
```
```{r, eval = FALSE}
## Save your plot to your working directory as a PDF
ggplot2::ggsave("Tree_nodes.pdf", width = 10, height = 10)
```

&nbsp;  


### 3. Import rate table with custom clade memberships 

A new "clade" column has been added to the rates table

```{r,eval=FALSE}
## Import rate table with clade membership (new "clade" column added) 
## from your local directory
RateTable_Means_3p_Clades <- read.csv("RateTable_Means_3p_Clades.csv", header = TRUE)
```

Below, we use the rate table with clade membership `RateTable_Means_3p_Clades` that accompanies `EvoPhylo`.

```{r}
data(RateTable_Means_3p_Clades)

head(RateTable_Means_3p_Clades)
```

&nbsp;  


### 4. Get summary stats for each clade/clock partition

Obtain summary statistics table and plots for each clade by clock partition using `clockrate_summary()`. Supplying a file path to `file` save the output to that file.

```{r, eval = FALSE}
## Get summary statistics table for each clade by clock 
clockrate_summary(RateTable_Means_3p_Clades,
                  file = "Sum_RateTable_Means_3p.csv")
```

```{r, echo = FALSE}
t1 <- clockrate_summary(RateTable_Means_3p_Clades, digits = 2) 
kableExtra::kbl(t1, caption = "Rate table summary statistics") |> 
  kableExtra::kable_styling(font_size = 15, full_width = FALSE,
                            bootstrap_options = "striped", "condensed")
```

&nbsp;  


### 5. Plot rates by clock partition and clade

Plot distributions of rates by clock partition and clade with `clockrate_dens_plot()`.

```{r, fig.width=10, fig.height=5, fig.align = "center", out.width = "100%"}
## Overlapping plots
clockrate_dens_plot(RateTable_Means_3p_Clades, stack = FALSE,
                    nrow = 1, scales = "fixed")
```

Sometimes using stacked plots provides a better visualization as it avoids overlapping distributions.

```{r, fig.width=10, fig.height=5, fig.align = "center", out.width = "100%"}
## Stacked plots
clockrate_dens_plot(RateTable_Means_3p_Clades, stack = TRUE,
                    nrow = 1, scales = "fixed")
```

It is also possible to append extra layers using `ggplot2` function, such as for changing the color scale. Below, we change the color scale to be the Viridis scale.

```{r, fig.width=10, fig.height=5, fig.align = "center", out.width = "100%"}
## Stacked plots with viridis color scale
clockrate_dens_plot(RateTable_Means_3p_Clades, stack = TRUE,
                    nrow = 1, scales = "fixed") +
  ggplot2::scale_color_viridis_d() +
  ggplot2::scale_fill_viridis_d()
```

&nbsp;  


### 6. Rate linear models

We can also plot linear model regressions between rates from two or more clocks with `clockrate_reg_plot()`.

```{r, fig.width=8, fig.height=6, fig.align = "center", out.width = "70%"}
## Plot regressions of rates from two clocks
p12 <- clockrate_reg_plot(RateTable_Means_3p_Clades, clock_x = 1, clock_y = 2)
p13 <- clockrate_reg_plot(RateTable_Means_3p_Clades, clock_x = 1, clock_y = 3)
p23 <- clockrate_reg_plot(RateTable_Means_3p_Clades, clock_x = 2, clock_y = 3)

library(patchwork) #for combining plots
p12 + p13 + p23 + plot_layout(ncol = 2)
```
```{r, eval = FALSE}
## Save your plot to your working directory as a PDF
ggplot2::ggsave("Plot_regs.pdf", width = 8, height = 8)
```

&nbsp;  
&nbsp;  


### ADDENDUM: Example using rates from single clock analysis (no partitioning)

You can also explore clock rates for summary trees including a single clock shared among all character partitions (or an unpartitioned analysis):

```{r,eval = FALSE}
## Import summary tree with a single clock partitions produced by 
## Mr. Bayes (.t or .tre files) from examples directory
tree1p <- treeio::read.mrbayes("Tree1p.t")
```

Below, we use the example tree `tree1p` that accompanies `EvoPhylo`.

```{r}
data(tree1p)
```

Then, get table of clock rates with summary stats for each node in the tree for each relaxed clock partition.

```{r}
RateTable_Means_1p <- get_clockrate_table_MrBayes(tree1p, summary = "mean")
```

Then proceed with the analysis, as in the case with multiple clocks.

```{r, eval = FALSE}
## Export the rate tables
write.csv(RateTable_Means_1p, file = "RateTable_Means1.csv")

## Import rate table after adding clade membership (new "clade" column added)
RateTable_Means_1p_Clades <- read.csv("RateTable_Means1_Clades.csv", header = TRUE)
```
```{r}
#Below, we use the rate table with clade membership `RateTable_Means_1p_Clades` that accompanies `EvoPhylo`.
data(RateTable_Means_1p_Clades)
```
```{r,eval = FALSE}
## Get summary statistics table for each clade by clock 
clockrate_summary(RateTable_Means_1p_Clades,
                  file = "Sum_RateTable_Medians1.csv")
```
```{r, echo = FALSE}
t1 <- clockrate_summary(RateTable_Means_1p_Clades, digits = 2) 
kableExtra::kbl(t1, caption = "Rate table summary statistics") |> 
  kableExtra::kable_styling(font_size = 15, full_width = FALSE,
                            bootstrap_options = "striped", "condensed")
```

```{r, fig.width=6, fig.height=4, fig.align = "center", out.width = "100%"}
## Stacked plots with viridis color scale
clockrate_dens_plot(RateTable_Means_1p_Clades, stack = TRUE,
                    nrow = 1, scales = "fixed") +
  ggplot2::scale_color_viridis_d() +
  ggplot2::scale_fill_viridis_d()
```

&nbsp;  
&nbsp;  
&nbsp;  

## Selection Mode

In this section, we will use evolutionary rate based inference of selection mode, as first introduced by @baker2016 for continuous traits, and later adapted to clock-based rates by @simões2021.

&nbsp;  


### 1. Import combined log file from all runs. 

This is produced by using `combine_log()`. The first argument passed to `combine_log()` should be a path to the folder containing the log files to be imported and combined.

```{r,eval=FALSE}
## Import all log (.p) files from all runs and combine them, with burn-in = 25% 
## and downsampling to 2.5k trees in each log file
posterior3p <- combine_log("LogFiles3p", burnin = 0.25, downsample = 1000)
```

Below, we use the posterior dataset `posterior3p` that accompanies `EvoPhylo`.

```{r, results='hide'}
data(posterior3p)

## Show first 10 lines of combined log file
head(posterior3p, 10)
```

&nbsp;  


###2. Check background rates distribution and if they need transformation

The output includes histograms showing the data distribution before and after data transformation for comparisons. 

```{r, fig.width=8, fig.height=3, fig.align = "center", out.width = "90%"}
library(ggplot2)
B1 <- plot_back_rates (type = "MrBayes", posterior3p, clock = 1,
                      trans = "log10", size = 10, quantile = 1)
B1
B2 <- plot_back_rates (type = "MrBayes", posterior3p, clock = 2,
                      trans = "log10", size = 10, quantile = 1)
B2
B3 <- plot_back_rates (type = "MrBayes", posterior3p, clock = 3,
                      trans = "log10", size = 10, quantile = 1)
B3
```

&nbsp;  


### 3. Plot selection gradient on the summary tree

Using different thresholds, identify the selection mode across branches in the tree for each clock partition with `plot_treerates_sgn()`. 

Users must indicate the type of output file (between [Mr. Bayes](https://nbisweden.github.io/MrBayes/) and [BEAST2](https://www.beast2.org/)) and whether they would like to log transform the background rate to meet assumptions of normally distributed data, based on the results obtained from `plot_back_rates`. Users should also indicate in "clock" the number of the clock partition they would like to plot rates from and the desired significance threshold to interpret branch rates (we recommend number of standard deviations around the mean of background rates).Finally, a series of arguments enable users to customize the geological timescale to add to the tree.

```{r, fig.width=8, fig.height=8, fig.align = "center", out.width = "70%"}
## Plot tree using various thresholds for clock partition 1
A1 <- plot_treerates_sgn(
  type = "MrBayes", trans = "none",                            #Indicates software name output and type of transformation
  tree3p, posterior3p,                                         #Summary tree and posterior files
  clock = 1,                                                   #Show rates for clock partition 1
  summary = "mean",                                            #sets summary stats to get from summary tree nodes
  branch_size = 1.5, tip_size = 3,                             #sets size for tree elements
  xlim = c(-450, -260), nbreaks = 8, geo_size = list(3, 3),    #sets limits and breaks for geoscale
  threshold = c("1 SD", "3 SD"))                               #sets threshold for selection mode
A1
```

Plot tree using various thresholds for the other clock partitions and combine them.

```{r, fig.width=20, fig.height=8, fig.align = "default", out.width = "100%"}
## Plot tree using various thresholds for other clock partition and combine them
A2 <- plot_treerates_sgn(
  type = "MrBayes", trans = "none",                            #Indicates software name output and type of transformation
  tree3p, posterior3p,                                         #Summary tree and posterior files
  clock = 2,                                                   #Show rates for clock partition 1
  summary = "mean",                                            #sets summary stats to get from summary tree nodes
  branch_size = 1.5, tip_size = 3,                             #sets size for tree elements
  xlim = c(-450, -260), nbreaks = 8, geo_size = list(3, 3),    #sets limits and breaks for geoscale
  threshold = c("1 SD", "3 SD"))                               #sets threshold for selection mode

A3 <- plot_treerates_sgn(
  type = "MrBayes", trans = "none",                            #Indicates software name output and type of transformation
  tree3p, posterior3p,                                         #Summary tree and posterior files
  clock = 3,                                                   #Show rates for clock partition 1
  summary = "mean",                                            #sets summary stats to get from summary tree nodes
  branch_size = 1.5, tip_size = 3,                             #sets size for tree elements
  xlim = c(-450, -260), nbreaks = 8, geo_size = list(3, 3),    #sets limits and breaks for geoscale
  threshold = c("1 SD", "3 SD"))                               #sets threshold for selection mode

library(patchwork)
A1 + A2 + A3 + plot_layout(nrow = 1)
```
```{eval = FALSE}
## Save your plot to your working directory as a PDF
ggplot2::ggsave("Tree_Sel_3p.pdf", width = 20, height = 8)
```

&nbsp;  


### 4. Pairwise t-tests of rate values among clades

The function `get_pwt_rates_MrBayes()` complements the functionality of `plot_treerates_sgn` by producing a table of pairwise t-tests for differences between the mean background rate in the posterior and the absolute rate for each summary tree branches Should be used only for normally distributed data in which a CI=0.95 is considered a good threshold. In many cases, however, using multiple standard deviations as outputted using `plot_treerates_sgn` provides a more robust test of whether branch rates are significantly different from background rates.

4.1. Import rate table with clade membership (new "clade" column added) from your local directory with "mean" values

```{r,eval=FALSE}
## Import rate table with clade membership 
RateTable_Means_3p_Clades <- read.csv("RateTable_Means_Clades.csv", header = TRUE)
```

Below, we use the rate table with clade membership `RateTable_Means_3p_Clades` that accompanies `EvoPhylo`.

```{r}
data(RateTable_Means_3p_Clades)
```

4.2. Get and export table of pairwise t-tests
```{r, eval = FALSE}
## Get table of pairwise t-tests for difference between the posterior 
## mean and the rate for each tree node
RateSign_Tests <- get_pwt_rates_MrBayes(RateTable_Means_3p_Clades, posterior3p)

## Show first 10 lines of table
head(RateSign_Tests, 10)
```
```{r, echo = FALSE}
RateSign_Tests <- get_pwt_rates_MrBayes(RateTable_Means_3p_Clades, posterior3p)
t3 <- head(RateSign_Tests, 10)
kableExtra::kbl(t3, caption = "Combined log file") |> 
  kableExtra::kable_styling(font_size = 15, full_width = FALSE,
                            bootstrap_options = "striped", "condensed")
```
```{r, eval=FALSE}
## Export the table
write.csv(RateSign_Tests, file = "RateSign_Tests.csv")
```

&nbsp;  


## References