%\VignetteIndexEntry{segmentSeq: small RNA locus detection}
%\VignettePackage{segmentSeq}

\documentclass[a4paper]{article}

%\usepackage{rotating}

\title{segmentSeq: methods for identifying small RNA loci from high-throughput sequencing data}
\author{Thomas J. Hardcastle}

<<<style-Sweave, eval=TRUE, echo=FALSE, results=tex>>=
BiocStyle::latex()
@ 

\begin{document}

\maketitle

\section{Introduction}

High-throughput sequencing technologies allow the production of large volumes of short sequences, which can be aligned to the genome to create a set of \textsl{matches} to the genome. By looking for regions of the genome which to which there are high densities of matches, we can infer a segmentation of the genome into regions of biological significance. The methods we propose allows the simultaneous segmentation of data from multiple samples, taking into account replicate data, in order to create a consensus segmentation. This has obvious applications in a number of classes of sequencing experiments, particularly in the discovery of small RNA loci and novel mRNA transcriptome discovery.

We approach the problem by considering a large set of potential \textsl{segments} upon the genome and counting the number of tags that match to that segment in multiple sequencing experiments (that may or may not contain replication). We then adapt the empirical Bayesian methods implemented in the \verb'baySeq' package \cite{Hardcastle:2010} to establish, for a given segment, the likelihood that the count data in that segment is similar to background levels, or that it is similar to the regions to the left or right of that segment. We then rank all the potential segments in order of increasing likelihood of similarity and reject those segments for which there is a high likelihood of similarity with the background or the regions to the left or right of the segment. This gives us a large list of overlapping segments. We reduce this list to identify non-overlapping loci by choosing, for a set of overlapping segments, the segment which has the lowest likelihood of similarity with either background or the regions to the left or right of that segment and rejecting all other segments that overlap with this segment. For fuller details of the method, see Hardcastle \textsl{et al.} \cite{Hardcastle:2011}.

\section{Preparation}

We begin by loading the \verb'segmentSeq' package.

<<>>=
  library(segmentSeq)
@

Note that because the experiments that \verb'segmentSeq' is designed to analyse are usually massive, we should use (if possible) parallel processing as implemented by the \verb'parallel' package. If using this approach, we need to begin by define a \textsl{cluster}. The following command will use eight processors on a single machine; see the help page for 'makeCluster' for more information. If we don't want to parallelise, we can proceed anyway with a \verb'NULL' cluster.

<<results = hide, eval = TRUE>>=
if(require("parallel")) 
{
    numCores <- min(8, detectCores())
    cl <- makeCluster(numCores)
} else {
    cl <- NULL
}
@

The \verb'readGeneric' function is able to read in tab-delimited files which have appropriate column names, and create an \verb'alignmentData' object. Alternatively, if the appropriate column names are not present, we can specify which columns to use for the data. In either case, to use this function we pass a character vector of files, together with information on which data are to be treated as replicates to the function. We also need to define the lengths of the chromosome and specifiy the chromosome names as a character. The data here, drawn from text files in the 'data' directory of the \verb'segmentSeq' package are taken from the first million bases of an alignment to chromosome 1 and the first five hundred thousand bases of an alignment to chromosome 2 of \textsl{Arabidopsis thaliana} in a sequencing experiment where libraries `SL9' and `SL10' are replicates, as are `SL26' and `SL32'. Libraries `SL9' and `SL10' are sequenced from an Argonaute 6 IP, while `SL26' and `SL32' are an Argonaute 4 IP.

A similar function, \verb'readBAM' performs the same operation on files in the BAM format. Please consult the help page for further details.

<<>>=
chrlens <- c(1e6, 2e5)

datadir <- system.file("extdata", package = "segmentSeq")
libfiles <- c("SL9.txt", "SL10.txt", "SL26.txt", "SL32.txt")
libnames <- c("SL9", "SL10", "SL26", "SL32")
replicates <- c("AGO6", "AGO6", "AGO4", "AGO4")

aD <- readGeneric(files = libfiles, dir = datadir,
                  replicates = replicates, libnames = libnames, 
                  chrs = c(">Chr1", ">Chr2"), chrlens = chrlens,
                  polyLength = 10, header = TRUE, gap = 200)
aD
@ 

Next, we process this \verb'alignmentData' object to produce a \verb'segData' object. This \verb'segData' object contains a set of potential segments on the genome defined by the start and end points of regions of overlapping alignments in the \verb'alignmentData' object. It then evaluates the number of tags that hit in each of these segments.

<<>>=
sD <- processAD(aD, gap = 100, cl = cl)
sD
@ 

We can now construct a segment map from these potential segments.

\subsection*{Segmentation by heuristic methods}

A fast method of segmentation can be achieved by exploiting the bimodality of the densities of small RNAs in the potential segments. In this approach, we assign each potential segment to one of two clusters for each replicate group, either as a segment or a null based on the density of sequence tags within that segment. We then combine these clusterings for each replicate group to gain a consensus segmentation map.

<<>>=
hS <- heuristicSeg(sD = sD, aD = aD, RKPM = 1000, largeness = 1e8, getLikes = TRUE, cl = cl)
@ 

\subsection*{Segmentation by empirical Bayesian methods}

A more refined approach to the problem uses an existing segment map (or, if not provided, a segment map defined by the \verb'hS' function) to acquire empirical distributions on the density of sequence tags within a segment. We can then estimate posterior likelihoods for each potential segment as being either a true segment or a null. We then identify all
potential segments in the with a posterior likelihood of being a segment
greater than some value 'lociCutoff' and containing no subregion with a posterior
likelihood of being a null greater than 'nullCutoff'. We then greedily
select the longest segments satisfying these criteria that do not
overlap with any other such segments in defining our segmentation map.

<<>>=
classSegs <- classifySeg(sD = sD, aD = aD, cD = hS,
                         subRegion = NULL, getLikes = TRUE,
                         lociCutoff = 0.9, nullCutoff = 0.9, cl = cl)
classSegs
@ 

By one of these methods, we finally acquire an annotated \verb'lociData' object, with the annotations describing the co-ordinates of each segment.


We can use this \verb'lociData' object, in combination with the \verb'alignmentData' object, to plot the segmented genome.

<<fig = FALSE, label=segPlot, height = 10, width = 12>>=
par(mfrow = c(2,1), mar = c(2,6,2,2))
plotGenome(aD, hS, chr = ">Chr1", limits = c(1, 1e5),
           showNumber = FALSE, cap = 50)
plotGenome(aD, classSegs, chr = ">Chr1", limits = c(1, 1e5),
           showNumber = FALSE, cap = 50)
@

%\begin{sidewaysfigure}[!ht]
\begin{figure}[!ht]
\begin{center}

<<label=figSeg, fig=TRUE,echo=FALSE>>=
<<segPlot>>
@ 
\caption{The segmented genome (first $10^5$ bases of chromosome 1.}
\label{fig:Seg}
\end{center}
\end{figure}
%\end{sidewaysfigure}

Given the calculated likelihoods, we can filter the segmented genome by controlling on likelihood, false discovery rate, or familywise error rate

<<>>=
loci <- selectLoci(classSegs, FDR = 0.05)
loci
@ 

This \verb'lociData' object can now be examined for differential expression with the \verb'baySeq' package.

Finally, to be a good citizen, we stop the cluster we started earlier:

<<<stopCluster>>=
if(!is.null(cl))
    stopCluster(cl)
@

\section*{Session Info}

<<>>=
sessionInfo()
@ 

\begin{thebibliography}{99}
\bibitem{Hardcastle:2010} Thomas J. Hardcastle and Krystyna A. Kelly. \textsl{baySeq: Empirical Bayesian Methods For Identifying Differential Expression In Sequence Count Data.} BMC Bioinformatics (2010).
\bibitem{Hardcastle:2011} Thomas J. Hardcastle and Krystyna A. Kelly and David C. Baulcombe. \textsl{Identifying small RNA loci from high-throughput sequencing data.} Bioinformatics (2012).

\end{thebibliography}

\end{document}




