\documentclass{elsarticle}

%% Redefines the elsarticle footer
\makeatletter
\def\ps@pprintTitle{%
 \let\@oddhead\@empty
 \let\@evenhead\@empty
 \def\@oddfoot{\it \hfill\today}%
 \let\@evenfoot\@oddfoot}
\makeatother


\bibliographystyle{elsarticle-harv}
\usepackage{graphicx}
\usepackage{subfigure}
\usepackage[pdftex, colorlinks]{hyperref}
\usepackage{amsmath, amsfonts}  % extended mathematics
\usepackage{booktabs} % book-quality tables
\textwidth 6.75in
\oddsidemargin -0.15in
\evensidemargin -0.15in
\textheight 9in
\topmargin -0.5in
\newcommand{\ud}{\mathrm{d}}


%% Looks like a comment but it isn't! 
% \SweaveOpts{fig=TRUE, fig.align='center', fig.width=3, fig.height=3, cache=FALSE, warning=FALSE, message=FALSE, comment=NA}

                  

\begin{document}
\begin{frontmatter}
  \title{An introduction to the \texttt{rfishbase} Package}
  \author[davis]{Carl Boettiger\corref{cor1}}
  \author[davis]{Peter Wainwright}
  \ead{cboettig@ucdavis.edu}
  %\author[davis]{}
  \cortext[cor1]{Corresponding author.}
  \address[davis]{Center for Population Biology, University of California, Davis, United States}

  \begin{abstract}
 We introduce a package that provides interactive and programmatic access to the FishBase repository~\citep{fishbase}.  This package allows us to interact with data on over 30,000 fish species in the rich statistical computing environment, \texttt{R}.  We illustrate how this direct, scriptable interface to FishBase data enables better discovery and integration essential for large-scale comparative analyses.  We provide several examples to illustrate how the package works, and how it can be integrated into such as phylogenetics packages~\texttt{ape} and \texttt{geiger}.  
  \end{abstract}

  \begin{keyword}
   R  \sep vignette \sep fishbase
   \end{keyword}
 \end{frontmatter}

\section{Introduction}

\emph{Describe the fishbase database ... extent, information avialable, etc  }
\emph{Briefly describe R}


<<load, echo=FALSE>>=
require(rfishbase)
data(fishbase)
@



Informatics

FishBase (\href{http://fishbase.org}{fishbase.org}) is an award-winning online database of information about the morphology, trophic ecology, physiology, ecotoxicology, reproduction, economic relevance of the world's fish, organized by species~\citep{fishbase2012}.  FishBase was developed in collaboration with the United Nations Food and Agriculture Organization and is supported by a consortium of nine research institutions.  In addition to its web-based interface, FishBase provides machine readable XML files for \Sexpr{length(fish.data)} of its species entries.  

To facilitate the  extraction, visualization, and integration of this data in research, we have written the \texttt{rfishbase} package for the R language for statistical computing and graphics~\citep{RTeam2012}.  R is a freely available open source computing environment that is used extensively in ecological research, with a large library of packages built explicitly for this purpose \citep{Kneib2007}.  




\setkeys{Gin}{width=.5\linewidth}

<<load, results='hide'>>=
require(rfishbase)
require(ggplot2) 
@


\section{A programmatic interface}
The \texttt{rfishbase} package works by creating a cached copy of all data on fishbase currently available in XML format.  Caching increases the speed of queries and places minimal demands on the fishbase server, which in it's present form is not built to support direct access to application programming interfaces (APIs).   The cached copy can be loaded in to R using the command:  

<<loaddata>>=
data(fishbase)
@

To get the most recent copy of fishbase, update the cache instead. The update may take up to 24 hours. This copy is stored in the working directory with the current date and can be loaded when finished.   
<<update, eval=FALSE>>=
updateCache() 
loadCache("2011-10-12fishdata.Rdat")
@
Loading the database creates an object called fish.data, with one entry per fish species for which data was successfully found, for a total of 
<<nfish>>=
length(fish.data)
@
\section{Data extraction, analysis, and visualization}
Comparative studies 

The examples we give here are meant to be illustrative of the kinds of queries that are possible, and also provide a simple introduction to assist the reader in using the software itself.  


Quantitatve queries
<<AgeHist>>=
yr <- getSize(fish.data, "age")
@


<<nocturnal>>=
nocturnal <- which_fish("nocturnal", "trophic", fish.data)
@
The object returned is a list of true/false values, indicating all fish in the dataset that match this query.  
This format is useful because it allows us to subset the original data and pass it to another query. 
For instance, we can use the \verb|fish_names| function to return the names of these fish.  
\verb|fish_names| can return more than just species names -- here we ask it to give us the top taxonomic Orders 
of these nocturnal fish, organized into a table:

<<nocturnaltable, results="tex">>=
nocturnal_orders <- fish_names(fish.data[nocturnal], "Order")
dat <- sort(table(nocturnal_orders),decreasing=TRUE)
xtable::xtable(head(dat))
@


The real power of programatic access the ease with which we can combine, visualize, and statistically test a custom compilation of this data.  
We begin by generating a custom data table of characteristics of interest
<<>>=
reef <- which_fish("reef", "habitat", fish.data)
nocturnal <- which_fish("nocturnal", "trophic", fish.data)
marine <- which_fish("marine", "habitat", fish.data)
africa <- which_fish("Africa:", "distribution", fish.data)
age <- getSize(fish.data, "age")
length <- getSize(fish.data, "length")
order <- fish_names(fish.data, "Order")
dat <- data.frame(reef, nocturnal, carnivore, marine, freshwater, age, length, order)
@

This data frame contains categorical data (\emph{e.g.} is the fish a carnivore) and continuous data (\emph{e.g.} weight or age of fish). 
We can take advantage of the rich data visualization in R to begin exploring this data. 

\setkeys{Gin}{width=.5\linewidth}
\begin{figure}
<<>>=
ggplot(dat,aes(age, length, color=marine)) + geom_point(position='jitter',alpha=.8) + scale_y_log10() + scale_x_log10() 
# In which orders are carnivores bigger than non-carnivores?
# More nocturnal species are found on reefs: 
qplot(reef[nocturnal])
# Are reef species longer lived than non-reef species in the marine environment?
ggplot(subset(dat, marine),aes(reef, log(age))) + geom_boxplot() 

# Are reef species longer lived than non-reef species in the marine environment?
ggplot(aes(reef, table(order))) + geom_bar() 

biggest <- names(head(sort(table(orders),decr=T), 10))
ggplot(subset(dat,order %in% biggest), aes(marine, fill=order)) + geom_bar() 


@
\end{figure}



Typical use of the package involves constructing queries to identify species matching certain criteria. The powerful R interface makes it easy to combine queries in complex ways to answer particular questions.  For instance, we can ask ``are there more labrids or goby species of reef fish?'' using the following queries:

Get all species in fishbase from the families ``Labridae'' (wrasses) or ``Scaridae'' (parrotfishes):



<<reefcount>>=
labrid <- familySearch("(Labridae|Scaridae)", fish.data)
@
and get all the species of gobies
<<gobycount>>=
goby <- familySearch("Gobiidae", fish.data)
@
Identify how many labrids are found on reefs
<<labridreef>>=
labrid.reef <- habitatSearch("reef", fish.data[labrid])
nlabrids <- sum(labrid.reef)
@
and how many gobies are found on reefs:
<<gobyreef>>=
ngobies <- sum (habitatSearch("reef", fish.data[goby]) )
@
showing us that there are~\Sexpr{nlabrids} labrid species associated with reefs, and ~\Sexpr{ngobies} goby species associated with reefs.  


\setkeys{Gin}{width=.5\linewidth}
\begin{figure}
<<size>>=
hist(log( getSize(fish.data[habitatSearch("freshwater", fish.data)], "length")),
         col=rgb(1,0,0,.5), breaks=40, freq=F, xlab="length", main="marine fish are bigger")
hist(log( getSize(fish.data[habitatSearch("marine", fish.data)], "length")),
          col=rgb(0,0,1,.5), breaks=40, add=T, freq=F)
@
\end{figure}


Note that any function can take a subset of the data, as specified by the square brackets.  
\section{Integration of analyses}
One of the greatest advantages about accessing FishBase directly through R is the ability to take advantage of the suite of specialized analyses available through R packages.  Likewise, users familiar with these packages can more easily take advantage of the data available on fishbase.  We illustrate this with an example that combines phylogenetic methods available in R with quantitative trait data available from \texttt{rfishbase}.  

This series of commands illustrates testing for a phylogenetically corrected correlation between the maximum observed size of a species and the maximum observed depth at which it is found.   


load a phylogenetic tree and some phylogenetics packages
<<results="hide", message=FALSE>>=
data(labridtree)
require(geiger) 
@

 Find those species on FishBase 
<<>>=
myfish <- findSpecies(tree$tip.label, fish.data)
@

Get the maxium depth of each species and sizes of each species: 
<<>>=
depths <- getDepth(fish.data[myfish])[,"deep"]
size <- getSize(fish.data[myfish], "length")
@

Drop tips from the phylogeny for unmatched species.  
<<>>=
data <- na.omit(data.frame(size,depths))
attach(treedata(tree, data))
@

Use phylogenetically independent contrasts~\cite{Felsenstein1985} to determine if depth correlates with size after correcting for phylogeny:
<<pic, results='tex'>>=
x <- pic(data[["size"]],phy)
y <- pic(data[["depths"]],phy)
xtable::xtable(summary(lm(y ~ x - 1)))
@


\begin{figure}
<<>>=
ggplot(data.frame(x=x,y=y), aes(x,y)) + geom_point() + stat_smooth(method=lm)
@
\end{figure}


We can also estimate different evolutionary models for these traits to decide which best describes the data,
<<models, results='hide'>>=
bm <- fitContinuous(phy, data[["depths"]], model="BM")[[1]]
ou <- fitContinuous(phy, data[["depths"]], model="OU")[[1]]
@
where the Brownian motion model has an AIC score of~\Sexpr{bm$aic} while the OU model has a score of~\Sexpr{ou$aic}, suggesting that~\Sexpr{names(which.min(list(BM=bm$aic, OU=ou$aic)))} is the better model.  



In a similar fashion, programmers of other R software packages can make use of the rfishbase package to make this data available to their functions, further increasing the use and impact of fishbase.  For instance, the project OpenFisheries.org makes use of the fishbase package to provide information about commercially relevant species.  

\section{Discussion}

\subsection{The self-updating study}

Describe how this package could help make studies that could be automatically updated as the dataset is improved and expanded (like the examples in this document which are automatically run when the pdf is created).  \citep{Merali2010}, \citep{Peng2011b}.  


\subsection{Limitations and future directions}
Fishbase contains much additional data that has not been made accessible in it's machine-readable XML format.  We are in contact with the database managers and look forward to providing access to additional types of data as they become available.  


 \section{Acknowledgements}
 CB is supported by a Computational Sciences Graduate Fellowship from the Department of Energy under grant number DE-FG02-97ER25308. 
 \section*{ }%bibliography
% \bibliography{/home/cboettig/Documents/Mendeley/bib/library}
 \bibliography{rfishbase}


\end{document}




