---
title: "Ancestral Sequence Reconstruction"
author:
- name: Klaus Schliep
  affiliation: Graz University of Technology
  email: klaus.schliep@gmail.com
date: "`r Sys.Date()`"
bibliography: phangorn.bib
output: rmarkdown::html_vignette
vignette: |
  %\VignetteIndexEntry{Ancestral Sequence Reconstruction}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, echo=FALSE}
# set global chunk options: images will be bigger
knitr::opts_chunk$set(fig.width=6, fig.height=4)
#, global.par=TRUE
options(digits = 4)
```   


# Introduction

These notes describe the ancestral sequence reconstruction using the _phangorn_ package [@Schliep2011]. _phangorn_ provides several methods to estimate ancestral character states with either Maximum Parsimony (MP) or Maximum Likelihood (ML). For more background on all the methods see e.g. [@Felsenstein2004] or [@Yang2006].

# Parsimony reconstructions 
To reconstruct ancestral sequences we first load some data and reconstruct a tree:
```{r}
library(phangorn)
fdir <- system.file("extdata/trees", package = "phangorn")
primates <- read.phyDat(file.path(fdir, "primates.dna"),
                        format = "interleaved")
tree <- pratchet(primates, trace=0) |> acctran(primates)
parsimony(tree, primates)
```

For parsimony analysis of the edge length represent the observed number of changes. Reconstructing ancestral states therefore defines also the edge lengths of a tree. However there can exist several equally parsimonious reconstructions or states can be ambiguous and therefore edge length can differ.
"MPR" reconstructs the ancestral states for each (internal) node as if the tree would be rooted in that node. However the nodes are not independent of each other. If one chooses one state for a specific node, this can restrict the choice of neighboring nodes (figures 2 and 3).
The function acctran (accelerated transformation) assigns edge length and internal nodes to the tree [@Swofford1987].
```{r}
anc.acctran <- ancestral.pars(tree, primates, "ACCTRAN")
anc.mpr <- ancestral.pars(tree, primates, "MPR")
```

All the ancestral reconstructions for parsimony are based on the fitch algorithm and so far only bifurcating trees are allowed. However trees can get pruned afterwards using the function `multi2di` from _ape_.

The `seqLogo` function from the _seqLogo_ package from Bioconductor provides a neat way to show proportions of a nucleotides of ancestral states (see figure 1).

```{r seqLogo, fig.cap="Fig 1. Ancestral reconstruction for a node.", eval=FALSE}
library(seqLogo)
seqLogo( t(subset(anc.mpr, getRoot(tree), 1:20)[[1]]), ic.scale=FALSE)
```
![](seqLogo.png)

You may need to install _seqLogo_ before
```{r, eval=FALSE}
if (!requireNamespace("BiocManager", quietly = TRUE))
    install.packages("BiocManager")
BiocManager::install("seqLogo")
```


```{r MPR, fig.cap="Fig 2. Ancestral reconstruction using MPR."}
plotAnc(tree, anc.mpr, 17)
title("MPR")
```
```{r ACCTRAN, fig.cap="Fig 3. Ancestral reconstruction using ACCTRAN."}
plotAnc(tree, anc.acctran, 17)
title("ACCTRAN")
```


# Likelihood reconstructions

_phangorn_ also offers the possibility to estimate ancestral states using a ML.
The advantages of ML over parsimony is that the reconstruction accounts for different edge lengths.
So far only a marginal construction is implemented (see [@Yang2006]).
```{r}
fit <- pml(tree, primates)
fit <- optim.pml(fit, model="F81", control = pml.control(trace=0))
```
We can assign the ancestral states according to the highest likelihood ("ml"):
\[
P(x_r = A) =  \frac{L(x_r=A)}{\sum_{k \in \{A,C,G,T\}}L(x_r=k)}
\]
and the highest posterior probability ("bayes") criterion:
\[
P(x_r=A) =  \frac{\pi_A L(x_r=A)}{\sum_{k \in \{A,C,G,T\}}\pi_k L(x_r=k)},
\]
where $L(x_r)$ is the joint probability of states at the tips and the state at the root $x_r$ and $\pi_i$ are the estimated base frequencies of state $i$.
Both methods agree if all states (base frequencies) have equal probabilities.
```{r}
anc.ml <- ancestral.pml(fit, "ml")
anc.bayes <- ancestral.pml(fit, "bayes")
```
The differences of the two approaches for a specific site (17) are represented in the following figures.
```{r plotML, fig.cap="Fig 4. Ancestral reconstruction the using the maximum likelihood."}
plotAnc(tree, anc.ml, 17)
title("ML")
```
```{r plotB, fig.cap="Fig 5. Ancestral reconstruction using (empirical) Bayes."}
plotAnc(tree, anc.bayes, 17)
title("Bayes")
```

# Session info 

```{r sessionInfo, echo=FALSE}
sessionInfo()
```

# References 
