%\VignetteIndexEntry{xtail}
%\VignetteDepends{xtail}
%\VignetteKeywords{xtail}
%\VignettePackage{xtail}
%\VignetteEngine{knitr::knitr}

% To compile this document
% library('knitr');rm(list=ls());knit('xtail.Rnw')

\documentclass[12pt]{article}


<<knitr, echo=FALSE, results="hide">>=
library("knitr")
opts_chunk$set(
  tidy=FALSE,
  fig.show="hide",
  cache=TRUE,
  message=FALSE)
@

\title{Genome-wide assessment of differential translations \\ with ribosome profiling data \\-- the xtail package}
\author{Zhengtao Xiao$^{1-3}$, Qin Zou$^{1,3}$, Yu Liu$^{1-3}$, and Xuerui Yang$^{1-3}$
\\[1em] \small{$^{1}$MOE Key Laboratory of Bioinformatics, }
\\ \small{$^{2}$Tsinghua-Peking Joint Center for Life Sciences,}
\\ \small{$^{3}$School of Life Sciences, Tsinghua University, Beijing 100084, China.}}

<<<style,eval=TRUE,echo=FALSE,results='asis'>>=
BiocStyle::latex()
@

\begin{document}

<<include=FALSE>>=
library(knitr)
opts_chunk$set(
concordance=TRUE
)
@

\maketitle
\vspace{15em}

\begin{center}
    \begin{tabular}{ | l | }
      \hline
      \textbf{xtail version:} \Sexpr{packageVersion("xtail")} \\
      \\
      If you use xtail in published research, please cite:  \\
      Z. Xiao, Q. Zou, Y. Liu, X. Yang: \textbf{Genome-wide assessment} \\
      \textbf{of differential translations with ribosome profiling data}. \\
      \emph{Nat Commun} 2016, \textbf{7}:11194. \\
      \url{http://www.ncbi.nlm.nih.gov/pubmed/27041671}  \\
      \hline
    \end{tabular}
\end{center}

\newpage
\section{Introduction}

This package, Xtail, is for identification of genes undergoing differential translation across two conditions with ribosome profiling data. Xtail is based on a simple assumption that if a gene is subjected to translational dyresgulation under certain exprimental or physiological condition, the change of its RPF abundance should be discoordinated with that of mRNA expression. Specifically, \verb'Xtail' consists of three major steps: (1) modeling of ribosome profiling data using negative binomial distribution (NB), (2) estabilishment of probability distributions for fold changes of mRNA or RPF (or RPF-to-mRNA ratios), and (3) evaluation of statistical significance and magnitude of differential translations. The differential translation of each gene is evaluated by two pipelines:
in the first one, \verb'Xtail' calculated the posterior probabilities for a range of mRNA or RPF fold changes, and eventually estabilished their probability distributions. These two distributions, represented as probability vectors, were then used to estabilish a joint probability distribution matrix, from which a new probability distribution were generated for differential translation. The P-values, point estimates and credible intervals of differential tranlsations were then calculated based on these results. In the other parallel pipline, \verb'Xtail' established probability distributions for RPF-to-mRNA ratios in two conditions and derived another distribution for differential translation. The more conserved set of results from these two parallel piplines was used as the final result. With this strategy, \verb'Xtail' performs quantification of differential translation for each gene, i.e., the extent to which a gene's translational rate is not coordinated with the change of the mRNA expression.

By default, \verb'Xtail' adapts the strategy of DESeq2 [1] to normalize read counts of mRNA and RPF in all samples, and fits NB distributions with dispersions $\alpha$ and $\mu$.

This guide provides step-by-step instructions on how to load data, how to excute the package and how to interpret output.

\section{Data Preparation}

The \verb'Xtail' package uses read counts of RPF and mRNA, in the form of rectangular table of values. The rows and columns of the table represent the genes and samples, respectively. Each cell in the \textsl{g-th} row and the \textsl{i-th} columns is the count number of reads mapped to gene \textsl{g} in sample \textsl{i}.

Xtail takes in raw read counts of RPF and mRNA, and performs median-of-ratios normalization by default. This normalization method is also recommend by Reddy R. [2]. Alternatively, users can provide normalized read counts and skip the built-in normalization in Xtail.

In this vignette, we select a published ribosome profiling dataset from human prostate cancer cell PC3 after mTOR signaling inhibition with PP242 [3]. This dataset consists of mRNA and RPF data for 11391 genes in two replicates from each of the two conditions("treatment" vs. "control").

\section{An Example}

Here we run \verb'Xtail' with the ribosome profiling data described above. First we load the library and data.

<<begain,results="hold",message=FALSE>>=
library(xtail)
data(xtaildata)
@


Next we can view the first five lines of the mRNA (\verb'mrna') and RPF (\verb'rpf') elements of \verb'xtaildata'.

<<>>=
mrna <- xtaildata$mrna
rpf <- xtaildata$rpf
head(mrna,5)
head(rpf,5)
@


We assign condition labels to the columns of the mRNA and RPF data.

<<>>=
condition <- c("control","control","treat","treat")
@


Next, we run the main function, \Rfunction{xtail()}. By default, the second condition (here is "treat") would be compared against the first condition (here is "control"). Those genes with the minimum average expression of mRNA counts and RPF counts among all samples larger than 1 are used (can be changed by setting \verb'minMeanCount'). All the available CPU cores are used for running program. The argument \verb`"bins"` is the number of bins used for calculating the probability densities of log2FC and log2R. This paramater will determine accuracy of the final pvalue. Here, in order to keep the run-time of this vignette short, we will set \verb'bins' to "1000". Detailed description of the arguments of the \texttt{xtail} function can be found by typing \texttt{?xtail} or \texttt{help(xtail)} at the \textbf{R} prompt.

<<>>=
test.results <- xtail(mrna,rpf,condition,bins=1000)
@

We can summarize some basic information of xtail results using the summary function (type \texttt{?summary} for further information).

<<summary>>=
summary(test.results)
@

Now we can extract a results table using the function \Rfunction{resultsTable}, and examine the first five lines of the results table.

<<inspectData,echo=TRUE>>=
test.tab <- resultsTable(test.results)
head(test.tab,5)
@

The results of fist pipline are named with suffix "\_v1", which are generated by comparing mRNA and RPF log2 fold changes: The element \verb'log2FC_TE_v1' represents the log2 fold change of TE; The \verb"pvalue_v1" represent statistical significance. The sencond pipline are named with suffix "\_v2", which are derived by comparing log2 ratios between two conditions: \verb'log2FC_TE_v2', and \verb'pvalue_v2' are log2 ratio of TE, and pvalues. Finally, the more conserved results (with larger-Pvalue) was select as the final assessment of differential translation, which are named with suffix "\_final". The \verb'pvalue.adjust' is the estimated false discovery rate corresponding to the \verb'pvalue_final'.

Users can also get the log2 fold changes of mRNA and RPF, or the log2 ratios of two conditions by setting "log2FCs" or "log2Rs" as "TRUE" in resultsTable. And the results table can be sorted by assigning the "sort.by". Detailed description of the \texttt{resultsTable} function can be found by typing \texttt{?resultsTable}.

Finally, the plain-text file of the results can be exported using the functions \textsl{write.csv} or \textsl{write.table}.

<<writeResult,eval=FALSE>>=
write.table(test.tab,"test_results.txt",quote=F,sep="\t")
@

We also provide a very simple function, \texttt{write.xtail} (using the write.table function), to export the \verb'xtail' result (test.results) to a tab delimited file.

<<writextailResult,eval=FALSE>>=
write.xtail(test.results,"test_results.txt",quote=F,sep="\t")
@


\section{Visualization}

\subsection{plotFCs}

In \verb'Xtail', the function \Rfunction{plotFCs} shows the result of the differential expression at the two expression levels, where each gene is a dot whose position is determined by its log2 fold change (log2FC) of transcriptional level (\verb'mRNA_log2FC'), represented on the x-axis, and the log2FC of translational level (\verb'RPF_log2FC'), represented on the y-axis (Figure \ref{fig:plotFCs}). The optional input parameter of \Rfunction{plotFCs} is \verb'log2FC.cutoff', a non-negative threshold value that will divide the genes into different classes:

\begin{itemize}
 \item \verb'blue': for genes whoes \verb'mRNA_log2FC' larger than \verb'log2FC.cutoff' (transcriptional level).
 \item \verb'red': for genes whoes \verb'RPF_log2FC' larger than \verb'log2FC.cutoff' (translational level).
 \item \verb'green': for genes changing homodirectionally at both level.
 \item \verb'yellow': for genes changing antidirectionally at two levels.
\end{itemize}


<<plotFCs,fig.width=5.5, fig.height=5.5>>=
plotFCs(test.results)
@
\begin{figure}[h]
\centering
\includegraphics[width=.5\textwidth]{figure/plotFCs-1}
\caption{Scatter plot of log2 fold changes}
\label{fig:plotFCs}
\end{figure}

Those genes in which the difference of \verb'mRNA_log2FC' and \verb'RPF_log2FC' did not exceed more than \verb'log2FC.cutoff' are excluded. The points will be color-coded with the \verb'pvalue_final' obtained with \verb'xtail' (more significant p values having darker color). By default the \verb'log2FC.cutoff' is 1.


\subsection{plotRs}

Similar to \Rfunction{plotFCs}, the function \Rfunction{plotRs} shows the RPF-to-mRNA ratios in two conditions, where the position of each gene is determined by its RPF-to-mRNA ratio (log2R) in two conditions, represented on the x-axis and y-axis respectively (Figure \ref{fig:plotRs}). The optional input parameter \verb'log2R.cutoff' (non-negative threshold value) will divide the genes into different classes:
\begin{itemize}
 \item \verb'blue': for genes whoes \verb'log2R' larger in first condition than second condition.
 \item \verb'red': for genes whoes \verb'log2R' larger in second condition than the first condition.
 \item \verb'green': for genes whoes \verb'log2R' changing homodirectionally in two condition.
 \item \verb'yellow': for genes whoes \verb'log2R' changing antidirectionally in two conditon.
\end{itemize}

<<plotRs,fig.width=5.5, fig.height=5.5>>=
plotRs(test.results)
@
\begin{figure}[h]
\centering
\includegraphics[width=.5\textwidth]{figure/plotRs-1}
\caption{Scatter plot of log2 RPF-to-mRNA ratios}
\label{fig:plotRs}
\end{figure}

Those genes in which the difference of \verb'log2R' in two conditions did not exceed more than \verb'log2R.cutoff' are excluded. The points will be color-coded with the \verb'pvalue_final' obtained with \verb'xtail' (more significant p values having darker color). By default the \verb'log2R.cutoff' is 1.


\subsection{volcanoPlot}

It can also be useful to evaluate the fold changes cutoff and p values thresholds by looking at the volcano plot. A simple function for making this plot is \Rfunction{volcanoPlot}, in which the \verb'log2FC_TE_final' is plotted on the x-axis and the negative log10 \verb'pvalue_fianl' is plotted on the y-axis (Figure \ref{fig:volcanoplot}).

<<volcanoPlot,fig.width=5.5, fig.height=5.5>>=
volcanoPlot(test.results)
@
\begin{figure}[h]
\centering
\includegraphics[width=.5\textwidth]{figure/volcanoPlot-1}
\caption{volcano plot.}
\label{fig:volcanoplot}
\end{figure}



\section*{Session Info}

<<sessInfo>>=
sessionInfo()
@

\begin{thebibliography}{99}
\bibitem{DESeq2}
Love MI, Huber W, Anders S: \textsl{Moderated Estimation of Fold Change and Dispersion for RNA-Seq Data with DESeq2}. Genome Biology 2014, 15:550.
A Comparison of Methods: Normalizing High-Throughput RNA Sequencing Data.
\bibitem{Reddy}
Reddy R: \textsl{A Comparison of Methods: Normalizing High-Throughput RNA Sequencing Data. Cold Spring Harbor Labs Journals}. bioRxiv 2015:1-9.
\bibitem{PC3}
Hsieh AC, Liu Y, Edlind MP, et al.: \textsl{The translational landscape of mTOR signaling steers cancer initiation and metastasis}. Nature 2012, 485:55-61.
\end{thebibliography}

\end{document}

