%\VignetteDepends{GenomicFeatures,Rsamtools,org.Sc.sgd.db,leeBamViews}
%\VignetteIndexEntry{Using the GenomicFeatures package}
%\VignettePackage{HTSandGeneCentricLabs}

\documentclass{beamer}

\usepackage{BioconductorSlides}
\SweaveOpts{keep.source=TRUE}

\title{Using the \Biocpkg{GenomicFeatures} package}
\author{Marc Carlson }
\institute[FHCRC]{Fred Hutchinson Cancer Research Center}
\date{July 30th 2010}

\begin{document}

<<setup, echo=FALSE>>=
options(width = 64)
@

\frame{\titlepage}

\section{Introduction}

\begin{frame}[t]
  \frametitle{\Bioconductor{} Annotation Packages}
\begin{figure}[ht]
 \centering
  \includegraphics[width=4in,height=3in]{databaseTypes}
\end{figure}
\end{frame}

\begin{frame}[t]
  \frametitle{\Bioconductor{} Sequence Packages}
\begin{figure}[ht]
 \centering
  \includegraphics[width=4in,height=3in]{packageStack}
\end{figure}
\end{frame}

\begin{frame}[t]
  \frametitle{\Bioconductor{} Sequence Annotations}
  \begin{block}{\Biocpkg{The GenomicFeatures package}}
    \begin{itemize}
      \item Transcript information stored in SQLite databases
      \item These databases attempt to represent the relational 
        nature of splicing data correctly
      \item Transcript information exposed to user via the
        \Biocpkg{GenomicRanges} infrastructure
      \item Parsers are available to construct these databases from biomaRt 
        or the UCSC genome browser.  Also there is a generic parser for 
        custom jobs.
    \end{itemize}
  \end{block}
\end{frame}


\section{GenomicFeatures}

\begin{frame}[t,fragile]
  \frametitle{\Biocpkg{GenomicFeatures} transcript sources}
  \begin{block}{Constructors}
    \Rfunction{makeTranscriptDbFromBiomart},
    \Rfunction{makeTranscriptDbFromUCSC}
  \end{block}

{\footnotesize
<<loadGenomicFeatures>>=
library(GenomicFeatures)
nrow(supportedUCSCtables())
head(supportedUCSCtables(), 10)
@
}
\end{frame}


\begin{frame}[t,fragile]
  \frametitle{\Rclass{TranscriptDb} basics}
  \begin{block}{Making a \Rclass{TranscriptDb} object}
{\small
<<makeUCSC, eval=FALSE>>=
mm9KG <-
  makeTranscriptDbFromUCSC(genome = "mm9",
                           tablename = "knownGene")
@
}
  \end{block}
  \begin{block}{Saving and Loading}
{\small
<<saveFeatures, eval=FALSE>>=
saveFeatures(mm9KG, file="mm9KG.sqlite")
@
<<loadFeatures>>=
mm9KGChr9 <-
  loadFeatures(system.file("extdata", "mm9KG.sqlite",
                           package = "HTSandGeneCentricLabs"))
@
}
  \end{block}
\end{frame}

\begin{frame}[t,fragile]
  \frametitle{\Rclass{TranscriptDb} class}
{\small
<<TranscriptDb>>=
mm9KGChr9
@
}
\end{frame}

\begin{frame}{\Rclass{TranscriptDb} schema}
  \begin{figure}
    \includegraphics[width=4.25in]{transcriptschema.png}
  \end{figure}
\end{frame}

\begin{frame}[t,fragile]
  \frametitle{Ungrouped transcript-related information}
  \begin{block}{Extractors}
    \Rfunction{transcripts}, \Rfunction{exons}, \Rfunction{cds}
  \end{block}

{\footnotesize
<<transcripts>>=
tx <- transcripts(mm9KGChr9)
length(tx)
head(tx, 5)
@
}
\end{frame}



\begin{frame}[t,fragile]
  \frametitle{Grouped transcript-related information}
  \begin{block}{Extractors}
    \Rfunction{transcriptsBy}, \Rfunction{exonsBy},
    \Rfunction{cdsBy}, \Rfunction{intronsByTranscript},
    \Rfunction{fiveUTRsByTranscript},
    \Rfunction{threeUTRsByTranscript}
  \end{block}

{\footnotesize
<<exonsBy>>=
txExons <- exonsBy(mm9KGChr9)
txIntrons <- intronsByTranscript(mm9KGChr9)
txExons[6]
@
}
\end{frame}


\begin{frame}[t,fragile]
  \frametitle{Standard GRanges accessors can be used}
  \begin{block}{Accessors}
    \Rmethod{names}, \Rmethod{length},
    \Rmethod{elementMetaData}, \Rmethod{width},
    \Rmethod{ranges},\Rmethod{start},\Rmethod{end}
  \end{block}
  \begin{block}{Examples:}
{\footnotesize
<<accessors>>=
head(start(tx))
head(ranges(txExons), n=1)
head(elementMetadata(tx), n=2)
@
}
  \end{block}
\end{frame}


%%elementMetadata

%%Should I split this slide up?  Or leave it as a pre-summary?

\begin{frame}[t,fragile]
  \frametitle{Overlapping with transcripts}
  \begin{block}{Methods}
    \Rfunction{findOverlaps}, \Rfunction{countOverlaps},
    \Rfunction{match}, \Rfunction{\%in\%},
    \Rfunction{subsetByOverlaps}
  \end{block}
\vskip12pt
  \begin{block}{Usage and help:}
{\footnotesize
<<findOverlaps-help, eval=FALSE>>=
findOverlaps(query, subject, maxgap = 0L, minoverlap = 1L,
             type = c("any", "start", "end"),
             select = c("all", "first"))
help("findOverlaps,GRanges,GRangesList-method")
@
}
  \end{block}
  \begin{block}{Example}
{\footnotesize
<<countOverlaps>>=
grngs <- GRanges("chr9", gaps(ranges(txExons[[6]])), "+")
countOverlaps(grngs, tx)
rbind(countOverlaps(grngs, txExons), countOverlaps(grngs, txIntrons))
@
}
  \end{block}
\end{frame}


%EXERCISE 1
\begin{frame}[fragile]
  \frametitle{GenomicFeatures exercise 1}
  Load the transciptDB object above and then gather the annotations
for transcripts as grouped by their genes.
\end{frame}

\begin{frame}[fragile]
\end{frame}
  
\begin{frame}[fragile]
  \frametitle{GenomicFeatures exercise 1 solution}
{\small
<<exer1, results=hide>>=
library(GenomicFeatures)
mm9KGChr9 <-
  loadFeatures(system.file("extdata", "mm9KG.sqlite",
                           package = "HTSandGeneCentricLabs"))

myTranscripts <- transcriptsBy(mm9KGChr9, by="gene")
@
}
\end{frame}



%% Section on finding overlaps with transcripts (from GenomicRanges)
\section{A simple RNA-seq example}

\begin{frame}[fragile]
  \frametitle{A simple RNA-seq example}
  \begin{block}{1st lets just load some data}
    \Rfunction{readBamGappedAlignments}
  \end{block}
{\small
<<yeastData>>=
library(Rsamtools)
testFile <- system.file("bam", "isowt5_13e.bam", 
                        package="leeBamViews")
aligns <- readBamGappedAlignments(testFile)
head(aligns)
@
}
\end{frame}



\begin{frame}[fragile]
  \frametitle{RNA-seq}
  \begin{block}{Retrieve corresponding Annotations}
    \Rfunction{makeTranscriptDbFromUCSC}
  \end{block}
{\footnotesize
<<GetAnnoations>>=
library(GenomicFeatures)
txdb <- makeTranscriptDbFromUCSC(genome="sacCer2", 
                                 tablename="sgdGene")
@
}
  \begin{block}{extract exons by transcripts}
    \Rfunction{exonsBy}
  \end{block}
{\footnotesize
<<exonsBy2>>=
exonRanges <- exonsBy(txdb, "tx")
length(exonRanges)
exonRanges[1]
@
}
\end{frame}



\begin{frame}[fragile]
  \frametitle{RNA-seq}
  \begin{block}{Correct for chromosome naming}
    \Rfunction{levels}
  \end{block}
{\small
<<ammendData>>=
levels(rname(aligns))
levels(rname(aligns)) <-
  c(paste("chr", as.roman(1:16), sep=""), "chrM")
@
}
\end{frame}




%EXERCISE 2
\begin{frame}[fragile]
  \frametitle{GenomicFeatures exercise 2}
  Now that we have the data and annotations stored in the appropriate
  objects, use the appropriate method to count the overlaps between
  them.
\end{frame}

\begin{frame}[fragile]
\end{frame}
  
\begin{frame}[fragile]
  \frametitle{RNA-seq: GenomicFeatures exercise 2 solution}
  \begin{block}{Use countOverlaps to count Reads}
    \Rfunction{countOverlaps}
  \end{block}
{\small
<<exer2, results=hide>>=
txdb <- makeTranscriptDbFromUCSC(genome="sacCer2", 
                                 tablename="sgdGene")
exonRanges <- exonsBy(txdb, "tx")

library("Rsamtools")
testFile <- system.file("bam", "isowt5_13e.bam", 
                        package="leeBamViews")
aligns <- readBamGappedAlignments(testFile)
levels(rname(aligns))
levels(rname(aligns)) <-
  c(paste("chr", as.roman(1:16), sep=""), "chrM")

counts <- countOverlaps(exonRanges, aligns)
@
}
\end{frame}



\begin{frame}[fragile]
  \frametitle{RNA-seq}
  \begin{block}{Can then calculate RPKM}
  \end{block}
{\small
<<numBases>>=
numBases <- sum(width(exonRanges))
geneLengthsInKB <- numBases / 1000
millionsMapped <- sum(counts) / 1000000
rpm <- counts / millionsMapped
rpkm <- rpm / geneLengthsInKB
@
}
\end{frame}



\begin{frame}[fragile]
  \frametitle{RNA-seq}
  \begin{block}{Results can be sorted}
  \end{block}
{\small
<<sort>>=
sortedRPKM <- sort(rpkm)
highScoreGenes <- tail(sortedRPKM)
@
}
\end{frame}


%EXERCISE 3
\begin{frame}[fragile]
  \frametitle{GenomicFeatures exercise 3}
  Now that we have some of the things that were measured the most, we
  want to know what they are.  We don't want to use the transcript ID's
  though because they are not guaranteed to be meaningful outside of
  this database.  What we want instead are the gene IDs.  
  
  So how can we use GenomicFeatures to extract the gene IDs matched to
  the transcript IDs?
\end{frame}

\begin{frame}[fragile]
\end{frame}

\begin{frame}[fragile]
  \frametitle{RNA-seq:  GenomicFeatures exercise 3 solution}
<<exer3, results=hide>>=
##All the RPKM stuff since count and then:
txs <- transcripts(txdb,
         vals=list(tx_id=names(highScoreGenes)),
         columns=c("tx_id","gene_id"))
systNames <- as.vector(
               unlist(elementMetadata(txs)["gene_id"]))
@
\end{frame}



\begin{frame}[fragile]
  \frametitle{RNA-seq}
  \begin{block}{use other annot's to learn more}
  \end{block}
<<annnotate2>>=
library(org.Sc.sgd.db)
toTable(org.Sc.sgdGENENAME[systNames])
@
  \begin{block}{(combine into sets as needed)}
  \end{block}
{\small
<<DESeqFrame, eval=false>>=
deSeqframe <- data.frame(counts, counts2)
@
}
\end{frame}



%% I might consider a chip-seq example too (from GenomicRanges) - but
%% NO: this is a bad idea since it is being covered in a lab later on
%% by Michael Lawrence.  Therefore, lets not waste time on it here.


\end{document}

