[Rcpp-devel] Grid Search in RcppParallel

Romain Francois romain at r-enthusiasts.com
Sun Oct 5 08:40:31 CEST 2014


Envoyé de mon iPhone

> Le 5 oct. 2014 à 07:51, Jeffrey Wong <jeff.ct.wong at gmail.com> a écrit :
> 
> I am trying to use RcppParallel to do a fast grid search.  The idea is to construct a matrix using R's expand.grid, then for each row of that matrix, x, call f(x).  For simplicity the function f will always return a double.  Since Rcpp can call an R function I was hoping RcppParallel would allow me to use a parallelFor to process the rows of the grid quickly.  However, it keeps crashing R, and I am wondering if this is because an R function cannot be passed to RcppParallel?

You definitely cannot call an R function concurrently. 

> require(Rcpp)
> require(RcppParallel)
> 
> grid = as.matrix(expand.grid(a = 1:5, b = 1:5))
> 
> foo = function(pars) {pars[1]^2 + pars[2]^2}
> 
> RcppParallelGridSearch(grid, foo)
> 
> in .cpp file
> 
> #include <Rcpp.h>
> using namespace Rcpp;
> 
> // [[Rcpp::depends(RcppParallel)]]
> #include <RcppParallel.h>
> using namespace RcppParallel;
> 
> struct GridSearch : public Worker
> {
>    // source matrix
>    const RMatrix<double> grid;
>    const Function f;
>    
>    // destination vector
>    RVector<double> output;
>    
>    // initialize with source and destination
>    GridSearch(const NumericMatrix grid, const Function f, NumericVector output) 
>       : grid(grid), f(f), output(output) {}
>    
>    // take the square root of the range of elements requested
>    void operator()(std::size_t begin, std::size_t end) {
>      
>       for (std::size_t i = begin; i < end; i++) {
>         RMatrix<double>::Row parameters = grid.row(i);
>         output[i] = as<double>(f(parameters));
>       }
>    }
> };
> 
> // [[Rcpp::export]]
> NumericVector RcppParallelGridSearch(NumericMatrix grid, Function f) {
>   
>   // allocate the output matrix
>   NumericVector output(grid.nrow());
>   
>   // SquareRoot functor (pass input and output matrixes)
>   GridSearch gridSearch(grid, f, output);
>   
>   // call parallelFor to do the work
>   parallelFor(0, grid.nrow(), gridSearch);
>   
>   // return the output matrix
>   return output;
> }
> 
> -- 
> Jeffrey Wong
> My portfolio: http://jeffreycwong.com
> 
> _______________________________________________
> Rcpp-devel mailing list
> Rcpp-devel at lists.r-forge.r-project.org
> https://lists.r-forge.r-project.org/cgi-bin/mailman/listinfo/rcpp-devel
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20141005/54a5d43e/attachment.html>


More information about the Rcpp-devel mailing list