Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it okay to modify a mapped matrix in RcppEigen?

Tags:

r

rcpp

I'm writing some code in RcppEigen, and I came across this ominous warning in the documentation:

One must, of course, be careful not to modify the contents of the R object in the C++ code. A recommended practice is always to declare mapped objects as const.

This refers to "mapped" matrices, i.e. matrices in Eigen that use the same memory as the corresponding R object.

Is this warning just about good functional programming practice, or are there other things that can go wrong if I use mapped objects to do modify-in-place?


This is a simplified version of what I'm doing in Rcpp:

#include <RcppEigen.h>
// [[Rcpp::depends(RcppEigen)]]

// [[Rcpp::export]]
void modify(Eigen::Map<Eigen::MatrixXd> X) {

    X(0,0) = 0;
    return;
}

Which does things like this in R:

X <- matrix(1:4, 2) + 0
X
#      [,1] [,2]
# [1,]    1    3
# [2,]    2    4
modify(X)
X
#      [,1] [,2]
# [1,]    0    3
# [2,]    2    4

For the particular problem I'm working on I'm getting a 5x speed increase by modifying my matrix in place, so I'm prepared for that small sacrifice in terms of readability and maintainability. As far as I can tell it's working as intended, but I'm worried that I'm inviting some sort of subtle bug some time in the future.

like image 445
pete Avatar asked Jan 14 '15 02:01

pete


1 Answers

It is perfectly ok to modify provided you remain aware of the side-effect of the variable in R.

In a purely functional world, you would want no side-effects: inputs are processed and not altered, a result is returned.

Here we have a more hybrid approach. Objects are passed down from R as SEXP, and the P stands for pointer---so changes persist. That confuses some people, and we sometimes have to explain here how to avoid it. :)

But in short you are safe, particularly if just set elements and do not do crazy stuff like altering dimensions etc pp.

like image 169
Dirk Eddelbuettel Avatar answered Oct 20 '22 15:10

Dirk Eddelbuettel