RcppArmadillo: Error when calling cppFunction [duplicate] - r

I am working through the book "Seamless R and C++ Integration with Rcpp". I am using R version 3.1.0 on Ubuntu 12.04. I cannot figure out how to properly link the necessary libraries. I have the following code in R:
R> library(Rcpp)
R> library(RcppArmadillo)
R> suppressMessages(require(inline))
R> code <- '
+ arma::mat coeff = Rcpp::as<arma::mat>(a);
+ arma::mat errors = Rcpp::as<arma::mat>(u);
+ int m = errors.n_rows;
+ int n = errors.n_cols;
+ arma::mat simdata(m,n);
+ simdata.row(0) = arma::zeros<arma::mat>(1, n);
+ for (int row=1; row < m; row++) {
+ simdata.row(row) = simdata.row(row-1)*trans(coeff)
+ + errors.row(row);
+ }
+ return Rcpp::wrap(simdata);
+ '
R> rcppSim <- cxxfunction(signature(a="numeric", u="numeric"),
+ code, plugin="RcppArmadillo")
/usr/bin/ld: cannot find -lgfortran
collect2: error: ld returned 1 exit status
make: *** [file167d1a7cd1ad.so] Error 1
ERROR(s) during compilation: source code errors or compiler configuration errors!
Program source:
1:
2: // includes from the plugin
3: #include <RcppArmadillo.h>
4: #include <Rcpp.h>
5:
6:
7: #ifndef BEGIN_RCPP
8: #define BEGIN_RCPP
9: #endif
10:
11: #ifndef END_RCPP
12: #define END_RCPP
13: #endif
14:
15: using namespace Rcpp;
16:
17:
18: // user includes
19:
20:
21: // declarations
22: extern "C" {
23: SEXP file167d1a7cd1ad( SEXP a, SEXP u) ;
24: }
25:
26: // definition
27:
28: SEXP file167d1a7cd1ad( SEXP a, SEXP u ){
29: BEGIN_RCPP
30:
31: arma::mat coeff = Rcpp::as<arma::mat>(a);
32: arma::mat errors = Rcpp::as<arma::mat>(u);
33: int m = errors.n_rows;
34: int n = errors.n_cols;
35: arma::mat simdata(m,n);
36: simdata.row(0) = arma::zeros<arma::mat>(1, n);
37: for (int row=1; row < m; row++) {
38: simdata.row(row) = simdata.row(row-1)*trans(coeff)
39: + errors.row(row);
40: }
41: return Rcpp::wrap(simdata);
42:
43: END_RCPP
44: }
45:
46:
Error in compileCode(f, code, language = language, verbose = verbose) :
Compilation ERROR, function(s)/method(s) not created!
/usr/bin/ld: cannot find -lgfortran
collect2: error: ld returned 1 exit status
make: *** [file167d1a7cd1ad.so] Error 1
Calls: cxxfunction -> compileCode
In addition: Warning message:
running command '/usr/lib/R/bin/R CMD SHLIB file167d1a7cd1ad.cpp 2>
file167d1a7cd1ad.cpp.err.txt' had status 1
Based on this response to a similar question,
http://lists.r-forge.r-project.org/pipermail/rcpp-devel/2014-February/007245.html
it would appear that I simply need to install
the FORTRAN compiler. However, I have installed gfortran using the Ubuntu package manager and still receive the same error. From terminal:
$ dpkg -s gfortran
Package: gfortran
Status: install ok installed
Priority: optional
Section: devel
Installed-Size: 33
Maintainer: Ubuntu Developers <ubuntu-devel-discuss#lists.ubuntu.com>
Architecture: i386
Source: gcc-defaults (1.112ubuntu5)
Version: 4:4.6.3-1ubuntu5
Provides: fortran-compiler
Depends: cpp (>= 4:4.6.3-1ubuntu5), gcc (>= 4:4.6.3-1ubuntu5), gfortran-4.6
(>= 4.6.3-1~)
Suggests: gfortran-multilib, gfortran-doc
Description: GNU Fortran 95 compiler
This is the GNU Fortran 95 compiler, which compiles Fortran 95 on platforms
supported by the gcc compiler. It uses the gcc backend to generate optimized
code.
This is a dependency package providing the default GNU Fortran 95 compiler.
Original-Maintainer: Debian GCC Maintainers <debian-gcc#lists.debian.org>
I have also been unsuccessful trying to use the CxxFlags() and LdFlags() functions. Any suggestions are greatly appreciated.
Running sourceCpp() produces the following:
R> rcppSim <- sourceCpp("~/Dropbox/Rcpp/rcppSim.cpp")
rcppSim.cpp: In function ‘SEXPREC* file167d1a7cd1ad(SEXP, SEXP)’:
rcppSim.cpp:31:1: error: ‘arma’ has not been declared
rcppSim.cpp:31:11: error: expected ‘;’ before ‘coeff’
rcppSim.cpp:32:1: error: ‘arma’ has not been declared
rcppSim.cpp:32:11: error: expected ‘;’ before ‘errors’
rcppSim.cpp:33:9: error: ‘errors’ was not declared in this scope
rcppSim.cpp:35:1: error: ‘arma’ has not been declared
rcppSim.cpp:35:11: error: expected ‘;’ before ‘simdata’
rcppSim.cpp:36:1: error: ‘simdata’ was not declared in this scope
rcppSim.cpp:36:18: error: ‘arma’ has not been declared
rcppSim.cpp:36:30: error: ‘arma’ has not been declared
rcppSim.cpp:38:47: error: ‘coeff’ was not declared in this scope
rcppSim.cpp:38:52: error: ‘trans’ was not declared in this scope
make: *** [rcppSim.o] Error 1
g++ -I/usr/share/R/include -DNDEBUG -I"/usr/lib/R/library/Rcpp/include"
-I"/usr/lib/R/library/RcppArmadillo/include" -I"/usr/lib/R/library/Rcpp/include"
-fpic -g -O2 -fstack-protector --param=ssp-buffer-size=4 -Wformat -Wformat-security
-Werror=format-security -D_FORTIFY_SOURCE=2 -g -c rcppSim.cpp -o rcppSim.o
Error in sourceCpp("~/Dropbox/Rcpp/rcppSim.cpp") :
Error 1 occurred building shared library.
Running the dpkg command gives:
~$ dpkg -l | grep libgfortran | cut -c-75
ii libgfortran-4.7-dev 4.7.3-2ubuntu1~12.04
ii libgfortran-4.8-dev 4.8.1-2ubuntu1~12.04
ii libgfortran3 4.8.1-2ubuntu1~12.04
~$

Can you run the following command, please:
edd#max:~$ dpkg -l | grep libgfortran | cut -c-75
ii libgfortran-4.7-dev:amd64 4.7.3-7ubuntu3
ii libgfortran-4.8-dev:amd64 4.8.1-10ubuntu9
ii libgfortran3:amd64 4.8.1-10ubuntu9
edd#max:~$
You need the libgfortrain-$VERSION-dev package for your machine. At some point having gfortran implied this via r-base-dev and its dependence on build-essentials.
Edit: Version numbers will of course be different on your 12.04 release; this was from a machine running 13.10.
Edit 2, based on your update: Your use of sourceCpp() is incorrect. You are not telling Rcpp that you need Armadillo, so Rcpp responds by saying it does not know Armadillo. You can either use a Rcpp::depends() in the cpp file, or use the plugin= argument.
So here is how I would write the code you have above. You can then just call sourceCpp() on the file which will create a function rcppSim() you can call:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
// [[Rcpp::export]]
arma::mat rcppSim(arma::mat coeff, arma::mat errors) {
int m = errors.n_rows;
int n = errors.n_cols;
arma::mat simdata(m,n);
simdata.row(0) = arma::zeros<arma::mat>(1, n);
for (int row=1; row < m; row++) {
simdata.row(row) = simdata.row(row-1)*trans(coeff) + errors.row(row);
}
return simdata;
}

Related

RStan toolchain error on ubuntu

I installed RStan, had a problem, uninstalled it, and then tried reinstalling it using https://github.com/stan-dev/rstan/wiki/Installing-RStan-on-Mac-or-Linux
However, when I try using rstan, I get this error:
Error in library(rstan) : there is no package called ‘rstan’
I noticed when I run the toolchain diagnostic mentioned on the above page,
fx <- inline::cxxfunction( signature(x = "integer", y = "numeric" ) , '
return ScalarReal( INTEGER(x)[0] * REAL(y)[0] ) ;
' )
fx( 2L, 5 ) # should be 10
I get an error:
clang: warning: argument unused during compilation: '-arch x86_64'
clang: warning: argument unused during compilation: '-arch x86_64'
file16777e2261ec.o: file not recognized: File format not recognized
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [file16777e2261ec.so] Error 1
ERROR(s) during compilation: source code errors or compiler configuration errors!
Program source:
1:
2: // includes from the plugin
3: #include <R.h>
4: #include <Rdefines.h>
5: #include <R_ext/Error.h>
6:
7:
8: // user includes
9:
10:
11: // declarations
12: extern "C" {
13: SEXP file16777e2261ec( SEXP x, SEXP y) ;
14: }
15:
16: // definition
17:
18: SEXP file16777e2261ec( SEXP x, SEXP y ){
19:
20: return ScalarReal( INTEGER(x)[0] * REAL(y)[0] ) ;
21:
22: Rf_warning("your C++ program does not return anything");
23: return R_NilValue ;
24: }
25:
26:
Error in compileCode(f, code, language = language, verbose = verbose) :
Compilation ERROR, function(s)/method(s) not created! clang: warning: argument unused during compilation: '-arch x86_64'
clang: warning: argument unused during compilation: '-arch x86_64'
file16777e2261ec.o: file not recognized: File format not recognized
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [file16777e2261ec.so] Error 1
In addition: Warning message:
running command '/usr/lib/R/bin/R CMD SHLIB file16777e2261ec.cpp 2> file16777e2261ec.cpp.err.txt' had status 1
Error in fx(2L, 5) : could not find function "fx"
What is going wrong? Thank you!

Compilation error using iBMA.glm from BMA package

My problem is probably trival (hope), but I haven't found specific help on errors from this package and posts on compilation errors regard issues where people wrote a code themselfs (so they could change it).
I'm trying to replicate first example from example from BMA package help:
library(MASS)
library(BMA)
data(birthwt)
y <- birthwt$lo
x <- data.frame(birthwt[,-1])
x$race <- as.factor(x$race)
x$ht <- (x$ht>=1)+0
x <- x[,-9]
x$smoke <- as.factor(x$smoke)
x$ptl <- as.factor(x$ptl)
x$ht <- as.factor(x$ht)
x$ui <- as.factor(x$ui)
### add 41 columns of noise
noise<- matrix(rnorm(41*nrow(x)), ncol=41)
colnames(noise)<- paste('noise', 1:41, sep='')
x<- cbind(x, noise)
iBMA.glm.out<- iBMA.glm( x, y, glm.family="binomial",
factor.type=FALSE, verbose = TRUE,
thresProbne0 = 5 )
summary(iBMA.glm.out)
Everything goes fine until iBMA.glm function which returns lengthy compilation error which I completely don't understand (I've never compiled anything inside R with my hands):
Warning message:
running command 'make -f "C:/PROGRA~1/R/R-32~1.2/etc/x64/Makeconf" -f "C:/PROGRA~1/R/R-32~1.2/share/make/winshlib.mk" SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)' SHLIB="file1b2c792f3888.dll" WIN=64 TCLBIN=64 OBJECTS="file1b2c792f3888.o"' had status 127
ERROR(s) during compilation: source code errors or compiler configuration errors!
Program source:
1: #include <R.h>
2: #include <Rdefines.h>
3: #include <R_ext/Error.h>
4:
5:
6: /* This is taken from envir.c in the R 2.15.1 source
7: https://github.com/SurajGupta/r-source/blob/master/src/main/envir.c
8: */
9: #define FRAME_LOCK_MASK (1<<14)
10: #define FRAME_IS_LOCKED(e) (ENVFLAGS(e) & FRAME_LOCK_MASK)
11: #define UNLOCK_FRAME(e) SET_ENVFLAGS(e, ENVFLAGS(e) & (~ FRAME_LOCK_MASK))
12:
13:
14: extern "C" {
15: SEXP file1b2c792f3888 ( SEXP env );
16: }
17:
18: SEXP file1b2c792f3888 ( SEXP env ) {
19:
20: if (TYPEOF(env) == NILSXP)
21: error("use of NULL environment is defunct");
22: if (TYPEOF(env) != ENVSXP)
23: error("not an environment");
24:
25: UNLOCK_FRAME(env);
26:
27: // Return TRUE if unlocked; FALSE otherwise
28: SEXP result = PROTECT( Rf_allocVector(LGLSXP, 1) );
29: LOGICAL(result)[0] = FRAME_IS_LOCKED(env) == 0;
30: UNPROTECT(1);
31:
32: return result;
33:
34: warning("your C program does not return anything!");
35: return R_NilValue;
36: }
Error in compileCode(f, code, language, verbose) :
Compilation ERROR, function(s)/method(s) not created! Warning message:
running command 'make -f "C:/PROGRA~1/R/R-32~1.2/etc/x64/Makeconf" -f "C:/PROGRA~1/R/R-32~1.2/share/make/winshlib.mk" SHLIB_LDFLAGS='$(SHLIB_CXXLDFLAGS)' SHLIB_LD='$(SHLIB_CXXLD)' SHLIB="file1b2c792f3888.dll" WIN=64 TCLBIN=64 OBJECTS="file1b2c792f3888.o"' had status 127
In addition: Warning message:
running command 'C:/PROGRA~1/R/R-32~1.2/bin/x64/R CMD SHLIB file1b2c792f3888.cpp 2> file1b2c792f3888.cpp.err.txt' had status 1
My session info is:
> sessionInfo()
R version 3.2.2 (2015-08-14)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 7 x64 (build 7601) Service Pack 1
locale:
[1] LC_COLLATE=Polish_Poland.1250 LC_CTYPE=Polish_Poland.1250 LC_MONETARY=Polish_Poland.1250
[4] LC_NUMERIC=C LC_TIME=Polish_Poland.1250
attached base packages:
[1] grid stats graphics grDevices utils datasets methods base
other attached packages:
[1] BMA_3.18.4 rrcov_1.3-8 inline_0.3.14 robustbase_0.92-5 leaps_2.9
[6] survival_2.38-3 rJava_0.9-6 relaimpo_2.2-2 mitools_2.3 survey_3.30-3
[11] boot_1.3-17 MASS_7.3-43
loaded via a namespace (and not attached):
[1] mvtnorm_1.0-3 lattice_0.20-33 corpcor_1.6.8 pcaPP_1.9-60 stats4_3.2.2 splines_3.2.2
[7] tools_3.2.2 DEoptimR_1.0-3 cluster_2.0.3

Rcpp implicit construction of DataFrame from S4 slot

Rcpp::DataFrame pData =pheno.slot("data")
This fails on clang++ but succeeds with g++
error: conversion from 'Rcpp::SlotProxyPolicy<Rcpp::S4_Impl<PreserveStorage> >::SlotProxy' to 'Rcpp::DataFrame' (aka 'DataFrame_Impl<PreserveStorage>') is ambiguous
Rcpp::DataFrame fsdata = fspd.slot("data");
^ ˜˜˜˜˜˜˜˜˜˜˜˜˜˜˜˜˜

issue with cxxfunction of package inline

I was trying to run the colMaxRCpp function provided by Dirk Eddelbuettel in this post. I'm just repeating the function here so that folks reading this post don't have to click on the link.
library(inline)
colMaxRcpp <- cxxfunction(signature(X_="numeric"), plugin="Rcpp", body='
Rcpp::NumericMatrix X(X_);
int n = X.ncol();
Rcpp::NumericVector V(n);
for (int i=0; i<n; i++) {
Rcpp::NumericVector W = X.column(i);
V[i] = *std::max_element(W.begin(), W.end()); // from the STL
}
return(V);
')
When I tried to run it, I got the following error:
cygwin warning:
MS-DOS style path detected: C:/PROGRA~1/R/R-30~1.2/etc/x64/Makeconf
Preferred POSIX equivalent is: /cygdrive/c/PROGRA~1/R/R-30~1.2/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
file148253859d1.cpp:1:0: sorry, unimplemented: 64-bit mode not compiled in
make: *** [file148253859d1.o] Error 1
ERROR(s) during compilation: source code errors or compiler configuration errors!
Program source:
1:
2: // includes from the plugin
3:
4: #include <Rcpp.h>
5:
6:
7: #ifndef BEGIN_RCPP
8: #define BEGIN_RCPP
9: #endif
10:
11: #ifndef END_RCPP
12: #define END_RCPP
13: #endif
14:
15: using namespace Rcpp;
16:
17:
18: // user includes
19:
20:
21: // declarations
22: extern "C" {
23: SEXP file148253859d1( SEXP X_) ;
24: }
25:
26: // definition
27:
28: SEXP file148253859d1( SEXP X_ ){
29: BEGIN_RCPP
30:
31: Rcpp::NumericMatrix X(X_);
32: int n = X.ncol();
33: Rcpp::NumericVector V(n);
34: for (int i=0;i<n; i++) {
35: Rcpp::NumericVector W=X.column(i);
36: V[i] = *std::max_element(W.begin(),W.end());
37: }
38: return(V);
39:
40: END_RCPP
41: }
42:
43:
Error in compileCode(f, code, language = language, verbose = verbose) :
Compilation ERROR, function(s)/method(s) not created! cygwin warning:
MS-DOS style path detected: C:/PROGRA~1/R/R-30~1.2/etc/x64/Makeconf
Preferred POSIX equivalent is: /cygdrive/c/PROGRA~1/R/R-30~1.2/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
file148253859d1.cpp:1:0: sorry, unimplemented: 64-bit mode not compiled in
make: *** [file148253859d1.o] Error 1
In addition: Warning message:
running command 'C:/PROGRA~1/R/R-30~1.2/bin/x64/R CMD SHLIB file148253859d1.cpp 2>
file148253859d1.cpp.err.txt' had status 1
I can't understand the error message above. What can I do to fix this error? Thanks.
EDIT:
This is the error if I try evalCpp("2+2")
g++ -m64 -I"C:/PROGRA~1/R/R-30~1.2/include" -DNDEBUG -I"C:/Users/Pradipto/Documents/R/win- library/3.0/Rcpp/include" -I"C:/Users/Pradipto/Documents/R/win-library/3.0/Rcpp/include"
-I"d:/RCompile/CRANpkg/extralibs64/local/include" -O2 -Wall -mtune=core2 -c
file1bb87b48650d.cpp -o file1bb87b48650d.o file1bb87b48650d.cpp:1:0: sorry, unimplemented: 64- bit mode not compiled in make: *** [file1bb87b48650d.o] Error 1
Error in sourceCpp(code = code, env = env, rebuild = rebuild, showOutput = showOutput, :
Error 1 occurred building shared library.
It's not an issue with the code. Using Rcpp-as-released:
R> source("/tmp/uday.R") ## with your example in this file
R> colMaxRcpp(matrix(1:9,3))
[1] 3 6 9
R>
Try something simpler such as
R> evalCpp("2 + 2") ## eval expression via C++ program
[1] 4
R> evalCpp("M_PI") ## pi as constant in math.h
[1] 3.14159
R>
to see that your compiler is fine.

using SHLIB to compile and load standalone Rcpp function

I am trying to compile the following function with SHLIB (saved as foo.cpp):
#include <Rcpp.h>
RcppExport SEXP foo( SEXP x, SEXP y){
Rcpp::NumericVector xx(x), yy(y) ;
int n = xx.size() ;
Rcpp::NumericVector res( n ) ;
double x_ = 0.0, y_ = 0.0 ;
for( int i=0; i<n; i++){
x_ = xx[i] ;
y_ = yy[i] ;
if( x_ < y_ ){
res[i] = x_ * x_ ;
} else {
res[i] = -( y_ * y_) ;
}
}
return res ;
}
I try
$ R CMD SHLIB foo.cpp
/opt/local/bin/g++-mp-4.4 -I/opt/local/lib/R/include -I/opt/local/lib/R/include/x86_64 -I/opt/local/include -fPIC -pipe -O2 -m64 -c foo.cpp -o foo.o
foo.cpp:1:18: error: Rcpp.h: No such file or directory
foo.cpp:3: error: 'RcppExport' does not name a type
make: *** [foo.o] Error 1
How do I include this file, and is this the right way to compile a standalone function with Rcpp? Of course, I have installed Rcpp with install.packages('Rcpp').
Update:
Trying to find the location of Rcpp.h in R I get:
> system.file("lib", "Rcpp.h", package="Rcpp")
[1] ""
>
However,
> Rcpp:::LdFlags()
/opt/local/lib/R/library/Rcpp/lib/x86_64/libRcpp.a>
Update 2:
Looking at http://www.mail-archive.com/r-help#r-project.org/msg79185.html, I tried
$ PKG_CPPFLAGS=`Rscript -e 'Rcpp:::CxxFlags()'` \
> PKG_LIBS=`Rscript -e 'Rcpp:::LdFlags()'` \
> R CMD SHLIB foo.cpp
/opt/local/bin/g++-mp-4.4 -I/opt/local/lib/R/include -I/opt/local/lib/R/include/x86_64 -I/opt/local/lib/R/library/Rcpp/include -I/opt/local/include -fPIC -pipe -O2 -m64 -c foo.cpp -o foo.o
/opt/local/bin/g++-mp-4.4 -dynamiclib -Wl,-headerpad_max_install_names -undefined dynamic_lookup -single_module -multiply_defined suppress -L/opt/local/lib -o foo.so foo.o /opt/local/lib/R/library/Rcpp/lib/x86_64/libRcpp.a -L/opt/local/lib/R/lib/x86_64 -lR
and it generated foo.o and foo.so. How do I import this in R now?
Update 3:
So it can be loaded from dyn.load as
> dyn.load("foo.so")
> is.loaded("foo")
[1] TRUE
It can be called successfully as as
> .Call("foo",x=as.numeric(c(1,2,3)),y=as.numeric(c(4,5,6)))
[1] 1 4 9
Although the function is not visible as such.
> foo
Error: object 'foo' not found
Your question is clearly addressed in Question 2.4. of the Rcpp-FAQ.
The answer I found is that SHLIB needs to be provided the location of the Rcpp files. This can be done as
$ PKG_CPPFLAGS=`Rscript -e 'Rcpp:::CxxFlags()'` \
> PKG_LIBS=`Rscript -e 'Rcpp:::LdFlags()'` \
> R CMD SHLIB foo.cpp
Then, the compiled file can be loaded in R as
> dyn.load("foo.so")
and it can be called in R as
> .Call("foo",c(1,2,3),c(4,5,6))

Resources