%\VignetteIndexEntry{1. An Introduction to the GenomicRanges Package}
%\VignetteKeywords{sequence, sequencing}
%\VignettePackage{GenomicRanges}
\documentclass{article}

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

\newcommand{\GenomicRanges}{\Biocpkg{GenomicRanges}}

\title{An Introduction to the GenomicRanges Package}
\author{Marc Carlson, Patrick Aboyoun, Herv\'{e} Pag\`{e}s, and Martin Morgan}
\date{\today; updated 11 January, 2018}

\begin{document}

\maketitle

\tableofcontents

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Introduction}

The \Biocpkg{GenomicRanges} package serves as the foundation for
representing genomic locations within the \software{Bioconductor}
project.  In the \software{Bioconductor} package hierarchy, it builds
upon the \Biocpkg{IRanges} (infrastructure) package and provides
support for the \Biocpkg{BSgenome} (infrastructure),
\Biocpkg{Rsamtools} (I/O), \Biocpkg{ShortRead} (I/O \& QA),
\Biocpkg{rtracklayer} (I/O), \Biocpkg{GenomicFeatures}
(infrastructure), \Biocpkg{GenomicAlignments} (sequence reads),
\Biocpkg{VariantAnnotation} (called variants), and many other
\software{Bioconductor} packages.

This package lays a foundation for genomic analysis by introducing
three classes (\Rclass{GRanges}, \Rclass{GPos}, and \Rclass{GRangesList}),
which are used to represent genomic ranges, genomic positions, and groups
of genomic ranges. This vignette focuses on the \Rclass{GRanges} and
\Rclass{GRangesList} classes and their associated methods.

The \Biocpkg{GenomicRanges} package is available at
\href{https://bioconductor.org}{https://bioconductor.org} and can be
installed via \Rfunction{biocLite}:
%% 
<<biocLite, eval=FALSE>>=
source("https://bioconductor.org/biocLite.R")
biocLite("GenomicRanges")
@
%% 
A package only needs to be installed once. Load the package into an
\R{} session with
%% 
<<initialize, results=hide>>=
library(GenomicRanges)
@


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{\Rclass{GRanges}: Genomic Ranges}

The \Rclass{GRanges} class represents a collection of genomic ranges
that each have a single start and end location on the genome. It can be
used to store the location of genomic features such as contiguous binding
sites, transcripts, and exons. These objects can be created by using the
\Rfunction{GRanges} constructor function. For example,

<<example-GRanges>>=
gr <- GRanges(
    seqnames = Rle(c("chr1", "chr2", "chr1", "chr3"), c(1, 3, 2, 4)),
    ranges = IRanges(101:110, end = 111:120, names = head(letters, 10)),
    strand = Rle(strand(c("-", "+", "*", "+", "-")), c(1, 2, 2, 3, 2)),
    score = 1:10,
    GC = seq(1, 0, length=10))
gr
options(warn=2)
@
%% 
creates a \Rclass{GRanges} object with 10 genomic ranges.
The output of the \Rclass{GRanges} \Rcode{show} method separates the
information into a left and right hand region that are separated by
\Rcode{|} symbols. The genomic coordinates (seqnames, ranges, and strand)
are located on the left-hand side and the metadata columns (annotation)
are located on the right. For this example, the metadata is
comprised of \Rcode{score} and \Rcode{GC} information, but almost
anything can be stored in the metadata portion of a \Rclass{GRanges}
object.

The components of the genomic coordinates within a \Rclass{GRanges}
object can be extracted using the \Rcode{seqnames}, \Rcode{ranges},
and \Rcode{strand} accessor functions.
%% 
<<GRanges-location-accessors>>=
seqnames(gr)
ranges(gr)
strand(gr)
@

The genomic ranges can be extracted without corresponding metadata
with \Rcode{granges}
%% 
<<granges-accessor>>=
granges(gr)
@ 
%% 
Annotations for these coordinates can be extracted as a
\Rclass{DataFrame} object using the \Rcode{mcols} accessor.
%% 
<<metadataAccess>>=
mcols(gr)
mcols(gr)$score
@

Information about the lengths of the various sequences that the ranges
are aligned to can also be stored in the \Rclass{GRanges} object. So
if this is data from \textit{Homo sapiens}, we can set the values as:
%% 
<<setSeqLengths>>=
seqlengths(gr) <- c(249250621, 243199373, 198022430)
@
%% 
And then retrieves as:
<<setSeqLengths2>>=
seqlengths(gr)
@
%% 
Methods for accessing the \Rcode{length} and \Rcode{names} have
also been defined.
%% 
<<names>>=
names(gr)
length(gr)
@


\subsection{Splitting and combining \Rclass{GRanges} objects}

\Rclass{GRanges} objects can be devided into groups using the
\Rcode{split} method. This produces a \Rclass{GRangesList} object,
a class that will be discussed in detail in the next section.
%% 
<<splitAppendGRanges>>=
sp <- split(gr, rep(1:2, each=5))
sp
@
%% 
Separate \Rclass{GRanges} instances can be concatenated by using the
\Rcode{c} and \Rcode{append} methods.
%% 
<<combine>>=
c(sp[[1]], sp[[2]])
@

\subsection{Subsetting  \Rclass{GRanges} objects}

\Rclass{GRanges} objects act like vectors of ranges, with the expected
vector-like subsetting operations available
%% 
<<subset1>>=
gr[2:3]
@
%% 
A second argument to the \Rcode{[} subset operator can be used
to specify which metadata columns to extract from the
\Rclass{GRanges} object. For example,
%% 
<<subset2>>=
gr[2:3, "GC"]
@

Elements can also be assigned to the \Rclass{GRanges} object.  Here is
an example where the second row of a \Rclass{GRanges} object is
replaced with the first row of \Robject{gr}.
%% 
<<assign1>>=
singles <- split(gr, names(gr))
grMod <- gr
grMod[2] <- singles[[1]]
head(grMod, n=3)
@

There are methods to repeat, reverse, or select specific portions of
\Rclass{GRanges} objects.
%% 
<<other>>=
rep(singles[[2]], times = 3)
rev(gr)
head(gr,n=2)
tail(gr,n=2)
window(gr, start=2,end=4)
gr[IRanges(start=c(2,7), end=c(3,9))]
@

\subsection{Basic interval operations for \Rclass{GRanges} objects}

Basic interval characteristics of \Rclass{GRanges} objects can
be extracted using the \Rcode{start}, \Rcode{end}, \Rcode{width},
and \Rcode{range} methods.
%% 
<<IRangesStuff>>=
g <- gr[1:3]
g <- append(g, singles[[10]])
start(g)
end(g)
width(g)
range(g)
@

The \Rclass{GRanges} class also has many methods for manipulating the
ranges. The methods can be classified as \emph{intra-range methods},
\emph{inter-range methods}, and \emph{between-range methods}.

\emph{Intra-range methods} operate on each element of a
\Rclass{GRanges} object independent of the other ranges in the
object. For example, the \Rcode{flank} method can be used to recover
regions flanking the set of ranges represented by the \Rclass{GRanges}
object. So to get a \Rclass{GRanges} object containing the ranges that
include the 10 bases upstream of the ranges:
%% 
<<flank>>=
flank(g, 10)
@
%% 
And to include the downstream bases:
%% 
<<flank2>>=
flank(g, 10, start=FALSE)
@
%% 
Other examples of intra-range methods include \Rcode{resize} and
\Rcode{shift}. The \Rcode{shift} method will move the ranges by a
specific number of base pairs, and the \Rcode{resize} method will
extend the ranges by a specified width.
%% 
<<shiftAndResize>>=
shift(g, 5)
resize(g, 30)
@
%% 
The \Biocpkg{GenomicRanges} help page \Rcode{?"intra-range-methods"}
summarizes these methods.

\emph{Inter-range methods} involve comparisons between ranges in a
single \Rclass{GRanges} object. For instance, the \Rcode{reduce}
method will align the ranges and merge overlapping ranges to produce a
simplified set.
%% 
<<reduce>>=
reduce(g)
@
%% 
Sometimes one is interested in the gaps or the qualities of the gaps
between the ranges represented by your \Rclass{GRanges} object.  The
\Rcode{gaps} method provides this information:
reduced version of your ranges:
%% 
<<gaps>>=
gaps(g)
@
%% 
The \Rcode{disjoin} method represents a \Rclass{GRanges} object as a
collection of non-overlapping ranges:
%% 
<<disjoin>>=
disjoin(g)
@
%% 
The \Rcode{coverage} method quantifies the degree of overlap for all
the ranges in a \Rclass{GRanges} object.
%% 
<<coverage>>=
coverage(g)
@
%% 
See the \Biocpkg{GenomicRanges} help page
\Rcode{?"inter-range-methods"} for additional help.

\emph{Between-range methods} involve operations between two
\Rclass{GRanges} objects; some of these are summarized in the next
section.

\subsection{Interval set operations for \Rclass{GRanges} objects}

\emph{Between-range methods} calculate relationships between different
\Rclass{GRanges} objects. Of central importance are
\Rcode{findOverlaps} and related operations; these are discussed
below.  Additional operations treat \Rclass{GRanges} as mathematical
sets of coordinates; \Rcode{union(g, g2)} is the union of the
coordinates in \Rcode{g} and \Rcode{g2}. Here are examples for
calculating the \Rcode{union}, the \Rcode{intersect} and the
asymmetric difference (using \Rcode{setdiff}).
%% 
<<intervals1>>=
g2 <- head(gr, n=2)
union(g, g2)
intersect(g, g2)
setdiff(g, g2)
@

Related methods are available when the structure of the
\Rclass{GRanges} objects are 'parallel' to one another, i.e., element
1 of object 1 is related to element 1 of object 2, and so on. These
operations all begin with a \Rcode{p}, which is short for
parallel. The methods then perform element-wise, e.g., the union of
element 1 of object 1 with element 1 of object 2, etc. A requirement
for these operations is that the number of elements in each
\Rclass{GRanges} object is the same, and that both of the objects have
the same seqnames and strand assignments throughout.
%% 
<<intervals2>>=
g3 <- g[1:2]
ranges(g3[1]) <- IRanges(start=105, end=112)
punion(g2, g3)
pintersect(g2, g3)
psetdiff(g2, g3)
@

For more information on the \Rcode{GRanges} classes be sure to consult
the manual page.
%% 
<<manPage, eval=FALSE>>=
?GRanges
@
%% 
A relatively comprehensive list of available methods is discovered
with
%% 
<<granges-methods, eval=FALSE>>=
methods(class="GRanges")
@ 


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{\Rclass{GRangesList}: Groups of Genomic Ranges}

Some important genomic features, such as spliced transcripts that are
are comprised of exons, are inherently compound structures. Such a
feature makes much more sense when expressed as a compound object
such as a \Rclass{GRangesList}. Whenever genomic features consist of
multiple ranges that are grouped by a parent feature, they can be
represented as a \Rclass{GRangesList} object. Consider the simple
example of the two transcript \Rfunction{GRangesList} below created
using the \Rfunction{GRangesList} constructor.
%% 
<<example-GRangesList>>=
gr1 <- GRanges(
    seqnames = "chr2", 
    ranges = IRanges(103, 106),
    strand = "+", 
    score = 5L, GC = 0.45)
gr2 <- GRanges(
    seqnames = c("chr1", "chr1"),
    ranges = IRanges(c(107, 113), width = 3),
    strand = c("+", "-"), 
    score = 3:4, GC = c(0.3, 0.5))
grl <- GRangesList("txA" = gr1, "txB" = gr2)
grl
@

The \Rcode{show} method for a \Rclass{GRangesList} object displays
it as a named list of \Rclass{GRanges} objects, where the names of
this list are considered to be the names of the grouping feature. In
the example above, the groups of individual exon ranges are represented
as separate \Rclass{GRanges} objects which are further organized into a
list structure where each element name is a transcript name. Many
other combinations of grouped and labeled \Rclass{GRanges} objects are
possible of course, but this example is expected to be a common
arrangement. 


\subsection{Basic \Rclass{GRangesList} accessors}

Just as with \Rclass{GRanges} object, the components of the genomic
coordinates within a \Rclass{GRangesList} object can be extracted
using simple accessor methods. Not surprisingly, the
\Rclass{GRangesList} objects have many of the same accessors as
\Rclass{GRanges} objects.  The difference is that many of these
methods return a list since the input is now essentially a list of
\Rclass{GRanges} objects. Here are a few examples:
%% 
<<basicGRLAccessors>>=
seqnames(grl)
ranges(grl)
strand(grl)
@
%% 
The \Rcode{length} and \Rcode{names} methods will return the length
or names of the list and the \Rcode{seqlengths} method will return the
set of sequence lengths.
%% 
<<exceptions>>=
length(grl)
names(grl)
seqlengths(grl)
@

The \Rcode{elementNROWS} method returns a list of integers
corresponding to the result of calling \Rcode{NROW} on each
individual \Rclass{GRanges} object contained by the
\Rclass{GRangesList}. This is a faster alternative to calling
\Rcode{lapply} on the \Rclass{GRangesList}.
%% 
<<elementNROWS>>=
elementNROWS(grl)
@
%% 
\Rcode{isEmpty} tests if a \Rclass{GRangesList} object contains
anything.
%% 
<<isEmpty>>=
isEmpty(grl)
@

In the context of a \Rclass{GRangesList} object, the \Rcode{mcols}
method performs a similar operation to what it does on a
\Rclass{GRanges} object. However, this metadata now refers to
information at the list level instead of the level of the individual
\Rclass{GRanges} objects.
%% 
<<mcolsGRL>>=
mcols(grl) <- c("Transcript A","Transcript B")
mcols(grl)
@
%% 
Element-level metadata can be retrieved by unlisting the
\Robject{GRangesList}, and extracting the metadata
%% 
<<mcolsGRL-unlist>>=
mcols(unlist(grl))
@ 

\subsection{Combining \Rclass{GRangesList} objects}

\Rclass{GRangesList} objects can be unlisted to combine the separate
\Rclass{GRanges} objects that they contain as an expanded
\Rclass{GRanges}.

<<unlistGRL>>=
ul <- unlist(grl)
ul
@

Append lists using \Rcode{append} or \Rcode{c}.

A \href{https://support.bioconductor.org/p/89339/}{support site user}
had two \Rclass{GRangesList} objects with 'parallel' elements, and
wanted to combined these element-wise into a single
\Rclass{GRangesList}. One solution is to use \Rcode{pc()} -- parallel
(element-wise) \Rcode{c()}. A more general solution is to concatenate
the lists and then re-group by some factor, in this case the names of
the elements.

<<pc-grl>>=
grl1 <- GRangesList(
    gr1 = GRanges("chr2", IRanges(3, 6)),
    gr2 = GRanges("chr1", IRanges(c(7,13), width = 3)))
grl2 <- GRangesList(
    gr1 = GRanges("chr2", IRanges(9, 12)),
    gr2 = GRanges("chr1", IRanges(c(25,38), width = 3)))

pc(grl1, grl2)

grl3 <- c(grl1, grl2)
regroup(grl3, names(grl3))
@ 

\subsection{Basic interval operations for \Rclass{GRangesList} objects}

For interval operations, many of the same methods exist for
\Rclass{GRangesList} objects that exist for \Rclass{GRanges} objects.
%% 
<<intOpsGRL>>=
start(grl)
end(grl)
width(grl)
@
%% 
These operations return a data structure representing, e.g.,
\Rclass{IntegerList}, a list where all elements are integers; it can
be convenient to use mathematical and other operations on
\Rclass{*List} objects that work on each element, e.g.,
%% 
<<List-ops>>=
sum(width(grl))  # sum of widths of each grl element
@ 
%% 

Most of the intra-, inter- and between-range methods operate on
\Rclass{GRangesList} objects, e.g., to shift all the \Rclass{GRanges}
objects in a \Rclass{GRangesList} object, or calculate the
coverage. Both of these operations are also carried out across each
\Rclass{GRanges} list member.
%% 
<<coverageGRL>>=
shift(grl, 20)
coverage(grl)
@

\subsection{Subsetting \Rclass{GRangesList} objects}

A \Rclass{GRangesList} object is behaves like a \Rcode{list}:
\Rcode{[} returns a \Rclass{GRangesList} containing a subset of the
original object; \Rcode{[[} or \Rcode{\$} returns the
\Rclass{GRanges} object at that location in the list.
%% 
<<subsetGRL, eval=FALSE>>=
grl[1]
grl[[1]]
grl["txA"]
grl$txB
@
%% 
In addition, subsetting a \Rclass{GRangesList} also accepts a second
parameter to specify which of the metadata columns you wish to select.
%% 
<<subsetGRL2>>=
grl[1, "score"]
grl["txB", "GC"]
@ 

The \Rcode{head}, \Rcode{tail}, \Rcode{rep}, \Rcode{rev}, and
\Rcode{window} methods all behave as you would expect them to for a
list object. For example, the elements referred to by \Rcode{window}
are now list elements instead of \Rclass{GRanges} elements.
%% 
<<otherSubsetGRL>>=
rep(grl[[1]], times = 3)
rev(grl)
head(grl, n=1)
tail(grl, n=1)
window(grl, start=1, end=1)
grl[IRanges(start=2, end=2)]
@


\subsection{Looping over \Rclass{GRangesList} objects}

For \Rclass{GRangesList} objects there is also a family of
\Rcode{apply} methods. These include \Rcode{lapply}, \Rcode{sapply},
\Rcode{mapply}, \Rcode{endoapply}, \Rcode{mendoapply}, \Rcode{Map},
and \Rcode{Reduce}.

The different looping methods defined for \Rclass{GRangesList} objects
are useful for returning different kinds of results.  The standard
\Rcode{lapply} and \Rcode{sapply} behave according to convention,
with the \Rcode{lapply} method returning a list and \Rcode{sapply}
returning a more simplified output.
%% 
<<lapply>>=
lapply(grl, length)
sapply(grl, length)
@
%% 
As with \Rclass{IRanges} objects, there is also a multivariate version
of \Rcode{sapply}, called \Rcode{mapply}, defined for
\Rclass{GRangesList} objects. And, if you don't want the results
simplified, you can call the \Rcode{Map} method, which does the same
things as \Rcode{mapply} but without simplifying the output.
%% 
<<mapply>>=
grl2 <- shift(grl, 10)
names(grl2) <- c("shiftTxA", "shiftTxB")

mapply(c, grl, grl2)
Map(c, grl, grl2)
@

Sometimes you will want to get back a modified version of the
\Rclass{GRangesList} that you originally passed in. 

An endomorphism is a transformation of an object to another instance
of the same class .  This is achieved using the \Rcode{endoapply}
method, which will return the results as a \Rclass{GRangesList}
object.
%% 
<<endoapply>>=
endoapply(grl, rev)
mendoapply(c, grl, grl2)
@
%% 
The \Rcode{Reduce} method will allow the \Rclass{GRanges} objects to
be collapsed across the whole of the \Rclass{GRangesList} object.
% Again, this seems like a sub-optimal example to me.
<<ReduceGRL>>=
Reduce(c, grl)
@

Explicit element-wise operations (\Rcode{lapply()} and friends) on
\Rclass{GRangesList} objects with many elements can be slow. It is
therefore beneficial to explore operations that work on \Rcode{*List}
objects directly (e.g., many of the `group generic' operators, see
\Rcode{?S4groupGeneric}, and the set and parallel set operators (e.g.,
\Rcode{union}, \Rcode{punion}). A useful and fast strategy is to
\Rcode{unlist} the \Rclass{GRangesList} to a \Rclass{GRanges} object,
operate on the \Rclass{GRanges} object, then \Rcode{relist} the
result, e.g.,
%% 
<<unlist-relist>>=
gr <- unlist(grl)
gr$log_score <- log(gr$score)
grl <- relist(gr, grl)
grl
@ 
%% 
See also \Rcode{?extractList}.

For more information on the \Rcode{GRangesList} classes be sure to
consult the manual page and available methods
%% 
<<manPage2, eval=FALSE>>=
?GRangesList
methods(class="GRangesList")   # _partial_ list
@


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Interval overlaps involving \Rclass{GRanges} and \Rclass{GRangesList}
objects}

Interval overlapping is the process of comparing the ranges in two
objects to determine if and when they overlap. As such, it is perhaps
the most common operation performed on \Rclass{GRanges} and
\Rclass{GRangesList} objects. To this end, the \Biocpkg{GenomicRanges}
package provides a family of interval overlap functions. The most general
of these functions is \Rfunction{findOverlaps}, which takes a query and a
subject as inputs and returns a \Rclass{Hits} object containing
the index pairings for the overlapping elements.

<<findOverlaps>>=
mtch <- findOverlaps(gr, grl)
as.matrix(mtch)
@

\noindent
As suggested in the sections discussing the nature of the
\Rclass{GRanges} and \Rclass{GRangesList} classes, the index in the
above matrix of hits for a \Rclass{GRanges} object is a single range
while for a \Rclass{GRangesList} object it is the set of ranges that
define a "feature".

Another function in the overlaps family is \Rfunction{countOverlaps},
which tabulates the number of overlaps for each element in the query.

<<countOL>>=
countOverlaps(gr, grl)
@

A third function in this family is \Rfunction{subsetByOverlaps},
which extracts the elements in the query that overlap at least one
element in the subject.

<<subsetByOverlaps>>=
subsetByOverlaps(gr,grl)
@

Finally, you can use the \Rcode{select} argument to get the index
of the first overlapping element in the subject for each element
in the query.

<<select-first>>=
findOverlaps(gr, grl, select="first")
findOverlaps(grl, gr, select="first")
@


%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\section{Session Information}

All of the output in this vignette was produced under the following
conditions:

\begin{small}
<<SessionInfo>>=
sessionInfo()
@
\end{small}

\end{document}
