<div dir="ltr">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?<div><br></div><div><div>require(Rcpp)</div><div>require(RcppParallel)</div><div><br></div><div>grid = as.matrix(expand.grid(a = 1:5, b = 1:5))</div><div><br></div><div>foo = function(pars) {pars[1]^2 + pars[2]^2}</div><div><br></div><div>RcppParallelGridSearch(grid, foo)</div><div><br></div><div>in .cpp file</div><div><br></div><div><div>#include <Rcpp.h></div><div>using namespace Rcpp;</div><div><br></div><div>// [[Rcpp::depends(RcppParallel)]]</div><div>#include <RcppParallel.h></div><div>using namespace RcppParallel;</div><div><br></div><div>struct GridSearch : public Worker</div><div>{</div><div> // source matrix</div><div> const RMatrix<double> grid;</div><div> const Function f;</div><div> </div><div> // destination vector</div><div> RVector<double> output;</div><div> </div><div> // initialize with source and destination</div><div> GridSearch(const NumericMatrix grid, const Function f, NumericVector output) </div><div> : grid(grid), f(f), output(output) {}</div><div> </div><div> // take the square root of the range of elements requested</div><div> void operator()(std::size_t begin, std::size_t end) {</div><div> </div><div> for (std::size_t i = begin; i < end; i++) {</div><div> RMatrix<double>::Row parameters = grid.row(i);</div><div> output[i] = as<double>(f(parameters));</div><div> }</div><div> }</div><div>};</div><div><br></div><div>// [[Rcpp::export]]</div><div>NumericVector RcppParallelGridSearch(NumericMatrix grid, Function f) {</div><div> </div><div> // allocate the output matrix</div><div> NumericVector output(grid.nrow());</div><div> </div><div> // SquareRoot functor (pass input and output matrixes)</div><div> GridSearch gridSearch(grid, f, output);</div><div> </div><div> // call parallelFor to do the work</div><div> parallelFor(0, grid.nrow(), gridSearch);</div><div> </div><div> // return the output matrix</div><div> return output;</div><div>}</div></div><div><br></div>-- <br><div dir="ltr">Jeffrey Wong<div>My portfolio: <a href="http://jeffreyctwong.com" target="_blank">http://jeffreycwong.com</a></div><div><br></div></div>
</div></div>