% -*- mode: noweb; noweb-default-code-mode: R-mode; -*-

%\VignetteIndexEntry{GMD - Measure Similarity between Histone Modifications}
%\VignettePackage{GMD}
%\VignetteKeywords{Generic distance between sequential data}
%\VignetteEngine{utils::Sweave}


\documentclass{article}
%% \usepackage{vignette}
\usepackage{Xvignette}



%% ------------------------------------------------------------------------
%% 
%% ------------------------------------------------------------------------


\newcommand{\currversion}{%
<<echo=FALSE,eval=TRUE,results=tex>>=%
  cat(as.character(packageVersion('GMD')))
@%
}
\newcommand{\currdate}{%
<<echo=FALSE,eval=TRUE,results=tex>>=%
  cat(unlist(strsplit(packageDescription('GMD')[['Date']],' '))[1])
@%
}


\newcommand{\GMD}{\software{GMD}}
\newcommand{\elbow}{\texttt{``elbow''}}
\newcommand{\heatmapthree}{\texttt{heatmap.3}}
\newcommand{\sliding}{\textit{sliding}}



%% ------------------------------------------------------------------------
%% title
%% ------------------------------------------------------------------------

\title{
  \CRAN{} \GMD{}: Data Processing (\currversion{})
}

\subtitle{
  Measure Similarity between Histone Modifications
}


\author[1]{Xiaobei Zhao\thanks{\lccc\ \emailme{GMD-\currversion}}}


%% \date{\today}
%% \date{January 31, 2012}

\date{
  Modified: \currdate{} \quad Compiled: \mydate{\today}
}



\def\aftertitle{
  You may find the latest version of \GMD{} and this documentation at, \\
  \url{http://CRAN.R-project.org/package=GMD} \\
}


%% ------------------------------------------------------------------------
%% 
%% ------------------------------------------------------------------------

\pagestyle{fancy}

\fancyhf{} %Clear Everything.
\fancyfoot[C]{\thepage} %Page Number
\fancyhead[LE,RO]{\zhaoetal{}}
\fancyhead[LO,RE]{\CRAN{} \GMD{}}

\setkeys{Gin}{width=1.0\textwidth}



%% ========================================================================
%% document
%% ========================================================================

\begin{document}

%% ------------------------------------------------------------------------
%% Overall Sweave and R options
%% ------------------------------------------------------------------------
\SweaveOpts{strip.white=true}
\SweaveOpts{engine=R,keep.source=TRUE,eps=FALSE,pdf=TRUE}
\SweaveOpts{prefix=TRUE,prefix.string=GMD-fig,include=TRUE} 
\SweaveOpts{width=10,height=8}


%% ------------------------------------------------------------------------
%% title
%% ------------------------------------------------------------------------

\maketitle

\aftertitle

\keywords{histone modifications, histogram, distance, heatmap, alignment, GMD}

\vspace{6ex}


%% ------------------------------------------------------------------------
%% 
%% ------------------------------------------------------------------------

\tableofcontents 
\vspace{6ex}


%% ------------------------------------------------------------------------
%% 
%% ------------------------------------------------------------------------

\section{Introduction and scope}
This is a tutorial to explain how biological data is processed to be used in \GMD{}. For detailed information of the \GMD{} functionality, please refer to the \href{http://cran.r-project.org/web/packages/GMD/GMD.pdf}{Reference Manual} and the \href{http://cran.r-project.org/web/packages/GMD/vignettes/GMD-vignette.pdf}{Vignette}\cite{GMD2014}\footnote{\url{cran.r-project.org/package=GMD}}. One case study is presented to measure the similarity of histone modifications using \code{BigWig} files from \quotes{\href{http://genome.ucsc.edu/cgi-bin/hgFileUi?db=hg19&g=wgEncodeBroadHistone}{Histone Modifications by ChIP-seq from ENCODE/Broad Institute}}. The idea and process is similar for other data formats (\code{bed}, \code{bam}, etc.).


\vspace{2ex}

%% RPS13 chr11:17095939-17099220
%% +/- 2000 upstream/downstream of the gene boundaries.
%% chr11:17093939-17101220
%% chr11 17093938 17101220
%% +/- 2000 around TSS
%% chr11 17093938 17097938

\begin{landscape}

\section{Case study: measure similarity between histone modifications}
We are going to investigate the histone modifications around the gene \textsl{RPS13 (chr11:17095939-17099220), reverse strand} generated by ChIP-seq from ENCODE/Broad Institute as shown below: 

%%\vignetteFigure{hg19-RPS13-histone.pdf}{}{1.0}{1}{the USCS Genome Browser}
\includegraphics[width=1.0\linewidth]{hg19-RPS13-histone.pdf}

Let's start with a few \code{BigWig} files of histone modifications downloaded via the \quotes{UCSC Genome Browser}\footnote{\url{http://hgdownload.cse.ucsc.edu/goldenPath/hg19/encodeDCC/wgEncodeBroadHistone/}} (assembly: hg19), for instance, there is a \code{BigWig} file for H3K4me1 \href{http://hgdownload.cse.ucsc.edu/goldenPath/hg19/encodeDCC/wgEncodeBroadHistone/wgEncodeBroadHistoneH1hescH3k4me1StdSig.bigWig}{wgEncodeBroadHistoneH1hescH3k4me1StdSig.bigWig}.

\end{landscape}




\subsection[Convert to BedGraph]{Convert to \code{BedGraph}}
We first download the \code{BigWig} files and convert them into \code{BedGraph} using the \code{bigWigToBedGraph}\footnote{\url{http://hgdownload.cse.ucsc.edu/admin/exe/}} program at a UNIX-like terminal, 

\begin{mdframed}
\begin{Schunk}
\begin{Sinput}
bigWigToBedGraph wgEncodeBroadHistoneH1hescH3k4me1StdSig.bigWig H3K4me1.full.BedGraph
\end{Sinput}
\end{Schunk}
\end{mdframed}

For a minimal demonstration, we will extract only a subregion of the data - the regions around the gene \textsl{RPS13 (chr11:17095939-17099220)} with \code{+/-2000} base pairs flanking the gene body. Note: the start position is zero-based.

\begin{mdframed}
\begin{Schunk}
\begin{Sinput}
bigWigToBedGraph wgEncodeBroadHistoneH1hescH3k4me1StdSig.bigWig H3K4me1.BedGraph \
-chrom=chr11 -start=17093938 -end=17101220

head H3K4me1.BedGraph
\end{Sinput}
\begin{Soutput}
chr11   17093950        17093975        0.92
chr11   17093975        17094000        1.84
chr11   17094000        17094025        2
chr11   17094025        17094050        2
chr11   17094050        17094075        2
chr11   17094075        17094100        2
chr11   17094100        17094125        2
chr11   17094125        17094150        2
chr11   17094150        17094175        1.08
chr11   17094175        17094200        0.16
\end{Soutput}
\end{Schunk}
\end{mdframed}

This \code{BedGraph} has four columns: \code{chr}, \code{start}, \code{end} and \code{data value}\footnote{\href{https://genome.ucsc.edu/goldenPath/help/bedgraph.html}{https://genome.ucsc.edu/goldenPath/help/bedgraph.html}}.


\subsection{Convert to a vector of depth-like signals}
The above \code{H3K4me1.BedGraph} file is packed with the \GMD{} package in the \code{extdata/hg19} subdirectory under the top level directory. Then we can read the file in \R{} and make downstream analysis.

\begin{mdframed}
<<echo=TRUE,eval=TRUE,results=verbatim,fig=TRUE,width=20,height=2.5,prefix.string=GMD-data-processing>>=
require(GMD)

## The file path of ecternal data
id <- "H3K4me1"
inFpath <- system.file('extdata/hg19',paste0(id,'.BedGraph.gz'),package="GMD",mustWork=TRUE)
print(inFpath)

## Convert to a vector of depth-like signals
res <- bedgraph.to.depth(inFpath,chr="chr11",start=17093938,end=17101220,reverse=TRUE)
str(res)

## Visualize the pattern of the signals
plot(as.numeric(names(res)),res,type="l",xlim=rev(range(as.numeric(names(res)))),
     main="H3K4me1 over RPS13", ylab="Depth", xlab="Genomic Postion (chr11)"
     )
@  
\end{mdframed}

Similarly, we have \code{BedGraph} files of other histone modifications. We will read them in \R{}.

\begin{mdframed}
<<echo=TRUE,eval=TRUE,results=verbatim,prefix.string=GMD-data-processing>>=
data_test <- list()
ids <- c("H3K4me1","H3K4me2","H3K4me3","H3K9me3","H3K27me3","H3K36me3")
for ( id in ids) {
  inFpath <- system.file('extdata/hg19',paste0(id,'.BedGraph.gz'),package="GMD",mustWork=TRUE) 
  res <- bedgraph.to.depth(inFpath,chr="chr11",start=17093938,end=17101220,reverse=TRUE)
  data_test[[id]] <- res
}
str(data_test)
@  
\end{mdframed}


\subsection{Distance measure}
\begin{mdframed}
<<echo=TRUE,eval=TRUE,results=verbatim,prefix.string=GMD-data-processing>>=
x <- gmdm(data_test,sliding=FALSE)
print(x)
@  
\end{mdframed}


\subsection{Heatmap of the distance matrix}
\begin{mdframed}
<<echo=TRUE,eval=TRUE,results=hide,fig=TRUE,include=TRUE,width=7,height=7,prefix.string=GMD-data-processing>>=
heatmap.3(x,dendrogram="both",cexCol=0.85,cexRow=0.85)
@  
\end{mdframed}
%%\includegraphics[width=0.8\textwidth]{GMD-data-processing-006.pdf}


\subsection{Alignment of the distributions (without sliding)}
\begin{mdframed}
<<echo=TRUE,eval=TRUE,results=hide,fig=TRUE,include=TRUE,width=9,height=9,prefix.string=GMD-data-processing>>=
plot(x,cex.text=2,type="polygon",if.plot.new=FALSE) 
#- setting if.plot.new to TRUE to pop-up a auto-adjust window
@  
\end{mdframed}
%%includegraphics[width=0.9\textwidth]{GMD-data-processing-007.pdf}




\clearpage


%% \nocite{*}

\bibliographystyle{plain}
\bibliography{GMD}


\end{document}


