%\VignetteIndexEntry{05. ChIP-seq}
%\VignettePackage{useR2013}



\section{ChIP-seq}
\label{sec:chipseq}

ChIP-seq and similar experiments combine chromosome
immuno-precipitation (ChIP) with sequence analysis. The idea is that
the ChIP protocol enriches genomic DNA for regions of interest, e.g.,
sites to which transcription factors are bound. The regions of
interest are then subject to high throughput sequencing, the reads
aligned to a reference genome, and the location of mapped reads
(`peaks') interpreted as indicators of the ChIP'ed regions. Reviews
include those by Park and colleagues \cite{pmid19736561,
  pmid21356108}; there is a large collection of peak-calling software,
some features of which are summarized in Pepke et
al. \cite{pmid19844228}.

The main challenge in early ChIP-seq studies was to develop efficient
peak-calling software, often tailored to the characteristics of the
peaks of interest (e.g., narrow and well-defined CTCF binding sites,
vs.\ broad histone marks).  More comprehensive studies draw from
multiple samples, e.g., in the ENCODE project \cite{pmid21179089,
  pmid21526222}. Decreasing sequence costs and better experimental and
data analytic protocols mean that these larger-scale studies are
increasingly accessible to individual investigators. Peak-calling in
this kind of study represents an initial step, but interpretting
analyses derived from multiple samples present significant analytic
challenges.  \Bioconductor{} packages play a role in several stages of
a ChIP-seq analysis. (Table \ref{tab:chipseq-pkgs}; a more
comprehensive list is under the
\href{http://bioconductor.org/packages/2.10/BiocViews.html#___ChIPseq}{ChIPseq}
and
\href{http://bioconductor.org/packages/2.10/BiocViews.html#___HighThroughputSequencing}{HighThroughputSequencing}
BiocViews terms).

\begin{table}
  \centering
  \caption{Selected \Bioconductor{} packages for RNA-seq analysis.}
  \label{tab:chipseq-pkgs}
  \begin{tabular}{lp{.7\textwidth}}
    Package & Description\\
    \hline

    \Biocpkg{qrqc} & Quality assessment; also \Biocpkg{ShortRead},
    \Biocpkg{chipseq}.\\

    \Biocpkg{PICS} & Peak calling, also \Biocpkg{mosaics},
    \Biocpkg{chipseq}, \Biocpkg{ChIPseqR}, \Biocpkg{BayesPeak},
    \Biocpkg{nucleR} (nucleosome positioning). \\

    \Biocpkg{ChIPpeakAnno} & Peak annotation.\\

    \Biocpkg{DiffBind} & Multiple-experiment analysis.\\

    \Biocpkg{MotIV} & Motif identification and validation; also
    \Biocpkg{rGADEM}.\\

    \hline
  \end{tabular}
\end{table}

Our attention is on analyzing multiple samples from a single
experiment, and identifying and annotating peaks. We start with a
typical work flow re-iterating key components in an exploration of
data from the ENCODE project, and continue with down-stream analysis
including motif discovery and annotation.

\subsection{Initial Work Flow}

We use data from GEO accession
\href{http://www.ncbi.nlm.nih.gov/projects/geo/query/acc.cgi?acc=GSE30263}{GSE30263},
representing ENCODE CTCF binding sites. CTCF is a zinc finger
transcription factor. It is a sequence specific DNA binding protein
that functions as an insulator, blocking enhancer activity, and
possibly the spread of chromatin structure.  The original analysis
involved Illumina ChIP-seq and matching `input' lanes of 1 or 2
replicates from many cell lines. The GEO accession includes BAM files
of aligned reads, in addition to tertiary files summarizing identified
peaks. We focus on 15 cell lines aligned to hg19.

As a precursor to analysis, it is prudent to perform an overall
quality assesssement of the data; an example is available:
\begin{Schunk}
\begin{Sinput}
> rpt <- system.file("GSE30263_qa_report", "index.html",
+            package="useR2013", mustWork=TRUE)
> if (interactive())
+     browseURL(rpt)
\end{Sinput}
\end{Schunk}
%
The main computational stages in the original work flow involved
alignment using Bowtie, followed by peak identification using an
algorithm (`HotSpots', \cite{pmid15550541}) originally developed for
lower-throughput methodologies. We collated the output files from the
original analysis with a goal of enumerating all peaks from all files,
but collapsing the coordinates of sufficiently similar peaks to a
common location. The \Biocpkg{DiffBind} package provides a formalism
with which to do these operations. Here we load the data as an \R{}
object \Robject{stam} (an abbreviation for the lab generating the
data).
\begin{Schunk}
\begin{Sinput}
> stamFile <- system.file("data", "stam.Rda", package="useR2013")
> load(stamFile)
> stam
\end{Sinput}
\begin{Soutput}
class: SummarizedExperiment 
dim: 369674 96 
exptData(0):
assays(2): Tags PVals
rownames: NULL
rowData metadata column names(0):
colnames(96): A549_1 A549_2 ... Wi38_1 Wi38_2
colData names(10): CellLine Replicate ... PeaksDate PeaksFile
\end{Soutput}
\end{Schunk}

\begin{Exercise}
  Explore \Robject{stam}. Tabulate the number of peaks represented
  1, 2, \ldots, 96 times. We expect replicates to have
  similar patterns of peak representation; do they?
\end{Exercise}
\begin{Solution}
  Load the data and display the \Rclass{SummarizedExperiment}
  instance. The \Rfunction{colData} summarizes information about each
  sample, the \Rfunction{rowData} about each peak. Use
  \Rfunction{xtabs} to summarize \Rcode{Replicate} and \Rcode{CellLine}
  representation within \Robject{colData(stam)}.
\begin{Schunk}
\begin{Sinput}
> head(colData(stam), 3)
\end{Sinput}
\begin{Soutput}
DataFrame with 3 rows and 10 columns
             CellLine Replicate   TotTags  TotPeaks      Tags     Peaks FastqDate
          <character>  <factor> <integer> <integer> <numeric> <numeric>    <Date>
A549_1           A549         1   1857934     50144   1569215     43119     15150
A549_2           A549         2   2994916     77355   2881475     73062     15150
Ag04449_1     Ag04449         1   5041026     81855   4730232     75677     14904
          FastqSize PeaksDate                                        PeaksFile
          <numeric>    <Date>                                      <character>
A549_1          463     15150    wgEncodeUwTfbsA549CtcfStdPkRep1.narrowPeak.gz
A549_2          703     15150    wgEncodeUwTfbsA549CtcfStdPkRep2.narrowPeak.gz
Ag04449_1       368     14904 wgEncodeUwTfbsAg04449CtcfStdPkRep1.narrowPeak.gz
\end{Soutput}
\begin{Sinput}
> head(rowData(stam), 3)
\end{Sinput}
\begin{Soutput}
GRanges with 3 ranges and 0 metadata columns:
      seqnames         ranges strand
         <Rle>      <IRanges>  <Rle>
  [1]     chr1 [10100, 10370]      *
  [2]     chr1 [15640, 15790]      *
  [3]     chr1 [16100, 16490]      *
  ---
  seqlengths:
        chr1      chr2      chr3      chr4 ...     chr21     chr22      chrX      chrY
   249250621 243199373 198022430 191154276 ...  48129895  51304566 155270560  59373566
\end{Soutput}
\begin{Sinput}
> xtabs(~Replicate + CellLine, colData(stam))[,1:5]
\end{Sinput}
\begin{Soutput}
         CellLine
Replicate A549 Ag04449 Ag04450 Ag09309 Ag09319
        1    1       1       1       1       1
        2    1       1       1       1       1
\end{Soutput}
\end{Schunk}
  Extract the \Rcode{Tags} matrix from the assays. This is a standard
  \R{} \Rclass{matrix}. Test which matrix elements are non-zero, tally
  these by row, and summarize the tallies. This is the number of times
  a peak is detected, across each of the samples
\begin{Schunk}
\begin{Sinput}
> m <- assays(stam)[["Tags"]] > 0 # peaks detected...
> peaksPerSample <- table(rowSums(m))
> head(peaksPerSample)
\end{Sinput}
\begin{Soutput}
     1      2      3      4      5      6 
174574  35965  18939  12669   9143   7178 
\end{Soutput}
\begin{Sinput}
> tail(peaksPerSample)
\end{Sinput}
\begin{Soutput}
   91    92    93    94    95    96 
 1226  1285  1542  2082  2749 14695 
\end{Soutput}
\end{Schunk}
  To explore similarity between replicates, extract the matrix of
  counts. Transform the counts using the \Rfunction{asinh} function (a
  log-like transform, except near 0; are there other methods for
  transformation?), and use the `correlation' distance
  (\Rfunction{cor.dist}, from \Biocpkg{bioDist}) to measure
  similarity. Cluster these using a hierarchical algorithm, via the
  \Rfunction{hclust} function.
\begin{Schunk}
\begin{Sinput}
> library(bioDist)                   # for cor.dist
> m <- asinh(assays(stam)[["Tags"]]) # transformed tag counts
> d <- cor.dist(t(m))                # correlation distance
> h <- hclust(d)                     # hierarchical clustering
\end{Sinput}
\end{Schunk}
  Plot the result, as in Figure~\ref{fig:chipseq:replicate_heatmap}.
\begin{Schunk}
\begin{Sinput}
> plot(h, cex=.8, ann=FALSE)
\end{Sinput}
\end{Schunk}
\end{Solution}
\begin{figure}
  \centering
  \includegraphics[width=\textwidth, height=!]{chipseq-stam-similarity.png}
  \caption{Hierarchical clustering of ENCODE samples.}
  \label{fig:chipseq:replicate_heatmap}
\end{figure}

\subsection{Motifs}

Transcription factors and other common regulatory elements often
target specific DNA sequences (`motifs'). These are often
well-characterized, and can be used to help identify, \emph{a priori},
regions in which binding is expected. Known binding motifs may also be
used to identify promising peaks identified using \emph{de novo} peak
discovery methods like \software{MACS}.  This section explores use of
known binding motifs to characterize peaks; packages such as
\Biocpkg{MotIV} can assist in motif discovery.

\paragraph{Known binding motifs}

The \href{http://jaspar.genereg.net}{JASPAR} data base curates known
binding motifs obtained from the literature. A binding motif is
summarized as a \emph{position weight matrix} PWM. Rows of a PWM
correspond to nucleotides, columns to positions, and entries to the
probability of the nucleotide at that position. Each start position in
a reference sequence can be compared and scored for similarity to the
PWM, and high-scoring positions retained.

\begin{Exercise}
  The objective of this exercise is to identify occurrences of the
  CTCF motif on chromosome 1 of \Hsap.
  
  Load needed packages. \Biocpkg{Biostrings} can represent a PWM and
  score a reference sequence. The
  \Biocpkg{BSgenome.Hsapiens.UCSC.hg19} package contains the hg19
  build of \Hsap, retrieved from the UCSC genome
  browser. \Biocpkg{seqLogo} and \Rpackage{lattice} are used for
  visualization.

  Retrieve the PWM for CTCF, with JASPAR id MA0139.1.pfm, using the
  helper function \Rfunction{getJASPAR} defined in the
  \Rpackage{useR2013} package. 

  Use \Rfunction{matchPWM} to score the plus strand of chr1 for the
  CTCF PWM. Visualize the distribution of scores using, e.g.,
  \Rfunction{densityplot}, and summarize the high-scoring matches
  (using \Rfunction{consensusMatrix}) as a \Rfunction{seqLogo}.

  As an additional exercise, work up a short code segment to apply the
  PWM to both strands (see \Rcode{?PWM} for some hints) and to all
  chromosomes.
\end{Exercise}
\begin{Solution}
  Here we load the required packages and retrieve the position weight
  matrix for CTCF.
\begin{Schunk}
\begin{Sinput}
> library(Biostrings)
> library(BSgenome.Hsapiens.UCSC.hg19)
> library(seqLogo)
> library(lattice)
> pwm <- getJASPAR("MA0139.1") # useR2013::getJASPAR
\end{Sinput}
\end{Schunk}
  Chromosome 1 can be loaded with \Rcode{Hsapiens[["chr1"]]};
  \Rfunction{matchPWM} returns a `view' of the high-scoring locations
  matching the PWM. Scores are retrieved from the PWM and hits using
  \Rfunction{PWMscoreStartingAt}.
\begin{Schunk}
\begin{Sinput}
> chrid <- "chr1"
> hits <-matchPWM(pwm, Hsapiens[[chrid]]) # '+' strand
> scores <- PWMscoreStartingAt(pwm, subject(hits), start(hits))
\end{Sinput}
\end{Schunk}
  The distribution of scores can be visualized with, e.g.,
  \Rfunction{densityplot} from the \Rpackage{lattice} package.
\begin{Schunk}
\begin{Sinput}
> densityplot(scores, xlim=range(scores), pch="|")
\end{Sinput}
\end{Schunk}
%%
   \Rfunction{consensusMatrix} applied to the views in \Robject{hits}
   returns a position frequency amtrix; this can be plotted as a logo,
   with the result in Figure~\ref{fig:seqlogo}. Reassuringly, the
   found sequences have a logo very similar to the expected.
\begin{Schunk}
\begin{Sinput}
> cm <- consensusMatrix(hits)[1:4,]
> seqLogo(makePWM(scale(cm, FALSE, colSums(cm))))
\end{Sinput}
\end{Schunk}
\end{Solution}

\begin{figure}
  \centering
  \includegraphics[width=.4\textwidth]{ChIPSeq-CTCF-PWM-found}
  \caption{CTCF position weight matrix of found sites on the plus
    strand of chr1 (hits within 80\% of maximum score).}
  \label{fig:seqlogo}
\end{figure}

% FIXME: \section{Resources}
