从 std::vector 到 adept::avector

from std::vector to adept::avector

我想在 R 的包中嵌入一些熟练的优化。请参阅下面的最小示例。我需要将 x(和 b)的值传递给该函数。默认情况下,它们以 Rcpp:NumericVector 形式出现,这很容易转换为 std::vector 或双精度数组,例如

std::vector<double> inx_std(inx.begin(),inx.end());
double* inx_d = inx_std.data();

但是,我无法将其传递给向量 a。 avector a = inx_d 不起作用。我创建了一个 for 循环,一切正常,但必须有更好的方法来做到这一点。

下面的代码示例。

#include <Rcpp.h>
#include "adept_source.h"
#include <adept_arrays.h>                

using namespace Rcpp;
using namespace adept;


// [[Rcpp::export]]
NumericVector run(NumericVector inx, NumericVector inb) {
  int inxsize=inx.size();       // dim of gradient
  NumericVector out(inxsize);   // output vector

  //adept main 

  Stack stack;                    // Object to store differential statements
  aVector x(inxsize);             // Independent variables: active vector with inxsize elements
  aVector b(inxsize);             // Independent variables: active vector with inxsize elements
  for(int i=0; i<inxsize; i++) {  // Fill vector
    x[i]=inx(i);
    b[i]=inb(i);
  }

  stack.new_recording();          // Clear any existing differential statements

  //function to be differentiated 
  aReal J = sum(log(x)/log(b));   // Compute dependent variable: L3-norm in this case


  //adept main
  J.set_gradient(1.0);             // Seed the dependent variable
  stack.reverse();                 // Reverse-mode differentiation

  //return gradient from adept to R
  for(int i=0; i<inxsize; i++) {
    out[i]=x[i].get_gradient();
  }

  return out;
}

基于 JHBonarius 的有用评论和 Dirk 关于指针的提示,我创建了以下通过 Rcpp 在 R 中使用 adept 的最小示例:

#include <Rcpp.h>
#include <adept_source.h>
#include <adept_arrays.h>                

using namespace Rcpp;
using namespace adept;


// [[Rcpp::export]]
NumericVector run(NumericVector inx, NumericVector inb, double gamma) {
  int inxsize=inx.size();       // dim of gradient
  NumericVector out(inxsize);   // output vector

  //convert inputs to adept arrays
  adept::Vector inxV(inx.begin(), dimensions(inxsize) );  
  adept::Vector b(inb.begin(), dimensions(inxsize) );  

  //adept main 
  Stack stack;                    // Object to store differential statements
  adept::aVector x = inxV;

  stack.new_recording();          // Clear any existing differential statements

  //function to be differentiated
  aReal J = gamma*sum(log(x)/log(b));   // Compute dependent variable


  //adept main
  J.set_gradient(1.0);             // Seed the dependent variable
  stack.reverse();                 // Reverse-mode differentiation


  //return gradient from adept to R
  for(int i=0; i<inxsize; i++) {
    out[i]=x[i].get_gradient();
  }

  return out;
}

/*** R
run(1:3,rep(exp(1),3),1)
*/

解决方案的关键要素是:

(1) 创建一个 adept::Vector,使用带有指向名为 inx 的输入 Rcpp::Numericvector 的指针的适当构造函数:

adept::Vector inxV(inx.begin(), dimensions(inxsize) )

(2) 然后可以将感兴趣的向量(我们要为其计算偏导数)转换为 'active' 向量:

adept::aVector x = inxV;