All right, so I'm programming in R and I want to make a C++ function. I've imported the Rcpp and inline libraries. For right now, I'm just trying to make a simple function that adds 2 numbers, but no matter what I try, I get errors.
Here's my code:
cppstring = 'double ss = RcppSexp(s).asDouble(); return RcppSexp(ss+4).asSexp();'
hi <- cfunction(body=cppstring, signature(s="double"), Rcpp = TRUE)
and when I enter that second line, I get
file628a34ce.cpp: In function ‘SEXPREC* file628a34ce(SEXPREC*)’:
file628a34ce.cpp:9: error: ‘RcppSexp’ was not declared in this scope
make: *** [file628a34ce.o] Error 1
ERROR(s) during compilation: source code errors or compiler configuration errors!
Program source:
1: #include <Rcpp.h>
2:
3:
4: extern "C" {
5: SEXP file628a34ce ( SEXP s );
6: }
7:
8: SEXP file628a34ce ( SEXP s ) {
9: double ss = RcppSexp(s).asDouble(); return RcppSexp(ss+4).asSexp();
10: Rf_warning("your C program does not return anything!");
11: return R_NilValue;
12: }
Error in compileCode(f, code, language, verbose) :
Compilation ERROR, function(s)/method(s) not created! file628a34ce.cpp: In function ‘SEXPREC* file628a34ce(SEXPREC*)’:
file628a34ce.cpp:9: error: ‘RcppSexp’ was not declared in this scope
make: *** [file628a34ce.o] Error 1
I've tried everything I could possibly think of, from casting, to moving code around, to #including RcppSexp, to just plain returning s, and every time I get some error, whether it's
cannot convert ‘double’ to ‘SEXPREC*’ in return
or
invalid use of undefined type ‘struct SEXPREC’
or
forward declaration of ‘struct SEXPREC’
...I'm so confused :( I've looked at several examples online, and what I currently have seems to be what everyone else is doing, and it magically works for them...
What is this SEXPREC* thing I keep seeing everywhere? And what is that extern "C" function thing that it makes? And why does it generate statements AFTER my return statement and tell me that my function doesn't return anything, even though it does?
Is there a reason you are not starting from the (literally!!) dozens of Rcpp examples using inline?
Also, what on earth is RcppSexp? What documentation are your following?
Here is an example I did last night for someone on the rcpp-devel (which you should probably join):
library(Rcpp)
library(inline)
xorig <- c(1, -2, 3, -4, 5, -6, 7)
code <- '
Rcpp::NumericVector x(xs);
Rcpp::NumericVector xa = sapply( x, ::fabs );
return(xa);
'
xabs <- cxxfunction(signature(xs="numeric"),
plugin="Rcpp",
body=code)
xabs(xorig)
This is a more advanced example as it uses Rcpp sugar to give us vectorised expression a la R in C++, which we demonstrate here with a the simple sapply() from Rcpp sugar:
R> library(Rcpp)
R> library(inline)
R>
R> xorig <- c(1, -2, 3, -4, 5, -6, 7)
R>
R> code <- '
+ Rcpp::NumericVector x(xs);
+ Rcpp::NumericVector xa = sapply( x, ::fabs );
+ return(xa);
+ '
R>
R> xabs <- cxxfunction(signature(xs="numeric"),
+ plugin="Rcpp",
+ body=code)
R>
R> xabs(xorig)
[1] 1 2 3 4 5 6 7
R>
This most clearly demonstrates two of your requests: we use the implicit template converters as<>() to go from a SEXP given from R to the initial vector, and then use the implicit template converter wrap() to return the transformed second vector.
All this is explained in detail in the Rcpp-introduction vignette and the other vignettes in the Rcpp documentation,.
Related
Writing a function implementing a Jacobi Matrix for Newton's method I have noticed a really nasty error.
Calling the function
auto DF = [T](VectorXd y){
return PhiAndW(y(0),y(1),T).second - MatrixXd::Identity(2,2);
};
only returns the value of PhiAndW(y(0),y(1),T).second and omits the subtraction of MatrixXd::Identity(2,2). But if I change the code to
auto DF = [T](VectorXd y){
MatrixXd mat = PhiAndW(y(0),y(1),T).second - MatrixXd::Identity(2,2);
return mat;
};
everything works seamlessly.
I have tried to reproduce it and this is not the exact same behavior but it also doesn't behave as wanted:
Consider the following code:
MatrixXd FF(MatrixXd y){
return y;
}
int other(){
auto DF = [](MatrixXd y){
MatrixXd test = FF(y) - MatrixXd::Identity(2,2);
return test;
};
std::cout << DF(MatrixXd::Ones(2,2)) <<std::endl;
std::cout << std::endl;
std::cout << (MatrixXd::Ones(2,2) - MatrixXd::Identity(2,2))<< std::endl;
}
It will print
> 1 0
> 0 1
>
> 1 0
> 0 1
to the console.
However if I change to function DF to
auto DF = [](MatrixXd y){
return FF(y) - MatrixXd::Identity(2,2);
};
The console will print
> 2.22045e-15 1.63042e-322
> 2.37152e-322 -0.999998
for the second matrix. (Which is just some uninitialized junk from memory).
Could someone explain what is happening with my code and my example problem. I have truly no idea what is going on here. I am especially interested why saving the result of the calculation in a temporary variable fixes the problem.
Since the comments have pretty much solved my issue (thank you very much) I thought I'd go ahead and answer my question so that other people see that this problem has been solved.
Why does the problem occur?
The problem is that, for example the result type of an Eigen multiplication of two matrices is not an Eigen matrix, but some internal object which represents the multiplication and references the two matrices we are trying to multiply.
Hence, if we use the auto keyword the compiler will very likely not give the variable we are setting the type MatrixXd but the type of some internal object.
For more information refer to the Eigen documentation which explicitly states:
In short: do not use the auto keywords with Eigen's expressions, unless you are 100% sure about what you are doing. In particular, do not use the auto keyword as a replacement for a Matrix<> type
How do I prevent it from happening?
do not use the auto keyword, use explicit types.
for a lambda function always specify the return type: Write auto DF = []() -> MatrixXd {...} instead of auto DF = []() {...}
The following Rcpp code is the minimal reproducible example for a much larger code that generates the identical compilation error. It seems that I cannot asign a numeric matrix to a list and the list then again to another matrix.
#include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
List return_a(NumericMatrix a, NumericMatrix b){
//the function only returns the input matrix a
List result(1);
result(0) = a;
return(result);
}
//[[Rcpp::export]]
List wrapper_cpp(NumericMatrix a, NumericMatrix b){
//the function is a dummy wrapper for much more code
List Step1(1);
List results(1);
Step1 = return_a(a,b);
a = Step1(0);
results(0) = a;
return(results);
}
The code above gives the following compilation error that I shortened:
error: ambiguous overload for 'operator=' (operand types are 'Rcpp::NumericMatrix {aka Rcpp::Matrix<14>}' and 'Rcpp::Vector<19>::Proxy ...
a = Step1(0);
My real function is much more complex. I need to manipulate matrices in several loops and in each step the matrices are returned by each function within a list. I then need to extract these lists to manipulate the matrices further. How can this be done?
Besides the error that #Ralf already mentioned, you were simply trying too much. Sometimes we need an intermediate step as the template magic is ... finicky. The following works.
Code
#include <Rcpp.h>
using namespace Rcpp;
//[[Rcpp::export]]
List return_a(NumericMatrix a, NumericMatrix b){
//the function only returns the input matrix a
List result(1);
result(0) = a;
return(result);
}
//[[Rcpp::export]]
List wrapper_cpp(NumericMatrix a, NumericMatrix b){
//the function is a dummy wrapper for much more code
List results(1);
List Step1 = return_a(a,b);
NumericMatrix tmp = Step1(0);
results(0) = tmp;
return(results);
}
Output
R> Rcpp::sourceCpp("~/git/stackoverflow/54771818/answer.cpp")
R> wrapper_cpp(matrix(1:4,2,2), matrix(4:1,2,2))
[[1]]
[,1] [,2]
[1,] 1 3
[2,] 2 4
R>
Why does the following code not compile?
library(Rcpp)
cppFunction('
int rows(const NumericMatrix& X) {
using Eigen::MatrixXf;
typedef Eigen::Map<MatrixXf> MapMat;
MapMat X1(as<MapMat>(X));
return X1.rows();
}', depends = "RcppEigen")
It throws the following error:
error: no matching function for call to 'Eigen::Map<Eigen::Matrix<float, -1, -1> >::Map(Rcpp::Vector<14, Rcpp::PreserveStorage>::iterator, int&, int&)'
OUT get() {return OUT(vec.begin(), d_nrow, d_ncol );}
The same code works fine when I used MatrixXd instead.
Thanks.
NumericMatrix uses type double (as opposed to float). Eigen does not support implicit type casting between matrices using different types. Your code appears to try and read the memory of a double NumericMatrix as a float Eigen matrix. Just use the MatrixXd type instead.
I'm writing a small library for quantum mechanics and I want to use expression template to form operator expressions. Especially forming the Hamiltonian with expression template.
I basically followed this source to construct the code and overloading the corresponding operators + * -: https://en.wikipedia.org/wiki/Expression_templates
Forming the expression for the Hamiltonian requires a sum
Vec x = u_1 + u_2 + ... + u_N
where N is a (const) integer and u_i are also of type Vec. Writing this expression in the code works but I would like to be able to write
Vec x = Sum_{i=0}^{N} u_i
How would one do this?
------------ EDIT ------------
After some research and with the help of the comments, I came up with an idea of static for loop... After googling I found an article in http://www.drdobbs.com/loops-metaloops-c/184401835?pgno=8 which is exactly what I needed.
There is no way to write a template or function that magically pattern matches variables from the surrounding scope, so your u_i syntax can not work. You could do something similar with a macro, e.g.:
#define SUM_4(x) x ## 1 + x ## 2 + x ## 3 + x ## 4
Usage:
Vec u_1, u_2, u_3, u_4;
...
Vec x = SUM_4(u_);
You'd need to define additional macros for other numbers of source vectors.
The subscript operator in C++ is modeled by array access, e.g. u[1], u[2], .... If you are willing to maintain an array of Vec, you could write a generic function that iterates over the array. In this case the parameter would be the array. Something like:
template<typename T, int N>
T sum(T (&u)[N])
{
// (or your preferred summation procedure)
T x = u[0];
for (int i=1; i < N; ++i)
x += u[i];
return x;
}
Usage:
Vec u[4];
...
Vec x = sum(u);
Even better use a std::vector or fixed size array template.
P.S. Consider using Eigen.
EDIT: Updated sum() template with array size deduction from http://www.cplusplus.com/articles/D4SGz8AR/
I am brand new to Rcpp. I am trying to using the R package RcppEigen to get the determinant of a matrix. The following code is saved in a file and I use sourceCpp to use it. There is no compilation error when I use sourceCpp. When using getDeterminant(A) in R, A is a matrix. It always complains the following error.
"Error: could not find function "getDeterminant""
However, the getEigenValues works well.
I appreciate a lot if anybody is happy to help me with this.
Thanks a lot!
#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]
using Eigen::Map; // 'maps' rather than copies
using Eigen::MatrixXd; // variable size matrix, double precision
using Eigen::VectorXd; // variable size vector, double precision
using Eigen::SelfAdjointEigenSolver; // one of the eigenvalue solvers
using Eigen::MatrixXi;
using Eigen::MatrixBase;
// [[Rcpp::export]]
VectorXd getEigenValues(Map<MatrixXd> M) {
SelfAdjointEigenSolver<MatrixXd> es(M);
return es.eigenvalues();
}
// [[Rcpp:export]]
double getDeterminant(Map<MatrixXd> AA){
return AA.determinant();
}
You are missing a : in the second Rcpp Attributes tag: Rcpp::export is the form the regular expression looks for.
If you add it, the functions becomes accessible:
R> Rcpp::sourceCpp("/tmp/crystal.cpp")
R> M <- matrix(1:9,3,3)*1.0
R> getEigenValues(M)
[1] 2.80689e-16 6.99265e-01 1.43007e+01
R> getDeterminant(M)
[1] 0
R>