%\VignetteDepends{}
%\VignetteIndexEntry{ForeignLanguage-lab}
%\VignettePackage{AdvancedR2011}

\documentclass{article}

\usepackage{BioconductorVignette}
\SweaveOpts{keep.source=TRUE,width=9,height=8,eps=FALSE,include=FALSE}

\title{Foreign Language Interfaces \\ Self-Study Exercises}
\author{Valerie Obenchain \\ Fred Hutchinson Cancer Research Center}
\date{17-18 February, 2011}


\begin{document}
\maketitle
<<setup, echo=FALSE>>=
options(width = 40)
@ 


\section{Introduction} 

These exercises will take you though the steps necessary to
include compiled C code in your course package. For additional
information on the material covered here see the
Writing \R{} Extensions Manual,
Section 5: System and Foreign Language Interfaces, 
http://cran.r-project.org/doc/manuals/R-exts.html.

In this lab we will be using a C function that computes linkage 
disequilibrium (LD). Linkage disequilibrium refers to association 
between SNPs. Alleles at different loci sometimes appear 
together more or less often than expected based on their frequencies. 
Two markers are said to be in LD if there is an statistical association
between the alleles.

To compute LD we need the haplotype phase. Because our data are simulated 
we do not have this information. Therefore our LD function computes a 
`composite` LD which is a statistical measure of association across 
loci when haplotype phase is not known. See Weir and Cockerham, 1989; 
Weir 1996 pp. 94, 125.

We will start by compiling the C code and loading it 
into an \R{} session for testing. Next the package NAMESPACE file
will be modified so the dynamic library will be automatically
loaded when the package is loaded. The final step will be
to register the C method with \R{}.

\begin{Ext} 
In this excercise the C code is compiled into a shared object
and loaded into an \R{} session for testing.
\end{Ext}

\begin{Question}
\begin{itemize}
  \item Move the C function composite\_linkage\_disequilibrium.c 
   and the header composite\_linkage\_disequilibrium.h
   from \Rcode{StudentGWAS/src/} into the src directory of your 
   package. Compile the C function using R CMD SHLIB.
 \end{itemize}
\end{Question}

\begin{Solution}
\begin{verbatim}
R CMD SHLIB composite_linkage_disequilibrium.c 
\end{verbatim}
\end{Solution}

\begin{Question}
\begin{itemize}
\item Before loading the shared object in the package, you may want to perform
some basic testing. Any shared object can be loaded into R by using the 
\Rcode{dyn.load} command. All functions in the shared object are now made
available to \R. Start an \R session and load the shared library with 
\Rcode{dyn.load}.
\item Call the composite linkage disequilibrium function from \R{}
using the .C function.
\end{itemize}
\end{Question}

\begin{Solution}
\begin{verbatim} 
If on Unix load the shared object,

dyn.load("composite_linkage_disequilibrium.so")

If on Windows load the dynamic-link library,

dyn.load("composite_linkage_disequilibrium.dll")


## Create sample data for testing
snps <- matrix(sample((1:3), replace=TRUE, 400), nrow=100, ncol=4)
nsnp <- ncol(snps)
nsub <- nrow(snps)
width <- 2 
delta <- rep.int(0, (nsnp-width)*width)

out <- .C("composite_linkage_disequilibrium", 
          snp = as.raw(snps),
          n_ind = as.integer(nsub),
          n_snp = as.integer(nsnp),
          width = as.integer(width),
          delta = as.double(delta))
out$delta
\end{verbatim} 
\end{Solution}

\begin{Question}
Create a more convenient interface to the linkage disequilibrium
function by writing an \R{} wrapper function. By default the .C function
returns a list. Make the wrapper function return a matrix with
dimensions of snp by width. Include the snp names as rownames.
Name the the wrapper \Rcode{.cld.R} and put it in the /R directory of 
your package.
\end{Question}

\begin{Solution}
<<wrapper, eval = FALSE, keep.source = TRUE>>=
.cld <- function(data, width = 5)
{
    nsub <- nrow(data)
    nsnp <- ncol(data)
    if (width > nsnp)
        stop("Width must be less than the number of snps.")
    delta <- rep.int(0, (nsnp-width)*width)
    res <- .C("composite_linkage_disequilibrium",
              snp = as.raw(data),
              n_sub = as.integer(nsub),
              n_snp = as.integer(nsnp),
              width = as.integer(width),
              delta = as.double(delta), PACKAGE="StudentGWAS")
    matrix(res$delta, nrow=(nsnp-width), ncol=width, byrow=TRUE,
           dimnames = list(colnames(data)[1:(nsnp-width)], NULL))
}
@
\end{Solution}


\begin{Ext} 
In this exercise the package NAMESPACE is modified 
to automatically load the shared library when the
package is loaded. All C code in the /src package
directory is compiled into a single shared object
with the same name as the package. 
\end{Ext}

\begin{Question}
\begin{itemize}
\item Using \Rcode{useDynLoad}, modify the NAMESPACE to load 
the dynamic library for the package
\end{itemize}
\end{Question}

\begin{Solution}
\begin{verbatim}
useDynLib(StudentGWAS)
\end{verbatim}
\end{Solution}


\begin{Ext} 
The purpose of this exercise is to register the C function with R.
\end{Ext}

When a shared object (or dynamic library) is loaded, \R{} looks for a 
routine within that shared object named R\_init\_mypkg. If such a 
routine is present, \R{} will invoke it. This is a convenient
way of executing some code automatically when a shared object is loaded or 
unloaded. We use this function to register native routines with \R{}.
When .C, .Call or .Fortran is used, \R{} must locate the specified native 
routine by looking in the shared object. Registering a native routine with 
\R{} allows the use of a platform-independent mechanism for finding the 
routines in the shared object instead of an operating system-specific 
method to lookup the routine. 

To register routines with \R{} we use the C routine R\_registerRoutines. 
It takes 5 arguments, the first is the shared object information followed 
by arrays describing the routines for each of the 4 different interfaces: 
.C, .Call, .Fortran and .External. These arrays are created with the 
appropriate entry from the following table :

  \begin{verbatim}
     .C            R_CMethodDef
     .Call         R_CallMethodDef
     .Fortran      R_FortranMethodDef
     .External     R_ExternalMethodDef
  \end{verbatim}


\begin{Question}
  \begin{itemize}
    \item Create a file called R\_init\_StudentGWAS.c and put it in the src
    directory
    \item Define the linkage disequilibrium function using R\_CMethodDef
    \item Call R\_registerRoutines using the array defined with R\_CMethodDef
    \item Wrap the R\_CMethodDef array declaration and the R\_registerRoutines
     function in a function called R\_init\_StudentGWAS
  \end{itemize}
\end{Question}

\begin{Solution}
\begin{verbatim}

 /* R_init_StudentGWAS.c file */

#include <R_ext/Rdynload.h>
#include "composite_linkage_disequilibrium.h"

void R_init_StudentGWAS(DllInfo *info)
{
    /* Create the R_CMethodDef array */
    R_NativePrimitiveArgType cld_t[5] =
        { RAWSXP, INTSXP, INTSXP, INTSXP, REALSXP };

    R_CMethodDef cMethods[] = {
        {"composite_linkage_disequilibrium",
         (DL_FUNC) &composite_linkage_disequilibrium,
         5, cld_t},
        {NULL, NULL, 0}
    };

    /* Register the routine */
    R_registerRoutines(info, cMethods, NULL, NULL, NULL);
}

\end{verbatim}
\end{Solution}

\begin{Ext} 
As an advanced exercise, create a C version of the heterozygosity function
introduced in the EfficientR-lab section. Create an \R{} wrapper for this 
C function and register the method.
\end{Ext}

\end{document}
