Rcpp inline package error in compileCode - r

I have R installed along with these two packages Rcpp and inline. (I am doing a project that consists of speeding up a painfully slow program in R and I decided to use Rcpp)...I know I am doing something wrong...probably missing a step but i cannot figure it out. Props to Dirk if you're reading this! Thanks for Rcpp and the brand new inline package pdf but...it's still not running.
Please note that I'm a newbie. As stated before I cleaned out all other packages and only R is installed with Rcpp and inline (of course I have c++ installed as well).
library(Rcpp)
library(inline)
x<-as.numeric(1:10)
n<-as.integer(10)
code<-"
integer i
do 1 i=1, n(1)
1 x(i)=x(i)**3
"
cubefn<- cfunction(signature(n="integer",x="numeric"),code,convention=".Fortran")
ERROR(s) during compilation: source code errors or compiler configuration errors!
Program source:
1: #include <R.h>
2:
3:
4: extern "C" {
5: void filef2424e34d61 ( int * n, double * x );
6: }
7:
8: void filef2424e34d61 ( int * n, double * x ) {
9:
10: integer i
11: do 1 i=1, n(1)
12: 1 x(i)=x(i)**3
13:
14: }
Error in compileCode(f, code, language, verbose) :
Compilation ERROR, function(s)/method(s) not created!
In addition: Warning message:
running command 'C:/R/R-2.15.2/bin/x64/R CMD SHLIB filef2424e34d61.cpp 2> filef2424e34d61.cpp.err.txt' had status 1
If it is the construction of a package skeleton missing: i tried the simple rcpp_hello_world() example:
rcpp_hello_world <- function(){
.Call( "rcpp_hello_world", PACKAGE = "mypackage" )
}
Folder PATH listing for volume OS
Volume serial number is 769C-A616
C:.
The rest was a long list of odd symbols but what I could read was the name of c++ projects I have, I didn't include them as it would be too lengthy
rcpp_hello_world <-function(){
.Call("rcpp_hello_world",PACKAGE="mypackage")
}
rcpp_hello_world()
Error in .Call("rcpp_hello_world", PACKAGE = "mypackage") :
"rcpp_hello_world" not available for .Call() for package "mypackage"
Anything would help please, also I have linux installed as well so if that is a better option please do tell. I am open to anything right now, the slightest progress makes is a delight

Do you actually have a Fortran compiler installed?
If you don't, or you don't know, try your Linux box. R on Windows must be able to compile source packages if you want to build with Rcpp and inline. A good quick test is to try something like
R> myroot <- cppFunction('double myroot(double x) { return ::sqrt(x); }')
R> myroot(16)
[1] 4
R>
or equivalently via inline (where rcpp is a wrapper for the cxxfunction(..., plugin="Rcpp") call, you need the most recent inline package for that)
R> myroot2 <- rcpp(signature(xs="numeric"),
+ body='double x=as<double>(xs); return wrap(::sqrt(x));')
R> myroot2(16)
[1] 4
R>
If this does not work, read up on the R basics of installing Rtools for Windows etc. We have a few additional notes in the Rcpp FAQ as well.

Related

Error in R package that need C program to complie

I would like to work with R package SampleSizeBinomial_1.0.tar.gz.This package includes a C program which will need be compiled. I am working in Windown 7 (64 bit) and I got the following error:
> prop.acc(len=200, alpha=20.5, beta=18.5, level=0.95, exact=TRUE,
sim.size=1000, precision=1e-6, mcs=3)
Error in .C("OutcomeEstimation", as.integer(n), as.double
(fixed.parm.target), : C symbol name "OutcomeEstimation" not in load table
How could i solve this problem? What should i do in this regards? All the information about this package and install instruction is here.

Source build of Rquantlib fails

I'm building Rquantlib from source and I recently have been encountering this issue:
Error in .Call("RQuantLib_setEvaluationDate", PACKAGE = "RQuantLib", evalDate) :
"RQuantLib_setEvaluationDate" not available for .Call() for package "RQuantLib"
Error : unable to load R code in package ‘RQuantLib’
R version 3.2.3 (2015-12-10)
Rcpp version 0.12.4
I have checked and setEvaluationDate() is there with appropriate rcpp tags, so not sure what's changed. I have not edited the file. It seems to be an inline version, wheras the github version is an actual call:
My rcpp generated inlcude verion for the function:
inline bool setEvaluationDate(QuantLib::Date evalDate) {
typedef SEXP(*Ptr_setEvaluationDate)(SEXP);
static Ptr_setEvaluationDate p_setEvaluationDate = NULL;
}
From github:
bool setEvaluationDate(QuantLib::Date evalDate);
static SEXP RQuantLib_setEvaluationDate_try(SEXP evalDateSEXP) {
BEGIN_RCPP
Rcpp::RObject __result;
Rcpp::traits::input_parameter< QuantLib::Date >::type evalDate(evalDateSEXP);
__result = Rcpp::wrap(setEvaluationDate(evalDate));
return __result;
END_RCPP_RETURN_ERROR
}
You need to recompile all dependents of Rcpp after major upgrades.
Eg when we went from Ubuntu 15.04 to 15.10 which changed the compiler to g++-5 with its new ABI, ran this this script to rebuild everything from the local repo:
#!/usr/bin/env r
## installed packages
IP <- installed.packages()
## all local packages
AP <- available.packages(contrib.url(getOption("repos")[["local"]]))
## all packages known to us
allAP <- available.packages()
pkgs <- "Rcpp"
deps <- tools::package_dependencies(packages=pkgs, db=IP, reverse=TRUE)
## set of dependencies
alldeps <- unique(sort(do.call(c, deps)))
cat("Installing these:\n")
print(alldeps)
## this makes sense on Debian where no packages touch /usr/local
libloc <- Sys.getenv("LIBLOC", unset="/usr/local/lib/R/site-library")
install.packages(alldeps, lib=libloc)
It is similar when something in Rcpp changes, though we've been pretty good about not changing interfaces. But when in doubt, rebuild. Also re-run compileAttributes() if in doubt but little changed there.
Edit: I just (re-)installed without a glitch on two systems too.
Edit 2: It also works directly at the R prompt:
## what follows was one line in R and just broken up for display
R> cppFunction("bool mySetEvalDate(QuantLib::Date d) "
"{ QuantLib::Settings::instance().evaluationDate() = d;"
" return true; }", depends="RQuantLib")
R> mySetEvalDate( Sys.Date() )
[1] TRUE
R>
Now, if your intent was to call setEvaluationDate() from C++ then you need to look at the discussion about exporting to R and C++ in the Rcpp Attributes vignettes. The code in src/daycounter.cpp is meant for R.

Fatal Error while using Rcpp in RStudio on Windows

I'm trying to use Rcpp on Windows in RStudio. I have R version 3.2.3 and I have installed the Rcpp package. The problem is that I am unable to call any functions defined through the CPP code. I tried the following (picked up from an example online).
body <- '
NumericVector xx(x);
return wrap( std::accumulate( xx.begin(), xx.end(), 0.0));'
add <- cxxfunction(signature(x = "numeric"), body, plugin = "Rcpp")
This gives the following warning, but completes execution successfully.
cygwin warning:
MS-DOS style path detected: C:/R/R-32~1.3/etc/x64/Makeconf
Preferred POSIX equivalent is: /cygdrive/c/R/R-32~1.3/etc/x64/Makeconf
CYGWIN environment variable option "nodosfilewarning" turns off this warning.
Consult the user's guide for more details about POSIX paths:
http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
When I try to use the above function,
x <- 1
y <- 2
res <- add(c(x, y))
I get the following error :
R Session Aborted
R encountered a fatal error.
The session was terminated.
Any suggestions? This same 'Fatal Error' happens for any code that I run with Rcpp.
Try rebuilding locally, starting with Rcpp. This is valid code and will work (and the hundreds of unit tests stress may more than this). Sometimes the compiler or something else changes under you and this sort of thing happens. It is then useful to have an alternative build system -- eg via Travis at GitHub you get Linux for free.
Also, learning about Rcpp Attributes. Your example can be written as
R> library(Rcpp)
R> cppFunction("double adder(std::vector<double> x) { return std::accumulate(x.begin(), x.end(), 0.0); }")
R> adder(c(1,2))
[1] 3
R>
which is simpler. Works of course the same way with Rcpp::NumericVector.

How to make devtools::test() consider package dependencies

Actual question
Seems like devtools::test() does not make sure that package dependencies as stated in a package's DESCRIPTION file are loaded prior to running the unit tests. How can I change that?
Details
I'm writing a package (B) that imports another one of my packages (A).
When I try to run my unit tests via devtools::test(), or, to be more precise via the shortcut SHFT + CRTL + T in RStudio, certain tests fail as the imported package seems to be disregarded/not loaded and thus a certain function (isPackageInstalled) can't be found.
Trying to load the imported package A manually before running devtools::test() didn't help either. I guess that's due to the fact that devtools (or testthat) "simulates" a fresh workspace state? Running the unit tests "one by one" works just fine after manually loading package A beforehand, though.
I thought that devtools would look up package dependencies in the DESCRIPTION file of B and thus load them as would be the case when running require("B"), but apparently not.
Here's my DESCRIPTION file:
Package: B
Type: Package
Title: What the package does (short line)
Version: 0.1.0.1
Date: 2014-08-05
Author: Who wrote it
Maintainer: Who to complain to <yourfault#somewhere.net>
Description: More about what it does (maybe more than one line)
License: What license is it under?
Imports: A
Here's the code I ran:
devtools::load_all() # or SHFT + CTRL + L in RStudio
devtools::test() # or SHFT + CTRL + T in RStudio
That's what RStudio's build pane gave me:
==> devtools::test()
Loading required package: testthat
Testing B
Loading B
Creating a new generic function for 'signalCondition' in package 'B'
package : 1
package : ......
1. Error: getPackageDescription ------------------------------------------------
could not find function "isPackageInstalled"
1: expect_is(res <- getPackageDescription(), expected) at test-getPackageDescription.r:13
2: expect_that(object, is_a(class), info, label)
3: condition(object)
4: paste0(class(x), collapse = ", ")
5: getPackageDescription()
6: getPackageDescription() at Q:\home\wsp\rapp2\B/R/getPackageDescription.r:37
7: getPackageDescription(from = from, fields = fields, drop = drop, encoding = encoding,
...) at Q:\home\wsp\rapp2\B/R/getPackageDescription.r:154
8: getPackageDescription(from = from, fields = fields, drop = drop, encoding = encoding,
...) at Q:\home\wsp\rapp2\B/R/getPackageDescription.r:37
Am I missing something here?
Screenshot of build tools dialogue:
The usual approach would be to use roxygen2 to automatically generate your NAMESPACE file from special comments in your source code, but maintain your DESCRIPTION file manually. There's no special stuff that I'm aware of to keep them in sync, but R CMD CHECK will tell you if there's something missing/extra in your DESCRIPTION.

Lemon Graph Library on R using Rcpp

I think that this answer is a bit complex because it involves several things.
I want to do high performance computations with R particularly with graphs (networks). As a R package igraph is very nice. But R is slow, so I want to code the computationally expensive routines in C++ (maybe in C). I take a look at the igraph C library and I found it a little messy to work with. I also look at the Boost Graph Library and I read about it that it is difficult to learn. So I eventually found Lemon Graph Library. It is in C++ and seems very nice to work with.
So I installed the Lemon Graph Library as recommended in the official page. Then using the Rcpp and inline packages I manage myself to run Lemon Graph C++ code from R. Here I write in detail what I had made. But basically I put this:
inc <- '
#include <lemon/list_graph.h>
using namespace lemon ;
'
src <- '
int xx = Rcpp::as<int>(x);
int res = xx + 1;
ListDigraph g;
ListDigraph::Node u = g.addNode();
ListDigraph::Node v = g.addNode();
ListDigraph::Arc a = g.addArc(u, v);
int i = countNodes(g);
int j = countArcs(g);
Rprintf("num nodes is %d , and num edges is %d \\n",i,j);
return Rcpp::wrap(res);
'
fun <- cxxfunction( signature(x="numeric"), body=src,include=inc, plugin="Rcpp")
in a myexample_inline.R file and then run a R console and write:
> library("inline")
> library("Rcpp")
> source("myexample_inline.R")
> fun(1)
num nodes is 2 , and num edges is 1
[1] 2
So it works !!! But now I have the following problem. If I make a C++ function (say double func1(g)) that for example calculates some property to some Lemon graph object. How I call that function from the inlined code? I must made func1() as a template function and put it in the include field of cxxfunction()?
Basically: I can't figure out how to call a C++ function inlined in R from another C++ function also inlined in R. Is it possible? Is there another way that do not uses inline code?
Maybe I can do it using Rcpp modules but I couldn't (still) figure out how to do this.
I'm having problems with making modules work. I will keep trying with this, but maybe I can get some kind of hint from here.
I also thought about the possibility to develop (my first) a package. But I had the problem that the Lemon Graph C++ code call the headers in this way (for example):
#include <iostream>
#include <lemon/list_graph.h>
So it means (at least I believe this) that I can not avoid the installation of the Lemon Graph Library. If I want to make a R package of the Lemon Graph Library I have to "rewrite" all the code again !!! So this is not my main option.
Best Regards
I have managed to success to this problem. Here you can find a detailed explanation about what I have done. Maybe, it is trivial to most of the people here, but it may be a good starting point for someone that is in the same position that I was. I will post a resume here of what I done.
First I installed the Lemon Graph (C++) Library (LGL). I just downloaded the LGL from its home page (from here). Then I proceed:
$ tar xvzf lemon-1.2.tar.gz
$ cd lemon-1.2
$ ./configure
$ make
$ make check # This is optional, but recommended. It runs a bunch of tests.
$ sudo make install
Then check if it works. So in a file named mycode.cc I put:
#include <iostream>
#include <lemon/list_graph.h>
using namespace lemon;
using namespace std;
int main()
{
ListDigraph g;
ListDigraph::Node u = g.addNode();
ListDigraph::Node v = g.addNode();
ListDigraph::Arc a = g.addArc(u, v);
cout << "Hello World! This is LEMON library here." << endl;
cout << "We have a directed graph with " << countNodes(g) << " nodes "
<< "and " << countArcs(g) << " arc." << endl;
return 0;
}
Then I compile and run it:
$ g++ -O2 mycode.cc -lemon
... BLA BLA BLA ...
$./a.out
Hello World! This is LEMON library here.
We have a directed graph with 2 nodes and 1 arc.
So it works. Now, the idea is to integrate that code into R via Rcpp. So in some directory I open a R console and I do:
> require("Rcpp")
Loading required package: Rcpp
> Rcpp.package.skeleton("pkgwithlgl")
Creating directories ...
Creating DESCRIPTION ...
Creating NAMESPACE ...
Creating Read-and-delete-me ...
Saving functions and data ...
Making help files ...
Done.
Further steps are described in './pkgwithlgl/Read-and-delete-me'.
Adding Rcpp settings
>> added Depends: Rcpp
>> added LinkingTo: Rcpp
>> added useDynLib directive to NAMESPACE
>> added Makevars file with Rcpp settings
>> added Makevars.win file with Rcpp settings
>> added example header file using Rcpp classes
>> added example src file using Rcpp classes
>> added example R file calling the C++ example
>> added Rd file for rcpp_hello_world
So, in this way I just created a new Rcpp based source package named pkgwithlgl. Now inside the pkgwithlgl directory (which is the source of the package that I want to modify and install) there is a directory named src. Inside it there are the files with the C++ code of the package. In particular there is one named *rcpp_hello_world.cpp* which contains:
#include "rcpp_hello_world.h"
SEXP rcpp_hello_world(){
using namespace Rcpp ;
CharacterVector x = CharacterVector::create( "foo", "bar" ) ;
NumericVector y = NumericVector::create( 0.0, 1.0 ) ;
List z = List::create( x, y ) ;
return z ;
}
Now, I modify it so it becomes:
#include "rcpp_hello_world.h"
#include <lemon/list_graph.h>
using namespace lemon ;
SEXP rcpp_hello_world(){
using namespace Rcpp ;
int res = 1;
ListDigraph g;
ListDigraph::Node u = g.addNode();
ListDigraph::Node v = g.addNode();
ListDigraph::Arc a = g.addArc(u, v);
int i = countNodes(g);
int j = countArcs(g);
Rprintf("num nodes is %d , and num edges is %d \n",i,j);
return wrap(res) ;
}
Then, from the linux console in the container directory of the source package I write:
$ R CMD INSTALL pkgwithlgl
which returns:
* installing to library ‘/home/juan/R/x86_64-pc-linux-gnu-library/2.12’
* installing *source* package ‘pkgwithlgl’ ...
** libs
g++ -I/usr/share/R/include -I"/usr/local/lib/R/site-library/Rcpp/include" -fpic -O3 -pipe -g -c rcpp_hello_world.cpp -o rcpp_hello_world.o
g++ -shared -o pkgwithlgl.so rcpp_hello_world.o -L/usr/local/lib/R/site-library/Rcpp/lib -lRcpp -Wl,-rpath,/usr/local/lib/R/site-library/Rcpp/lib -L/usr/lib64/R/lib -lR
installing to /home/juan/R/x86_64-pc-linux-gnu-library/2.12/pkgwithlgl/libs
** R
** preparing package for lazy loading
** help
Warning: /home/juan/Desktop/facu/investigacion_ensayos/Cosas_crudas/programming_coding/R-work- space/integrating_R_with_cpp_via_Rcpp/using_packages/pkgwithlgl/man/pkgwithlgl- package.Rd:32: All text must be in a section
Warning: /home/juan/Desktop/facu/investigacion_ensayos/Cosas_crudas/programming_coding/R-work- space/integrating_R_with_cpp_via_Rcpp/using_packages/pkgwithlgl/man/pkgwithlgl- package.Rd:33: All text must be in a section
*** installing help indices
converting help for package ‘pkgwithlgl’
finding HTML links ... done
pkgwithlgl-package html
rcpp_hello_world html
** building package indices ...
** testing if installed package can be loaded
* DONE (pkgwithlgl)
So the package is installed (the warnings has to do with the fact that I don't filled in the right way the .Rd file, ie, the files that contains the helps about the package). The I open a R console and write:
> require("pkgwithlgl")
Loading required package: pkgwithlgl
Loading required package: Rcpp
> rcpp_hello_world()
num nodes is 2 , and num edges is 1
[1] 1
so it works !!! That is all.
But hey !!! What happens if I build this package and upload it into (forexample) CRAN (I will not do it). If some one install this package from CRAN, will it work for him? Even if it does not install the LGL package?
Best Regards
Howdy, and thanks for your interest in Rcpp.
To bind calls between different library functions, you may want to look into building a package. There are now twenty packages using Rcpp as listed on the Rcpp page on CRAN so you have examples to copy from. At a first appromixation,. this is no different from writing a normal program and Rcpp simply helps you getting it to R.
If you have more questions, please feel free to bring them to the rcpp-devel list.

Resources