%\VignetteDepends{ncdf}
%\VignetteIndexEntry{Foreign Language Interfaces}
%\VignettePackage{AdvancedR2011}

\documentclass{beamer}

\usepackage{BioconductorSlides}
\SweaveOpts{keep.source=TRUE, eval=FALSE}

\title{Foreign Language Interfaces}
\author{Valerie Obenchain}
\institute[FHCRC]{Fred Hutchinson Cancer Research Center}
\date{17-18 February, 2011}

\begin{document}

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

\frame{\titlepage}

\begin{frame}{Overview}
  \begin{itemize}
  \item Motivation 
  \item Interface functions 
  \item Compile and load dynamic libraries 
  \item Using .C() 
  \item Register native routines 
  \end{itemize}
\end{frame}

\begin{frame}{Motivation}
  \begin{itemize}
  \item Areas where the R implementation is suboptimal : 
     \begin{itemize}
       \item sliding window algorithms
       \item calculations that are difficult to vectorize
     \end{itemize}
  \item Implement third party algorithms or
   libraries (e.g., GSL, BOOST, BGL, SAMtools, affxparser)
  \end{itemize}
\end{frame}

\begin{frame}{Interface Functions}
 The following functions provide a standard 
 interface to compiled code that has been linked into \R{}:
  \begin{itemize}
  \item .C 
  \item .Call
  \item .Fortran
  \end{itemize}
\end{frame}

\begin{frame}{Advantages of .Call() vs .C()}
  \begin{itemize}
  \item Less copying 
  \item Memory allocation in C 
  \item Pass and recieve R objects instead of primitive types 
  \item Access to the attributes of the vectors (i.e., names)
  \item Ability to handle missing values easily
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{C code}
  \begin{itemize}
  \item Compiled code should not return anything except through
   the arguments
  \item C functions should be of type \Rcode{void}
  \item Include Rdefines.h and R\_ext/Rdynload.h 
  \end{itemize}
\begin{verbatim}
/* composite_linkage_disequlibrium.c */
void
composite_linkage_disequilibrium(
    unsigned char *snp, /* matrix indiv x snp */
    int *n_ind,         /* # individuals */
    int *n_snp,         /* # snps */
    int *width,         /* adjacent snp window */
    double *delta)      /* result */
{
   ... 
} 
\end{verbatim}
\end{frame}

\begin{frame}[fragile]{Compile and load dynamic libraries : \R{} Session}
  \begin{itemize}
    \item The shared library 
     can be created with R CMD SHLIB composite\_linkage\_disequlibrium.c.
    \item From within an \R{} session the compiled library can be loaded with
     \Rcode{dyn.load}. The functions in the compiled code are now 
     available for use in the \R{} session. 
<<dynload, eval=FALSE, keep.source=TRUE>>=
   dyn.load("composite_linkage_disequlibrium.so") 
@
  \end{itemize}
\end{frame}

\begin{frame}{Compile and loading dynamic libraries : \R{} Package}
  \begin{itemize}
    \item Load with \Rfunction{useDynLib(mypkg)} in the NAMESPACE
    \item Other instructions can be put in \Rfunction{.onLoad}
     and \Rfunction{.onUnload} functions in a zzz.R file. 
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{Using .C()}
  \begin{itemize}
  \item The first argument to .C is a character string
   of the C function name. The remainder of the arguments 
   are \R{} objects to
   be passed to the C function.
  \item All arguments should be coerced to the correct \R{}
   storage mode
  \end{itemize}
\begin{verbatim}
snps <- matrix(sample((0:2), replace=TRUE), 
               nrow=10, ncol=4)
nsnp <- ncol(snps)
nsub <- nrow(snps)
width <- 3 
delta <- rep.int(0, (nsnp-width)*width)
out <- .C("composite_linkage_disequilibrium", 
          snp = as.integer(snp), n_ind = as.integer(nind),
          n_snp = as.integer(nsnp),width = as.integer(width),
          delta = as.double(delta))
\end{verbatim}
\end{frame}

\begin{frame}{Register Native Routines}
 Motivation :
  \begin{itemize}
    \item Platform-independent mechanism for finding routines in 
     shared objects 
    \item Information about a native routine made available within \R{} 
  \end{itemize}
 Steps :
  \begin{itemize}
    \item Create an initialization file called R\_init\_mypkg.c
    \item Create an array describing the function with R\_CmethodDef
    \item Register the function with R\_registerRoutines 
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{Register Native Routines }
  \begin{itemize}
  \item Create an array describing the C 
   routine using R\_CMethodDef using the following
   \R{} types and corresponding type identifiers : 
    \begin{verbatim}
  `numeric'   `REALSXP'
  `integer'   `INTSXP'
  `logical'   `LGLSXP'
  `character' `STRSXP'
  `list'      `VECSXP'
    \end{verbatim}
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{Register Native Routines }
  \begin{itemize}
   \item Given the C function declared as
\begin{verbatim}
void composite_linkage_disequilibrium(
         unsigned char *snp, 
         int *n_ind,
         int *n_snp, 
         int *width, 
         double *delta) 
\end{verbatim}
   \item We would create the R\_CMethodDef array 
\begin{verbatim}
R_CMethodDef cMethods[] = {
    {"composite_linkage_disequilibrium",
     (DL_FUNC) &composite_linkage_disequilibrium, 5,
     { INTSXP, INTSXP, INTSXP, INTSXP, REALSXP }
    },
    {NULL, NULL, 0}
};
\end{verbatim}
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Initialization Function}
  \begin{itemize}
    \item The initialization file contains the
R\_CMethodDef array and the call to R\_registerRoutines
in the R\_init\_STudentGWAS function. 
\begin{verbatim}
void R_init_StudentGWAS(DllInfo *info)
{
    /* Create the R_CMethodDef array */
    R_CMethodDef cMethods[] = {
        {"composite_linkage_disequilibrium",
         (DL_FUNC) &composite_linkage_disequilibrium, 5,
         { INTSXP, INTSXP, INTSXP, INTSXP, REALSXP }
        },
        {NULL, NULL, 0}
    };

    /* Register the routine */
    R_registerRoutines(info, cMethods, NULL, NULL, NULL);
}
\end{verbatim}
  \end{itemize}
\end{frame}


\begin{frame}{Resources}
\begin{itemize}
     \item Writing \R{} Extensions Manual
           http://www.r-project.org/
\end{itemize}
\end{frame}

\end{document}
