I receive a fatal error with boost and Rcpp - r

As described in the post:
Rcpp and boost: it should work but it does not
I am trying to use boost in Rcpp in Windows. The (simplified) file is:
// [[Rcpp::depends(BH)]]
#include <Rcpp.h>
#include <boost/multiprecision/float128.hpp>
namespace mp = boost::multiprecision;
// [[Rcpp::export]]
std::string qexp(double da = -1500.0, double db = -1501.0)
{
mp::float128 a(da), b(db);
mp::float128 res = mp::exp(a) / (mp::exp(a) + mp::exp(b));
return res.convert_to<std::string>();
}
I had a compile problem. As #duckmayr suggested in that post, I tried with:
Sys.setenv("PKG_LIBS" = "-lquadmath")
and then Rcpp::sourceCpp('quadexp.cpp')
In this way, the compilation runs without errors. But then, when I execute qexp(), I get a message in RStudio about "fatal error", and RStudio shuts down completely. Do you know what could be happening? I assume my problem is due to some kind of configuration I have, since #duckmayr could run the same code without problems. What parts of my configuration should look at, in order to avoid this nasty "fatal error"?

In addition to the comment above:
edd#rob:~/git/so-r/52933795$ cat code.cpp
// [[Rcpp::depends(BH)]]
#include <Rcpp.h>
#include <boost/multiprecision/float128.hpp>
namespace mp = boost::multiprecision;
// [[Rcpp::export]]
std::string qexp(double da = -1500.0, double db = -1501.0) {
mp::float128 a(da), b(db);
mp::float128 res = mp::exp(a) / (mp::exp(a) + mp::exp(b));
return res.convert_to<std::string>();
}
/*** R
qexp()
*/
edd#rob:~/git/so-r/52933795$ Rscript -e 'Rcpp::sourceCpp("code.cpp")'
R> qexp()
[1] "0.731058578630004879251159241821836351"
edd#rob:~/git/so-r/52933795$
I.e. using exactly your code (plus an added R invocation) it just works "as is".

Related

Rcpp installed but compilation error from complex code snippet

I have Rcpp and RccpEigen already installed in RStudio. I am able to run an Rcpp code (that didn't use RccpEigen) successfully as well. However the following code which uses both doesn't seem to work.
Here is the code -
library(Rcpp)
library(RcppEigen)
sourceCpp(code = '
#include <Rcpp.h>
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
using namespace Rcpp;
using namespace Eigen;
using namespace RcppEigen;
// [[Rcpp::export]]
List luEigen(MatrixXd M) {
FullPivLU<MatrixXd> luE(M);
return List::create(Named("L_matrix") = luE.matrixLU().triangularView<Upper>());
}')
A <- 0.8 + 0.2 * diag(100)
(luEigen(A))
This code gives a really long error, so here are the key error lines -
/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include/Rcpp/generated/Vector__create.h:71:10: note: in instantiation of function template specialization 'Rcpp::Vector<19, PreserveStorage>::create__dispatch<Rcpp::traits::named_object<Eigen::TriangularView<const Eigen::Matrix<double, -1, -1, 0>, 2>>>' requested here
return create__dispatch( typename traits::integral_constant<bool,
^
file16bbd8305f5c.cpp:11:18: note: in instantiation of function template specialization 'Rcpp::Vector<19, PreserveStorage>::create<Rcpp::traits::named_object<Eigen::TriangularView<const Eigen::Matrix<double, -1, -1, 0>, 2>>>' requested here
return List::create(Named("L_matrix") = luE.matrixLU().triangularView<Upper>());
^
18 warnings and 1 error generated.
make: *** [file16bbd8305f5c.o] Error 1
clang++ -mmacosx-version-min=10.13 -std=gnu++14 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/Rcpp/include" -I"/Library/Frameworks/R.framework/Versions/4.1/Resources/library/RcppEigen/include" -I"/private/var/folders/_3/wdql3v5d4vggzffw3xdcr3p80000gn/T/RtmpQioi38/sourceCpp-x86_64-apple-darwin17.0-1.0.7" -I/usr/local/include -fPIC -Wall -g -O2 -c file16bbd8305f5c.cpp -o file16bbd8305f5c.o
Given that Rcpp and RccpEigen are installed and a different Rccp code does work, what may be causing error in this code?
With a very helpful suggestion from #Dirk, I simplified the decomposition and that did the trick. Still not sure why the more complex construction threw an error, but bottom line is that simplification gets the job done. Here is my modified code that works -
library(Rcpp)
library(RcppEigen)
sourceCpp(code = '
#include <Rcpp.h>
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
using namespace Rcpp;
using namespace Eigen;
using namespace RcppEigen;
// [[Rcpp::export]]
List luEigen(MatrixXd M) { // here I name our function
FullPivLU<MatrixXd> luE(M); // here I perform the decomposition
MatrixXd upper = luE.matrixLU().triangularView<Upper>(); // this creates the upper matrix
MatrixXd lower = luE.matrixLU().triangularView<StrictlyLower>(); // this creates the lower matrix
return List::create(Named("U_matrix") = upper, Named("L_matrix") = lower); // this makes the list of the 2 matrices
}')
A <- 0.8 + 0.2 * diag(100)
(luEigen(A))
You could possibly speed it up further by doing the decomposition only once and calling the upper and lower triangular matrices from it, like so -
FullPivLU<MatrixXd> luE(M); // here I perform the decomposition
MatrixXd decomp = luE.matrixLU();
MatrixXd upper = decomp.triangularView<Upper>(); // this creates the upper matrix
MatrixXd lower = decomp.triangularView<StrictlyLower>(); // this creates the lower matrix

Returning a user-defined structure from Rcpp in an R package

Rcpp is powerful and has worked great in most all cases, but I cannot figure out how to wrap a C-function that returns a user-defined structure into an R package.
DESCRIPTION
Package: myPackage
Type: Package
Title: What the Package Does (Title Case)
Version: 0.1.0
Depends: R (>= 4.0.0)
License: GPL-3
Encoding: UTF-8
LazyData: true
RoxygenNote: 7.1.0
Imports:
Rcpp
Suggests:
knitr,
rmarkdown,
testthat
VignetteBuilder: knitr
LinkingTo:
Rcpp
NAMESPACE
# Generated by roxygen2: do not edit by hand
importFrom(Rcpp,evalCpp)
export(read_header)
useDynLib(myPackage, .registration = TRUE)
Header File ("inst/include/myPackage_types.h")
#include <Rcpp.h>
namespace Rcpp {
typedef struct {
int my_data;
} MY_HEADER_INFO;
template <> SEXP wrap(const MY_HEADER_INFO& x) {
std::vector<std::string> names;
std::vector<SEXP> elements(1);
// do something with the elements and names
names.push_back("my_data");
elements[0] = Rcpp::wrap( x.my_data );
return 0;
};
}
C-code
/*
read_header.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <Rcpp.h>
#include "inst/include/myPackage_types.h"
namespace Rcpp {
// [[Rcpp::export]]
Rcpp::MY_HEADER_INFO read_header() {
Rcpp::MY_HEADER_INFO *header;
header = (Rcpp::MY_HEADER_INFO*)malloc(sizeof(Rcpp::MY_HEADER_INFO));
memset(header, 0, sizeof(Rcpp::MY_HEADER_INFO));
return *header;
}
}
When I source (i.e., compile) the C-code, I get the following:
Error in dyn.load("/private/var/folders/gl/jvj9b0xn34lgq6_h9370p8q80000gn/T/RtmpYRaBGW/sourceCpp-x86_64-apple-darwin17.0-1.0.4.6/sourcecpp_25a13fe3d7da/sourceCpp_49.so") :
unable to load shared object ...
When I try to build the package (CMD + Shift + B), I get:
clang++ -mmacosx-version-min=10.13 -std=gnu++11 -I"/Library/Frameworks/R.framework/Resources/include" -DNDEBUG -I'/Library/Frameworks/R.framework/Versions/4.0/Resources/library/Rcpp/include' -I/usr/local/include -fPIC -Wall -g -O2 -UNDEBUG -Wall -pedantic -g -O0 -fdiagnostics-color=always -c RcppExports.cpp -o RcppExports.o
RcppExports.cpp:9:7: error: no type named 'MY_HEADER_INFO' in namespace 'Rcpp'
Rcpp::MY_HEADER_INFO read_header();
~~~~~~^
This seems so simple, but I can't find a similar vignetter or example and none of the variations I've tried seem to work. What is the cause of the dynamical loading error for SourceCpp? Why can't the compiler find the code in the header file?
Thanks!
I got this to work and have posted my solution to GitHub: git#github.com:markrbower/myPackage.git
The key parts are:
inst/include/myPackage_types.h
#include <RcppCommon.h>
namespace Rcpp {
typedef struct {
int my_data;
} MY_HEADER_INFO;
template <> SEXP wrap(const MY_HEADER_INFO& x);
template<> MY_HEADER_INFO* as(SEXP x);
}
read_header.cpp
/*
read_header.c
*/
#include <stdio.h>
#include <stdlib.h>
#include "../inst/include/myPackage_types.h"
#include <RcppCommon.h>
namespace Rcpp {
template <> SEXP wrap(const MY_HEADER_INFO& x);
}
#include <Rcpp.h>
namespace Rcpp {
template <> SEXP wrap(const MY_HEADER_INFO& x) {
std::vector<std::string> names;
std::vector<SEXP> elements(1);
// do something with the elements and names
names.push_back("my_data");
elements[0] = wrap( x.my_data );
Rcpp::List result(elements.size());
for (size_t i = 0; i < elements.size(); ++i) {
result[i] = elements[i];
}
result.attr("names") = Rcpp::wrap(names);
// result can be return to R as a list
return( result );
};
}
//' #importFrom Rcpp evalCpp
//' #useDynLib myPackage
//' #export
// [[Rcpp::export]]
Rcpp::MY_HEADER_INFO read_header() {
Rcpp::MY_HEADER_INFO *header = NULL;
printf( "%ld\n", sizeof(Rcpp::MY_HEADER_INFO) );
header = (Rcpp::MY_HEADER_INFO*)malloc(sizeof(Rcpp::MY_HEADER_INFO));
memset(header, 0, sizeof(Rcpp::MY_HEADER_INFO));
header->my_data = 10;
return *header;
}
There were two problems. First, I had template definitions under the wrong Rcpp header (put the initial calls after RcppCommon.h and the detailed calls after Rcpp.h). The tutorials and examples warned me not to do that, but I did it, anyway. Second, I found that if you "source" the code and then "load" the library, the sourced code will obscure the library code and you will get a "null pointer" error. Running "devtools::check()" showed me that along with noting that the fix is to "rm" the sourced function.
Let me also add that there are two Roxygen comments that I needed to add to my .cpp file to get the appropriate commands to appear in my NAMESPACE file:
//' #importFrom Rcpp evalCpp
//' #useDynLib myPackage
I found an old post where Dirk suggested using the Rcpp.package.skeleton function to build a "baby" project and then slowly add things until you can do what you want. That is so much better than the approach I have been using: Start with a complex C program and try to shoehorn my code into Rcpp.

RcppArmadillo "Error in inDL(x, as.logical(local), as.logical(now), ...)" under Windows Platform [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I have some functions written in Rcpp and RcppArmadillo like this
example.cpp:
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <iostream>
#include <math.h>
using namespace Rcpp;
// using namespace RcppArmadillo;
using namespace arma;
using namespace std;
// [[Rcpp::export]]
double inner1(NumericVector x, NumericVector y) {
int K = x.length() ;
double ip = 0 ;
for (int k = 0 ; k < K ; k++) {
ip += x(k) * y(k) ;
}
return(ip) ;
}
// [[Rcpp::export]]
mat multiply2(mat A, mat B) {
return A * B;
}
Then I use Rcpp::sourceCpp('example.cpp') and It works well under Ubuntu.
(I have run library(Rcpp) and library(RcppArmadillo) before )
However, When I move to Windows Platform, the RStudio Throw an error said:
> Rcpp::sourceCpp('R:/example.cpp')
Error in inDL(x, as.logical(local), as.logical(now), ...) :
unable to load shared object 'C:/Users/[Username]/AppData/Local/Temp/RtmpG6H80X/sourceCpp-x86_64-w64-mingw32-0.12.19/sourcecpp_40b04b2c2bcf/sourceCpp_4.dll':
LoadLibrary failure: The specified procedure could not be found.
I found the key problem is in the matrix multiplication. Since I try to delete the second function multiply2. Then the rest of the code can be complied successfully under Windows.
example2.cpp
#include <RcppArmadillo.h>
// [[Rcpp::depends(RcppArmadillo)]]
#include <iostream>
#include <math.h>
using namespace Rcpp;
// using namespace RcppArmadillo;
using namespace arma;
using namespace std;
// [[Rcpp::export]]
double inner1(NumericVector x, NumericVector y) {
int K = x.length() ;
double ip = 0 ;
for (int k = 0 ; k < K ; k++) {
ip += x(k) * y(k) ;
}
return(ip) ;
}
I have tried some other codes, found that this error occurs when matrix multiplication * was used in code.
So, Why matrix multiplication in RcppArmadillo fails under Windows Platform?
After the struggled with the compiler for a long time, I found the key point is the BLAS library was not correctly set in my windows system environment path.
In short, the solution is :
Download precompiled binary packages of OpenBLS at Here (DO NOT try to compile the newest version under windows, I've waste a lot time on it)
Exactor OpenBLAS-v0.2.19-Win64-int32.zip to some where like C:\LIBS\OpenBLAS-v0.2.15-Win64-int32
Add C:\LIBS\OpenBLAS-v0.2.15-Win64-int32\bin to your PATH
[Optional] Create a new environment variable called BLAS_LIBS, which value is C:\LIBS\OpenBLAS-v0.2.15-Win64-int32\bin
Restart RStudio, and the problem was solved.
I find this solution by install RcppArmadillo from source by install.packages("RcppArmadillo", type = "source"), this time the RStudio throw the same error during the compiling, so the install fails.
However, if I just use install.packages("RcppArmadillo"), the RStudio will install binary version of RcppArmadillo, so I didn't get any feedback about the absence of BLAS.

Fortran code and Found no calls to: 'R_registerRoutines', 'R_useDynamicSymbols'

When I submit my package to cran I get the error as
Found no calls to: 'R_registerRoutines', 'R_useDynamicSymbols'
It is good practice to register native routines and to disable symbol
search.
My package was tested in this version of R by CRAN:
R version 3.4.0 alpha (2017-03-28 r72427)
Note that there is a solution for this error here
R CMD check note: Found no calls to: ‘R_registerRoutines’, ‘R_useDynamicSymbols’
but my external codes are in Fortran and tried the procedure described there but does not fix the issue for me. What can I do to overcome the issue?
Thanks
Update:
Following the procedure described https://www.r-bloggers.com/1-easy-package-registration/ I could pass the
Error:Found no calls to: ‘R_useDynamicSymbols’
But Found no call to: 'R_registerRoutines' still remains.
I solved the problem and you may find it useful for your own case.
Let's assume you have a subroutine called myf.f90 in src directory with following content:
SUBROUTINE cf(r,cd,loci)
INTEGER::r,cd
DOUBLE PRECISION::loci
....
....
....
END SUBROUTINE cf
To register this you need to do the following :
A) Run tools::package_native_routine_registration_skeleton("package directory")
B) Edit the output; for the example above would be:
#include <R.h>
#include <Rinternals.h>
#include <stdlib.h> // for NULL
#include <R_ext/Rdynload.h>
/* FIXME:
Check these declarations against the C/Fortran source code.
*/
/* .Fortran calls */
extern void F77_NAME(cf)(int *r, int *cd, double *loci);
static const R_FortranMethodDef FortranEntries[] = {
{"cf", (DL_FUNC) &F77_NAME(cf), 3},
{NULL, NULL, 0}
};
void R_init_packagename(DllInfo *dll)
{
R_registerRoutines(dll, NULL, NULL, FortranEntries, NULL);
R_useDynamicSymbols(dll, FALSE);
}
C) Copy and paste the full output in a packagename_init.c file to be put in src/
D) Update NAMESPACE, verifying that useDynLib(packagename, .registration = TRUE)

Rcpp - Compile a C++ file with multiple functions

I have just quick question about how to compile a .cpp file with multiple function in it.
Let's say I have c++ file like this : Functions.cpp
#include <Rcpp.h>
#include <math.h> /* pow */
using namespace Rcpp;
// [[Rcpp::export]]
int Function1 (int N, NumericMatrix W){
return ....
}
// [[Rcpp::export]]
int Function2 (int N, NumericMatrix W){
return ....
}
and then I would like to compile the file and be able to to call both functions.
I have done it, but what happens is when I try to load the Functions.o it gives me this":
Error in inDL(x, as.logical(local), as.logical(now), ...) :
unable to load shared object 'C:/Users/Functions.o':
LoadLibrary failure: %1 is not a valid Win32 application.
Anybody , any idea ?
Just use sourceCpp("nameofyourfile.cpp")
If you you have no syntax error preventing compilation both Function1 and Function2 will be accessible in your R session.
Literally thousands of such files have been written, and almost one hundred are at your disposal over at the Rcpp Gallery.

Resources