%\VignetteDepends{ncdf}
%\VignetteIndexEntry{ForeignLanguage}
%\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 receive 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}
  \end{itemize}
\begin{verbatim}
/* composite_linkage_disequilibrium.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 A shared object can be created with 
\begin{verbatim}
R CMD SHLIB composite_linkage_disequlibrium.c.
\end{verbatim}
    \item From within an \R{} session the shared object 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_disequilibrium.so") 
@
  \end{itemize}
\end{frame}

\begin{frame}{Compile and load 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 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 Arguments should be coerced to the \R{}
   storage mode that corresponds to the data type 
   defined in the C code
  \end{itemize}
\begin{verbatim}
## Create sample data
snps <- matrix(sample((1:3), replace=TRUE, 400), 
               nrow=10, ncol=4)
width <- 3
delta <- rep.int(0, (ncol(snps)-width)*width)
out <- .C("composite_linkage_disequilibrium", 
          snp = as.raw(snps), 
          n_ind = as.integer(nrow(snps)),
          n_snp = as.integer(ncol(snps)),
          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 with R\_CMethodDef:
\begin{verbatim}
typedef struct {
    const char *name; DL_FUNC fun; int numArgs;
    R_NativePrimitiveArgType *types;
    R_NativeArgStyle         *styles;
} R_CMethodDef;
\end{verbatim}
  \item \R{} types and corresponding type identifiers : 
    \begin{verbatim}
  `numeric'   `REALSXP'
  `integer'   `INTSXP'
  `logical'   `LGLSXP'
  `character' `STRSXP'
  `raw'       `RAWSXP'
    \end{verbatim}
  \end{itemize}
\end{frame}

\begin{frame}[fragile]{Register Native Routines }
  \begin{itemize}
   \item Given the original C function 
\begin{verbatim}
void composite_linkage_disequilibrium(
         unsigned char *snp, 
         int *n_ind,
         int *n_snp, 
         int *width, 
         double *delta) 
\end{verbatim}
   \item We create the R\_CMethodDef array in R\_init\_mypkg.c 
\begin{verbatim}
R_CMethodDef cMethods[] = {
    {"composite_linkage_disequilibrium",
     (DL_FUNC) &composite_linkage_disequilibrium, 5,
     {RAWSXP, 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 R\_registerRoutines
function wrapped in the R\_init\_mypkg function. 
\begin{verbatim}
void R_init_mypkg(DllInfo *info)
{
    /* Create the R_CMethodDef array */
    R_CMethodDef cMethods[] = {
        {"composite_linkage_disequilibrium",
         (DL_FUNC) &composite_linkage_disequilibrium, 
         5,{RAWSXP, 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 \\
      Section 5: System and Foreign Language Interfaces\\
      http://www.r-project.org/
\end{itemize}
\end{frame}

\begin{frame}[fragile]{Wrap Up}
  \begin{itemize}
    \item C code belongs in src directory of package 
      \begin{itemize}
        \item function type void 
        \item return results through arguments 
      \end{itemize}
    \item By including \Rcode{useDynLib(mypkg)} in the NAMESPACE
          the R CMD INSTALL process compiles and links the C code
          into shared object 
    \item Call C routine using .C interface using correct data types 
    \item Register C method with R in the R\_init\_mypkg.c file
      \begin{itemize}
         \item R\_CMethodDef defines the C function
         \item R\_registerMethods registers routine we defined with R\_CMethodDef  
         \item R\_CMethodDef and R\_registerMethods belong in 
          R\_init\_mypkg function 
      \end{itemize}
\end{itemize}
\end{frame}


\end{document}
