[Rcpp-devel] Grid Search in RcppParallel
Jeffrey Wong
jeff.ct.wong at gmail.com
Sun Oct 5 07:51:25 CEST 2014
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?
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 <http://jeffreyctwong.com>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.r-forge.r-project.org/pipermail/rcpp-devel/attachments/20141004/1cfc0c6c/attachment.html>
More information about the Rcpp-devel
mailing list