% \VignetteIndexEntry{Using the homology package}
% \VignetteDepends{hsahomology, xlahomology}
% \VignetteKeywords{Annotation}
%\VignettePackage{annotate}

\documentclass{article}

\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Rmethod}[1]{{\texttt{#1}}}

\newcommand{\Robject}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\textit{#1}}}
\newcommand{\Rclass}[1]{{\textit{#1}}}

\usepackage{hyperref}

\usepackage[authoryear,round]{natbib}
\usepackage{times}

\begin{document}
\title{How to use the homology packages}

\author{Jianhua Zhang \and Ben Wittner}
\date{}
\maketitle

\section*{Introduction}

The homology packages are a group of data packages built based on a source
data file provided by HomoloGene
(\url{http://www.ncbi.nlm.nih.gov/HomoloGene/}). There is a separate
package for each individual organism. This vignette illustrates how to
use the homology packages to explore the homologous relationships
among organisms. Two or more organisms have homologous relationships
if their genes share an arbitrary threshold level of similarity
determined by alignment of matching bases.

This vignette demonstrates the usage of the homology packages by
performing two tasks to introduce users to the packages, although the
potential use of the packages is well beyond the scope of the tasks.

\section*{Contents of the packages}

The homology packages are built on organism bases with a separate data
package for each of the species contained in the source file. The
packages are named following a convention of \Rpackage{XXXhomology}
where XXX are a three letter string consisting of the first letter of
the genus name and the first two letters of the species name of a
given organism. For example, hsahomology is the package for human
(Homo sapiens).

As other Bioconductor data packages, the homology packages contains
environment objects in the \texttt{data} subdirectory that will be
loaded when the package is loaded. A full list of the environment
objects is shown below (using the package for human as an example):

<<>>=
library("annotate")
library("hsahomology")
hsahomology()
@

\Robject{XXXhomologyDATA} has HomoloGeneIDs as keys and lists of
sub-lists containing data for other organisms that have been
identified to have homology relationships as the corresponding
values. The list for a given HomoloGene ID may have one or more
sub-lists depending on whether homology relationships have been
identified in only one or more other organisms.

Each sub-list has an element for the name of the organism (homoOrg),
HomologGeneID (homoHGID), type of similarity (homoType. B - reciprocal
best match between three or more organisms, b - reciprocal best match
between two organisms, and c - curated homology relationship between
two organisms), percent of identity (homoPS) measured as the
percentage of base pair alignment between the matching sequences, and
a url (homoURL) to the source if the relationship is a curated
orthology. A sub-list with homoType = B or b will not have any value
for homoURL and a sublist with homoType = c will not have any value
for homoPS.



The \Robject{XXXhomologyLL2HGID} environment contains mappings between
LocusLink identifiers and HGIDs (HomoloGene IDs used by HomoloGene to
represent sequences represented by the LocusLink ids). This
environment allows users to map LocusLink ids to HGIDs and then use
the obtained HGIDs to locate homologous genes in other organisms using
the environment that contains data for homologous genes found in other
organisms using \Robject(XXXhomologyDATA).


\subsection{Use \Rpackage{XXXhomology} to explore homologous
  relationships among organisms}

\subsubsection{Task 1}

Given LocusLink id 25 in human (Homo sapiens), how would one find all
other species containing homologous genes of best matches with percent
similarity values above 80.00?


First we call a function \Rfunction{LL2homology} in
\Rpackage{annotate} to obtain data for all the homologous genes of
LocusLink id 25 in human.

<<>>=
homoGenes <- LL2homology("hsahomology", "25")
@

\Robject{homoGenes} is a list of sub-lists with elements shown below:

<<>>=
names(homoGenes[[1]][[1]])
@

We are only interested in genes that are best best matches (homoType =
B) to LocusLink id 25 with percent identity values greater than
80.00. The following code finds and prints the names of the organisms
and LocusLink IDs and HGIDs for genes that satisfy these conditions:

<<>>=
## A given LocusLink id may be mapped to more than one HGID. Use the
## data for the first one here
goodG <- sapply(homoGenes[[1]], function(x){
    (x[["homoType"]] == "B" && x[["homoPS"]] > 80.00)})

geneList <- homoGenes[[1]][goodG]
sapply(geneList, function(x) x[["homoOrg"]])
sapply(geneList, function(x) x[["homoHGID"]])
@

\subsubsection{Task 2}

Find all the genes in \texttt{Xenopus laevis} that are homologous to
genes of \texttt{Danio rerio} with percent identity values greater
than 90.00.

The organism code for \texttt{Danio rerio} is:

<<>>= 
library("xlahomology")
subset(xlahomologyORGCODE, species_name == "Danio rerio")
@ 

The object containing homology data for \texttt{Xenopus laevis}
is \Robject{xlahomologyHGID} in \Rpackage{xlahomology}, which is a
vector of HGIDs. Genes in \texttt{Xenopus laevis} that satisfy the
conditions can be obtained using the following code chunk.

<<>>=
temp <- mget(xlahomologyHGID, xlahomologyDATA)
tempFun <- function(x){
   for(i in x){
       if(!is.na(i[["homoOrg"]]) && i[["homoOrg"]] == "dre"
          && i[["homoPS"]] > 90.00){
           return(i)
       }
   }
   return(NA)
}
goodGenes <- sapply(temp, tempFun)
goodGenes <- goodGenes[!is.na(goodGenes)]
@

\Robject{goodGenes} obtained above is a list of sub-lists. The names
of the list are the HGIDs for genes in \texttt{Xenopus laevis} and the
corresponding \Robject(homoData) objects contain information about the
homologous genes in \texttt{"Danio rerio"}. The following code gets
the HGIDs and percent similarity of these homologous genes:


<<>>=
## Get the HGIDs
hgids <- unlist(sapply(goodGenes, function(x) x[["homoHGID"]]))
## Get the percent similarities
ps <- unlist(sapply(goodGenes, function(x) x[["homoPS"]]))
@

%\subsubsection{Task 3}

%For all Affymetrix Danio rerio probe-set IDs, find the
%Affymetrix Xenopus laevis probe-set ID of the homologous
%gene.

%Below is example code to accomplish this task. The code looks up
%homologies and Affymetrix probe-set IDs using GenBank accession
%numbers. More homologies can be found by also using Locus Link IDs,
%but we did not put code for that in the example in order to limit the
%complexity of the example code. The code below takes tens of minutes
%to run.

%The overall goal of all the code in this subsection is to set
%\texttt{homoloProbeSets} to be a matrix with Affymetrix Denio rerio
%probe-set IDs in the first column and the Affymetrix Xenopus laevis
%probe-set ID of the corresponding homologous gene in the second
%column.

%<<>>=
%#
%#  Set homoloProbeSets to be a matrix with Affy zebrafish probe-set IDs
%#  in the first column and the Affy xenopuslaevis probe-set ID of the
%#  corresponding homologous gene in the second column.
%#

%require("Biobase")
%require("zebrafish")                      # Danio rerio
%require("xenopuslaevis")                  # Xenopus laevis
%require("drehomology")
%@

%The function \Rfunction{swapKeyVal} returns an environment with keywords
%and values of the input environment swapped.

%<<>>=
%swapKeyVal <- function(inputEnvironment) {
%  tmp <- as.list(inputEnvironment)
%  vals <- as.list(names(tmp))
%  names(vals) <- tmp
%  l2e(vals)
% }
%@

%The line below set \texttt{psids.Xl} to be an environment that maps
%Xenopus laevis GenBank IDs to Affymetrix xenopus probe-set IDs

%<<>>=
%psids.Xl <- swapKeyVal(xenopuslaevisACCNUM)
%@

%The line below sets \texttt{psids.Dr} to be a list of the Affymetrix
%zebrafish probe-set IDs

%<<>>=
%#psids.Dr <- names(as.list(zebrafishACCNUM))
%psids.Dr <- ls(zebrafishACCNUM)
%@

%The next two lines set \Robject{homoloProbeSets} to be an empty matrix
%with one column for each species.

%<<>>=
%homoloProbeSets <- matrix(character(0), nrow=0, ncol=2)
%colnames(homoloProbeSets) <- c('zebrafish', 'xenopuslaevis')
%@

%For each Danio rerio probe-set ID, we look for the homologous Xenopus
%laevis probe-set ID. (The use of \Rfunction{sub()} below is to chop off
%extensions to GenBank IDs that indicate version number because those
%extensions are not in \Robject{xenopuslaevisACCNUM}.)

%<<>>=
%for (psid.Dr in psids.Dr) {
%print(psid.Dr)

%  listOfLists <- ACC2homology(zebrafishACCNUM[[psid.Dr]], "drehomology")
%  targetHomoGene <- NULL

%  for (homoGeneList in listOfLists) {
%    for (homoGene in homoGeneList) {
%      if (homoGene[["homoOrg"]] == 'xla') {
%        targetHomoGene <- homoGene
%        break
%      }
%    }
%  }

%  if (!is.null(targetHomoGene)) {
%    # The GenBank IDs in xenopuslaevisACCNUM do not have extensions that
%    # indicate version number, so we chop off the extensions.
%    acc <- sub('\\.[0-9]+$', '', targetHomoGene[["homoHGID"]])
%    acc <- drehomologyHGID2ACC[[acc]]
%    psid.Xl <- psids.Xl[[acc]]
%    if (!is.null(psid.Xl)) {
%      homoloProbeSets <- rbind(homoloProbeSets, c(psid.Dr, psid.Xl))
%    }
%  }
% }
%@

%Now let's see how many homologies we found and look at the first ten.

%<<>>=
%print(dim(homoloProbeSets))
%print(homoloProbeSets[1:10,])
%@

\section{Session Information}

The version number of R and packages loaded for generating the vignette were:

<<echo=FALSE, results=tex>>=
toLatex(sessionInfo())
@

\end{document}


