Ошибка компилятора R cpp с возвращаемым значением - без понятия - PullRequest
1 голос
/ 23 апреля 2020

Я пытаюсь ускорить код R с помощью функций R cpp. Одна функция дает мне припадки для компиляции, и я не знаю, почему компилятор жалуется на возвращаемый аргумент. Я объявил функцию для возврата NumericVector, результатом является NumericVector, и все же компилятор жалуется, что возвращаемый аргумент недействителен.

R cpp - версия 0.12.18, R - Microsoft Open R 3.5.3

cppFunction('NumericVector NNE(IntegerVector X, IntegerVector Y, IntegerVector XY, IntegerVector xy, NumericVector P, int radius ) {

  int n = X.size();
  NumericVector vN[n];
  NumericVector vSum[n];
  NumericVector vAvg[n];


  // for each xy determine neighborhood Sum and count (N)
  for(int i=0; i<n; i++) {
    vN[i] = 0.0;
    vSum[i] = 0.0;

    // traverse neighborhood, if the xy exists in the input
    // vector then accumulate the values, otherwise ignore

    for(int dx=-1*radius; dx<=radius; dx++) {
      for(int dy=-1*radius; dy<=radius; dy++) {

        // construct an xy index for the neighborhood die
        xy[0] = ( (X[i]+dx) * 10000 ) + (Y[i]+dy);

        // check to see if index above exists in input set
        IntegerVector m = Rcpp::match(xy, XY);

        // if valid then accumulate and count
        if(m[0] != NA_INTEGER) {
          vN[i] = vN[i] + 1.0;
          vSum[i] = vSum[i] + P[ m[0] ];
        }
      }
    }

    vAvg[i] = vSum[i] / vN[i];
  }

  return vAvg;
}')

Запутанное сообщение компилятора выглядит следующим образом:

C:/RBuildTools/3.5/mingw_64/bin/g++ -m64 -I"C:/PROGRA~1/MICROS~3/ROPEN~1/R-35~1.3/include" -DNDEBUG   -I"D:/Users/ka/Documents/R/win-library/3.5/Rcpp/include" -I"D:/Users/ka/AppData/Local/Temp/4/RtmpeGKfUg/sourceCpp-x86_64-w64-mingw32-0.12.18"   -I"C:/a/w/1/s/vendor/extsoft/include"     -O2 -Wall  -mtune=core2 -c filefcc651c7fa9.cpp -o filefcc651c7fa9.o
filefcc651c7fa9.cpp: In function 'Rcpp::NumericVector NNE(Rcpp::IntegerVector, Rcpp::IntegerVector, Rcpp::IntegerVector, Rcpp::IntegerVector, Rcpp::NumericVector, int)':
filefcc651c7fa9.cpp:42:10: error: invalid conversion from 'Rcpp::NumericVector* {aka Rcpp::Vector<14, Rcpp::PreserveStorage>*}' to 'const int&' [-fpermissive]
   return vAvg;
          ^
In file included from D:/Users/ka/Documents/R/win-library/3.5/Rcpp/include/Rcpp/Vector.h:52:0,
                 from D:/Users/ka/Documents/R/win-library/3.5/Rcpp/include/Rcpp.h:40,
                 from filefcc651c7fa9.cpp:1:
D:/Users/ka/Documents/R/win-library/3.5/Rcpp/include/Rcpp/vector/Vector.h:128:5: note: initializing argument 1 of 'Rcpp::Vector<RTYPE, StoragePolicy>::Vector(const int&) [with int RTYPE = 14; StoragePolicy = Rcpp::PreserveStorage]'
     Vector( const int& size ) {
     ^
make: *** [C:/PROGRA~1/MICROS~3/ROPEN~1/R-35~1.3/etc/x64/Makeconf:215: filefcc651c7fa9.o] Error 1
Error in sourceCpp(code = code, env = env, rebuild = rebuild, cacheDir = cacheDir,  : 
  Error 1 occurred building shared library.

1 Ответ

4 голосов
/ 23 апреля 2020

У вас была miniscule ошибка рендеринга переменная"плохая" в том, что касается компилятора, и затем вы неправильно поняли отклоненный возврат "плохой" переменной как другую вопрос.

Это происходит. Мы все были там.

Вот исправленный код. Короче говоря, вам нужно было NumeriVector x(n); с round вместо прямоугольных скобок (поскольку последние обозначают массивы в C, а затем в C ++).

Код

Я также превратил его во входные данные для sourceCpp(), что легче, учитывая длину функций.

#include <Rcpp.h>

using namespace Rcpp;

// [[Rcpp::export]]
NumericVector NNE(IntegerVector X, IntegerVector Y, IntegerVector XY,
                  IntegerVector xy, NumericVector P, int radius ) {

  int n = X.size();
  NumericVector vN(n);
  NumericVector vSum(n);
  NumericVector vAvg(n);

  // for each xy determine neighborhood Sum and count (N)
  for(int i=0; i<n; i++) {
    vN[i] = 0.0;
    vSum[i] = 0.0;

    // traverse neighborhood, if the xy exists in the input
    // vector then accumulate the values, otherwise ignore

    for(int dx=-1*radius; dx<=radius; dx++) {
      for(int dy=-1*radius; dy<=radius; dy++) {

        // construct an xy index for the neighborhood die
        xy[0] = ( (X[i]+dx) * 10000 ) + (Y[i]+dy);

        // check to see if index above exists in input set
        IntegerVector m = Rcpp::match(xy, XY);

        // if valid then accumulate and count
        if(m[0] != NA_INTEGER) {
          vN[i] = vN[i] + 1.0;
          vSum[i] = vSum[i] + P[ m[0] ];
        }
      }
    }

    vAvg[i] = vSum[i] / vN[i];
  }

  return vAvg;
}

/*** R
cat("Built\n")
*/

Вывод

Поскольку у нас нет справочных данных, я могу только показать, что он построен:

R> sourceCpp("~/git/stackoverflow/61377960/answer.cpp")

R> cat("Built\n")
Built
R> 
...