简体   繁体   中英

Errors when using OptimLib in Rcpp

I encountered an error when using OptimLib library in Rcpp.First I copied sphere_fn function online in order to use it later in optim function. However, this shere_fn didn't work.

Error: can not initialize a member subobject of type `'arma::Col<double>*'with an lvalue of type 'SEXP'(aka'SEXPREC *').` 

It seems the problem was at grad_out,but this input form is required for optim function.

For example, the optim algorithm is called using:

bool cg(arma::vec& init_out_vals, std::function<double (const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)> opt_objfn, void* opt_data);  

Could anyone help me with this?

My code is:

#include <iostream>
#include <math.h>       /* sqrt */

#define USE_RCPP_ARMADILLO
#include "optim.hpp"

// [[Rcpp::depends(RcppArmadillo)]]

using namespace Rcpp;
using namespace std;

// This is a simple example of exporting a C++ function to R. You can
// source this function into an R session using the Rcpp::sourceCpp
// function (or via the Source button on the editor toolbar). Learn
// more about Rcpp at:
//
//   http://www.rcpp.org/
//   http://adv-r.had.co.nz/Rcpp.html
//   http://gallery.rcpp.org/
//


// [[Rcpp::export]]
double sphere_fn(const arma::vec& vals_inp, arma::vec* grad_out, void* opt_data)
{
  double obj_val = arma::dot(vals_inp,vals_inp);
  //
  if (grad_out) {
    *grad_out = 2.0*vals_inp;
  }
  //
  return obj_val;
}

Well sometime you may need to put in the time to learn to walk before you can compete in races.

In other words, you cannot just put semi-arbitrary signatures in there and expect Rcpp Attributes to translate it it all for you. What is void * supposed to map to? Ditto for arma::vec*.

Just pass an arma::vec, it will use a pointer internally. Study some existing examples from working RcppArmadillo-using package, and maybe glance at some of the vignettes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM