Bayesian Phylogeny
This exercise is part of the course Computational Molecular Evolution (22115).
Overview
Today's exercise will focus on phylogenetic analysis using Bayesian methods.
As was the case for likelihood methods, Bayesian analysis is founded on having a probabilistic model of how the observed data is produced. (This means that, for a given set of parameter values, you can compute the probability of any possible data set). You will recall from the lecture that in Bayesian statistics the goal is to obtain a full probability distribution over all possible parameter values. To find this so-called posterior probability distribution requires combining the likelihood and the prior probability distribution.
The prior probability distribution shows your beliefs about the parameters before seeing any data, while the likelihood shows what the data is telling about the parameters. Specifically, the likelihood of a parameter value is the probability of the observed data given that parameter value. (This is the measure we have previously used to find the maximum likelihood estimate). If the prior probability distribution is flat (i.e., if all possible parameter values have the same prior probability) then the posterior distribution is simply proportional to the likelihood distribution, and the parameter value with the maximum likelihood then also has the maximum posterior probability. However, even in this case, using a Bayesian approach still allows one to interpret the posterior as a probability distribution. If the prior is NOT flat, then it may have a substantial impact on the posterior although this effect will diminish with increasing amounts of data. A prior may be derived from the results of previous experiments. For instance one can use the posterior of one analysis as the prior in a new, independent analysis.
In Bayesian phylogeny the parameters are of the same kind as in maximum likelihood phylogeny. Thus, typical parameters include tree topology, branch lengths, nucleotide frequencies, and substitution model parameters such as for instance the transition/transversion ratio or the gamma shape parameter. The difference is that while we want to find the best point estimates of parameter values in maximum likelihood, the goal in Bayesian phylogeny is instead to find a full probability distribution over all possible parameter values. The observed data is again usually taken to be the alignment, although it would of course be more reasonable to say that the sequences are what have been observed (and the alignment should then be inferred along with the phylogeny).
In this exercise we will explore how one can determine and use posterior probability distributions over trees, over clades, and over substitution parameters. We will also touch upon the difference between marginal and joint probability distributions.
Getting started
- In the command below: Instead of /path/to/molevol enter the path to the directory where you have placed your course files (for instance cd /Users/bob/Documents/molevol, or cd /home/student/molevol).
cd /path/to/molevol mkdir bayes cd bayes cp ../data/primatemitDNA.nexus ./primatemitDNA.nexus cp ../data/neanderthal.nexus ./neanderthal.nexus cp ../data/hcvsmall.nexus ./hcvsmall.nexus
- You have analyzed (versions of) all these data files previously in this course. We will now use Bayesian phylogenetic analysis to complement what we learned in those analyses.
Load R libraries
- In RStudio: set the working directory to the bayes directory. Then issue these commands:
library(magrittr) library(tidyverse) library(bayesplot)
Posterior probability of trees
Question 1
- In today's exercise we will be using the program "MrBayes" to perform Bayesian phylogenetic analysis. MrBayes is a program that, like PAUP*, can be controlled by giving commands at a command line prompt. In fact, there is a substantial overlap between the commands used to control MrBayes and the PAUP command language. This should be a help when you are trying to understand how to use the program.
- Note that the command "help" will give you a list of all available commands. Issuing "help command" will give you a more detailed description of the specified command along with current option values. This is similar to how "help command" works in PAUP.
Start program
mb
- This starts the program, giving you a prompt ("MrBayes> ") where you can enter commands.
Get a quick overview of available commands
help
Load your sequences
execute primatemitDNA.nexus
- This file contains mitochondrial DNA sequences from 5 different primates. Note that MrBayes accepts input in nexus format, and that this is the same command that was used to load sequences in PAUP*. In general, you can use many of the PAUP commands in MrBayes also.
Inspect data set
showmatrix
Define outgroup
outgroup Gibbon
Specify your model of sequence evolution
lset nst=2 rates=gamma
- This command is again very much like the corresponding one in PAUP. You are specifying that you want to use a model with two substitution types (nst=2), and this is automatically taken to mean that you want to distinguish between transitions and transversions. Furthermore, rates=gamma means that you want the model to use a gamma distribution to account for different rates at different sites in the sequence.
Start Markov chain Monte Carlo sampling
- Make sure to make the shell window as wide as possible and then issue the following commands to start the run:
mcmc ngen=1000000 samplefreq=1000 nchains=3 diagnfreq=5000
- What you are doing here is to use the method known as MCMCMC ("Metropolis-coupled Markov chain Monte Carlo") to empirically determine the posterior probability distribution of trees, branch lengths and substitution parameters. Recall that in the Bayesian framework this is how we learn about parameter values: instead of finding the best point estimates, we typically want to quantify the probability of the entire range of possible values. An estimate of the time left is shown in the last column of output.
- Let us examine the command in detail. First, ngen=1000000 samplefreq=1000 lets the search run for 1,000,000 steps ("generations") and saves parameter values once every 1000 rounds (meaning that a total of 1000 sets of parameter values will be saved). The option nchains=3 means that the MCMCMC sampling uses 3 parallel chains (but see below): one "cold" from which sampling takes place, and two "heated" that move around in the parameter space more quickly to find additional peaks in the probability distribution.
- The option diagnfreq=5000 has to do with testing whether the MrBayes run is succesful. Briefly, MrBayes will start two entirely independent runs starting from different random trees. In the early phases of the run, the two runs will sample very different trees but when they have reached convergence (when they produce a good sample from the posterior probability distribution), the two tree samples should be very similar. Every diagnfreq generations, the program will compute a measure of how similar the tree-samples are (specifically, the measure is the average standard deviation of split frequencies. A "split" is the same as a bipartition, i.e., a division of all leaves in the tree in two groups, by cutting an internal branch). As a rule of thumb, you may want to run until this value is less than 0.05 (the smaller the better).
- During the run you will see reports about the progress of the two sets of four chains. Each line of output lists the generation number and the log likelihoods of the current tree/parameter combination for each of the two groups of three chains (a column of asterisks separate the results for the independent runs). The cold chains are the ones enclosed in brackets [...], while the heated chains are enclosed in parentheses (...). Occasionally the chains will swap so one of the heated chains now becomes cold (and sampling then takes place from this chain).
Continue run until parallel runs converge on same solution
- At the end of the run, Mrbayes will print the average standard deviation of split frequencies (which is a measure of how similar the tree samples of the two independent runs are). We recommend that you continue with the analysis until the value gets below 0.01 (if the value is larger than 0.01 then you should answer "yes" when the program asks "Continue the analysis? (yes/no)".)
Question: Once you have reached convergence (and answered "no" to continue the analysis): How many generations did you have to run?
Question 2
Have a look at the resulting sample files
- Open a new Terminal and cd to the bayes directory. Open one of the parameter sampling files in an nedit window:
nedit primatemitDNA.nexus.run1.p &
- This file contains one line for each sampled point (you may want to turn off line-wrapping in nedit under the preferences menu). Each row corresponds to a certain sample time (or generation). Each column contains the sampled values of one specific parameter. The first line contains headings telling what the different columns are: "lnL" is the log likelihood of the current parameter estimates, "TL" is the tree length (sum of all branch lengths), "kappa" is the transition/transversion rate ratio, "pi(A)" is the frequency of A (etc.), and "alpha" is the shape parameter for the gamma distribution. (Column headings may be shifted relative to their corresponding columns). Note how the values of most parameters change a lot during the initial "burnin" period, before they settle near their most probable values. Now, close the nedit window and have a look at the file containing sampled trees:
nedit primatemitDNA.nexus.run1.t &
- Tree topology is also a parameter in our model, and exactly like for the other parameters we also get samples from tree-space. One tree is printed per line in the parenthetical format used by most phylogeny software. There are 5 taxa in the present data set, meaning that the tree-space consists of only 15 different possible trees. Since we have taken more than 15 sample points, there must be several lines containing the same tree topology. Close the nedit window when you are done.
Examine MCMC trajectory for nucleotide frequency
- Recall, that the idea in MCMCMC sampling is to move around in parameter space in such a way that the points will be visited according to their posterior probability (i.e., a region with very high posterior probability will be visited frequently). Now, in RStudio plot the sampled values for the frequency of A for one of the run files:
df = read_tsv("primatemitDNA.nexus.run1.p", skip=1) mcmc_trace(df, pars="pi(A)")
- mcmc_trace is one of several plotting commands available in the bayesplot package. These commands produce a plot of f_A (or "pi(A)") from the sample file for the first of the two parallel runs. Note how the Markov chain starts at the arbitrary value of 0.25, rapidly moves to a value that fits with the observed data, and then moves around in parameter space, sampling different possible values of f_A. You can experiment with plotting other columns as well.
Investigate posterior probability distribution over trees
- MrBayes provides the sumt command to summarize the sampled trees. Before using it, we need to decide on the burn-in: The burn-in is the initial set of samples that are typically discarded, because we want to ensure that the MCMC has moved away from the random starting values, and has found the peaks of the probability landscape. Since the convergence diagnostic we used previously to determine when to stop the analysis discarded the first 25% of the samples, it makes sense to also discard 25% of the samples obtained during the analysis.
- Return to the shell window where you have MrBayes running. In the command below relburnin=yes and burninfrac=0.25 tells MrBayes to discard 25% of the samples as burnin (you could also have explicitly given the number of samples to discard - help sumt will give you details about the command and the current option settings).
sumt contype=halfcompat conformat=simple relburnin=yes burninfrac=0.25 showtreeprobs=yes
- (Scroll back so you can see the top of the output when the command is done). This command gives you a summary of the trees that are in the file you examined manually above. The option contype=halfcompat requests that a majority rule consensus tree is calculated from the set of trees that are left after discarding the burnin. This consensus is the first tree plotted to the screen. Below the consensus cladogram, a consensus phylogram is plotted. The branch lengths in this have been averaged over the trees in which that branch was present (a particular branch corresponds to a bi-partition of the data, and will typically not be present in every sampled tree). The cladogram also has "clade credibility" values. We will return to the meaning of these later in today's exercise.
- What most interests us right now is the list of trees that is printed after the phylogram. These trees are labeled "Tree 1", "Tree 2", etc, and are sorted according to their posterior probability which is indicated by a lower-case p after the tree number. (The upper-case P gives the cumulated probability of trees shown so far, and is useful for constructing a credible set). This list highlights how Bayesian phylogenetic analysis is different from maximum likelihood: Instead of finding the best tree(s), we now get a full list of how probable any possible tree is.
- The list of trees and probabilities was printed because of the option showtreeprobs=yes. Note that you probably do not want to issue that command if you have much more than 5 taxa! In that case you could instead inspect the file named primatemitDNA.nexus.trprobs which is now present in the same directory as your other files (this file is automatically produced by the sumt command).
- NOTE: Annoyingly, there is a bug in the version of mrbayes we are using here, which means leaf names are not printed on the list of trees with probabilities. However, the most probable tree here in fact is identical to the consensus tree printed above it.
Question: What is the posterior probability of the most probable tree?
Analysis of Neanderthal data (posterior probability of clades)
Question 3
The predominant theory in the 1950s and 60s (although it varied greatly from scholar to scholar) was that our earliest hominid ancestors (specifically Homo erectus) evolved in Africa and then radiated out into the world. This so-called Multiregional Hypothesis says that after H. erectus arrived in the various regions in the world hundreds of thousands of years ago, they slowly evolved into modern humans. The hypothesis thus posits that there were nearly independent origins of modern humans within the various regions of the world.
In the 1970s, paleontologist W.W. Howells proposed an alternate theory: the first Recent African Origin model. Howells argued that H. sapiens evolved solely in Africa. By the 1980s, growing data from human genetics led Stringer and Andrews to develop a model that said that the very earliest anatomically modern humans arose in Africa about 100,000 years ago and archaic populations found throughout Eurasia (including Neanderthals) might be descendants of H. erectus and later archaic types but they were not related to modern humans.
We will use the present data set to consider this issue.
Load Neanderthal data set
- In the Terminal where you have MrBayes running:
execute neanderthal.nexus delete 5-40
- As we did for the maximum likelihood analysis, we will discard some of the human sequences in order to speed up the analysis. The command delete 5-40 removes sequence number 5 to sequence number 40 from the active data set.
Investigate data
showmatrix
- This data set consists of an alignment of mitochondrial DNA from human (17 sequences), chimpanzee (1 sequence), and Neanderthal (1 sequence). The Neanderthal DNA was extracted from archaeological material, specifically bones found at Vindija in Croatia.
Start analysis
outgroup Pan_troglodytes lset nst=mixed rates=gamma mcmc ngen=500000 nchains=3 diagnfreq=10000
- Here we use the command `nst=mixed` which allows MrBayes to automatically explore all possible substitution models. Essentially, MrBayes now considers the substitution model as one more parameter, and uses MCMC to sample from the possible versions (with nst ranging from 1 to 6). This will often be the best choice when using MrBayes. (Below, I use nst=6 for pedagogical purposes, because it makes it simpler to analyse the output files).
Find posterior probability of clades
sumt contype=halfcompat showtreeprobs=no relburnin=yes burninfrac=0.25
- Examine the consensus tree that is plotted to screen: On the branches that are resolved, you will notice that numbers have been plotted. These are clade-credibility values, and are in fact the posterior probability that the clade is real (based on the present data set). These numbers are different from bootstrap values: unlike bootstrap support (which have no clear statistical meaning) these are actual probabilities. Furthermore, they have been found using a full probabilistic model, instead of neighbor joining, and have still finished in a reasonable amount of time. These features make Bayesian phylogeny very useful for assessing hypotheses about monophyly.
Question: What is the clade probability for Homo sapiens being a monophyletic group excluding the Neanderthal?
Probability distributions over other parameters
Question 4
- As the last thing, we will now turn away from the tree topology, and instead examine the other parameters that also form part of the probabilistic model. We will do this using a reduced version of the Hepatitis C virus data set that we have examined previously. Stay in the shell window where you just performed the analysis of Neanderthal sequences.
Load data set
execute hcvsmall.nexus
Define site partition
charset 1stpos=1-.\3 charset 2ndpos=2-.\3 charset 3rdpos=3-.\3 partition bycodon = 3:1stpos,2ndpos,3rdpos set partition=bycodon prset ratepr=variable
- This is an alternative way of specifying that different sites have different rates. Instead of using a gamma distribution and learning which sites have what rates from the data, we are instead using our prior knowledge about the structure of the genetic code to specify that all 1st codon positions have the same rate, all 2nd codon positions have the same rate, and all 3rd codon positions have the same rate. Specifically, charset 1stpos=1-.\3 means that we define a character set named "1stpos" which includes site 1 in the alignment followed by every third site ("\3", meaning it includes sites 1, 4, 7, 11, ...) until the end of the alignment (here denoted ".").
Specify model
lset nst=6
- This specifies that we want to use a model of the General Time Reversible (GTR) type, where all 6 substitution types have separate rate parameters.
- When the lset command was discussed previously, a few issues were glossed over. Importantly, and unlike PAUP, the lset command in MrBayes gives no information about whether nucleotide frequencies are equal or not, and whether they should be estimated from the data or not. In MrBayes this is instead controlled by defining the prior probability of the nucleotide frequencies (the command prset can be used to set priors). For instance, a model with equal nucleotide frequencies corresponds to having prior probability 1 (one) for the frequency vector (A=0.25, C=0.25, G=0.25, T=0.25), and zero prior probability for the infinitely many other possible vectors. As you will see below, the default prior is not this limited, and the program will therefore estimate the frequencies from the data.
Inspect model details
showmodel
- This command gives you a summary of the current model settings. You will also get a summary of how the prior probabilities of all model parameters are set. You will for instance notice that the nucleotide frequencies (parameter labeled "Statefreq") have a "Dirichlet" prior. We will not go into the grisly details of what exactly the Dirichlet distribution looks like, but merely note that it is a distribution over many variables, and that depending on the exact parameters the distribution can be more or less flat. The Dirichlet distribution is a handy way of specifying the prior probability distribution of nucleotide (or amino acid) frequency vectors. The default statefreq prior in MrBayes is the flat or un-informative prior dirichlet(1,1,1,1).
- We will not go into the priors for the remaining parameters in any detail, but you may notice that by default all topologies are taken to be equally likely (a flat prior on trees).
Start MCMC sampling
mcmc ngen=500000 samplefreq=100 diagnfreq=10000 nchains=3
- The run will take a while to finish (you may want to ensure that the average standard deviation of split frequencies is less than 0.01 before ending the analysis).
Compute summary of parameter values
sump relburnin=yes burninfrac=0.25
- The sump command works much like the sumt command for the non-tree parameters. Again, we are using 25% of the total number of samples as burnin.
- First, you get a plot of the lnL as a function of generation number. Values from the two independent runs are labeled "1" and "2" respectively. If the burnin is suitable, then the points should be randomly scattered over a narrow lnL interval.
- Secondly, the posterior probability distribution of each parameter is summarized by giving the mean, variance, median, and 95% credible interval.
Question: Report the mean of the relative substitution rate parameters r(AC) and r(CG).
Question 5: Based on the reported posterior means, does it seem that r(CG) is different from r(AC)?
Question 6
Marginal vs. joint distributions
- Strictly speaking the comparison above was not entirely appropriate. We first found the overall distribution of the r(CG) parameter and then compared its mean to the mean of the overall distribution of the r(AC) parameter. By doing things this way, we are ignoring the possibility that the two parameters might be associated in some way. For instance, one parameter might always be larger than the other in any individual sample, even though the total distributions overlap. We should instead be looking at the distribution over both parameters simultaneously. A probability distribution over several parameters simultaneously is called a "joint distribution" over the parameters.
- By looking at one parameter at a time, we are summing its probability over all values of the other parameters. This is called the marginal distribution.
Examine marginal distributions
- In RStudio, use the following commands to read and plot the marginal distributions of r(AC) and r(CG). Note that we are discarding the first 25% of the reads as burnin
df = read_tsv("hcvsmall.nexus.run1.p", skip=1) burnin = df$Gen %>% max() %>% multiply_by(0.25) %>% floor() df2 = df %>% filter(Gen > burnin) %>% select(CG = `r(C<->G){all}`, AC = `r(A<->C){all}` ) mcmc_intervals(df2, prob_outer = 1) mcmc_areas(df2, prob_outer = 1)
- The functions mcmc_intervals and mcmc_areas plot different views of the same posterior distributions.
- You can also simply plot the data using ggplot:
df2long = pivot_longer(df2, cols = c("CG", "AC")) ggplot(df2long) + geom_density(mapping=aes(x=value, fill=name), alpha=0.3) + labs(x="Substitution rate")
Question: Which of the following statements best describe how the marginal distributions behave?
- The two marginal distributions have a small overlap. The r(CG) distribution has the highest peak.
- The two marginal distributions have a large overlap. The r(CG) distribution has the highest peak.
- The two marginal distributions have no overlap. The r(CG) distribution has the highest peak.
- The two marginal distributions have a large overlap. The r(AC) distribution has the highest peak.
- The two marginal distributions have a small overlap. The r(AC) distribution has the highest peak.
Question 7
Examine joint distributions
- These plots and results explore the relationship between the A<->C and C<->G rates.
ggplot(df2, aes(x=CG, y=AC)) + geom_point(col="blue") + geom_abline(intercept=0, slope=1, lty=2, col="red") + xlim(0,0.25) + ylim(0,0.25) + labs(x="CG rate", y ="AC rate") ggplot(df2, aes(x=CG, y= AC)) + geom_hex(col="blue") + geom_abline(intercept=0, slope=1, lty=2, col="red") + xlim(0,0.25) + ylim(0, 0.25) + labs(x="CG rate", y ="AC rate") df2 %>% nrow() df2 %>% filter(AC>CG) %>% nrow()
Question: Based on the above plots and results: What is the joint probability that rAC > rCG?
Question 8
- Note how examining the joint distribution provides you with information that you could not get from simply comparing the marginal distributions. This very simple procedure can be used to answer many different questions.
- Now, plot the relative substitution rates at the first, second, and third codon positions:
df3 = df %>% filter(Gen > 75000) %>% select(Codon_1st = `m{1}`, Codon_2nd = `m{2}`, Codon_3rd = `m{3}` ) %>% pivot_longer(cols=c("Codon_1st", "Codon_2nd", "Codon_3rd")) ggplot(df3) + geom_density(mapping=aes(x=value, fill=name), alpha=0.3) + labs(x="Relative substitution rate")
Question: Since random mutations presumably hit all three codon positions with the same frequency, any differences must be caused by subsequent selection. How does the result fit with your knowledge of the structure of the genetic code? Which of the following statement are correct ? (More than one answer may be correct)
- Codon position 2 is the most degenerate of the codon positions.
- Codon position 1 is the most degenerate of the codon positions.
- Codon position 1 is the most conserved codon position.
- Codon position 3 is the most conserved codon position.
- Codon position 3 is the most degenerate of the codon positions.
- Codon position 2 is the most conserved codon position.