Rcpp_eval causes segfault when passing unevaluated arguments - r

I want to evaluate variable inside Rcpp function
SEXP foo(SEXP arg) {
SEXP x = NULL;
try {
x = Rcpp_eval(arg, Environment::global_env());
} catch(...) {
printf("Error\n");
}
return x;
}
If arg is initialized in .GlobalEnv it seems fine.
x <- 1
foo(substitute(x))
But if arg is not initialized in .GlobalEnv segfault occurs
foo(substitute(y))
What am I doing wrong? Or it's a problem in Rcpp?

Set x to R_NilValue to return R's NULL on error, rather than a NULL pointer. Presumably you don't want to use printf() to handle the error. I guess you meant
x = Rcpp_eval(arg, Environment::global_env());
(arg rather than mode).
SEXP foo(SEXP arg) {
SEXP x = R_NilValue;
try {
x = Rcpp_eval(arg, Environment::global_env());
} catch(...) {
printf("Error\n");
}
return x;
}

Related

Need help recursion explanation Leetcode

How does this code work? (leetcode 95 question) I don't understand how the 2 recursions work inside the for loop. Does the 2nd inner for loop end when the recursive function returns NULL? Or would it continue executing the 3rd inner for loop?
class Solution {
public:
vector<TreeNode*> generateTrees(int n) {
if(n == 0) {
return {};
}
vector<TreeNode*> ans = generateT(1,n);
return ans;
}
vector<TreeNode*> generateT(int l, int r) {
if(l > r) return {nullptr};
vector<TreeNode*> ans;
for(int i=l; i <= r; ++i) {
for(TreeNode*left: generateT(l, i-1)) {
for(TreeNode* right:generateT(i+1, r)) {
ans.push_back(new TreeNode(i));
ans.back()->left = left;
ans.back()->right = right;
}
}
}
return ans;
}
};
Problem statement:
Given an integer n, return all the structurally unique BST's (binary search trees), which has exactly n nodes of unique values from 1 to n. Return the answer in any order.
Does the 2nd inner for loop end when the recursive function returns NULL?
No. The recursive function is not returing NULL, it is returning vector of nullptr.
Or would it continue executing the 3rd inner for loop?
Of course, it will.
How does this code work? I don't understand how the 2 recursions work inside the loop.
I suppose the following snippet is the cause of confusion, so commented the case when nullptr provided by outer loop.
vector<TreeNode*> generateT(int l, int r) {
if(l > r) return { nullptr };
vector<TreeNode*> ans;
for ( int i = l; i <= r; i++ ) {
// if l = 0, i = 0
for ( TreeNode* left :generateT(l, i-1) ) // if l = 0, i = -1, returns { nullptr } (vector of nullptr)
for (TreeNode* right :generateT(i+1, r)) { // now this snippet will execute
auto node = new TreeNode(i);
ans.push_back(node);
node->left = left; // the nullptr we have from the outer loop, will provide null value for this
node->right = right;
}
}
return ans;
}
Visually, for a combination of node where,
a
\
b
/ \
null c
/
null
the above pattern occurs the provided { nullptr } from outer loop will come in handy setting left node.

Rcpp template class for custom input and output

I'm trying to create C++ function which will apply any funtion on R vector of any type. I've been reading and searching for an answer but my knowledge is still too chaotic and I can't put everything together. I was inspired by sapply example and some from Rcpp gallery but it's to advanced so far.
What I've already done is simple class which kinda-works, but I'm having problem even with this one. Error happens when I'm trying to call function which returns something else than numeric. However I don't know how to extend function to work with custom output type.
At this point, I don't know how:
Obtain type of R Function return value and use this type do define out - same size as x
Alternatively - use std::string type argument in apply_fun which could switch OUTTYPE
Pass any x to the class and use in f - I think I've managed this correctly with <int XTYPE>
Perhaps answer to this question might be to complex so I appreciate all hints. Below I present current progress. Thanks!
Rcpp class
#include <Rcpp.h>
namespace apply {
template <int XTYPE>
class SomeClass {
private:
Rcpp::Vector<XTYPE> x;
Rcpp::Function f;
public:
Rcpp::Vector<XTYPE> run() {
typedef typename Rcpp::traits::storage_type<XTYPE>::type STORAGE;
int n = x.size();
Rcpp::Vector<XTYPE> out(n);
for (unsigned int i{0}; i < n; i++) {
out(i) = Rcpp::as<STORAGE>(f(x(i)));
// Rcpp::Rcout << out(i) << std::endl;
}
return out;
}
SomeClass (Rcpp::Vector<XTYPE> x, Rcpp::Function f)
: x{x}, f{f} {
std::cout << "Initialized SomeClass" << std::endl;
}
};
}
Exported Rcpp function
//' #export
//[[Rcpp::export]]
Rcpp::RObject apply_fun(Rcpp::RObject x,
Rcpp::Function f) {
if (TYPEOF(x) == INTSXP) {
apply::SomeClass<13> r{Rcpp::as<Rcpp::IntegerVector>(x), f};
return r.run();
} else if (TYPEOF(x) == REALSXP) {
apply::SomeClass<14> r{Rcpp::as<Rcpp::NumericVector>(x), f};
return r.run();
} else if (TYPEOF(x) == STRSXP) {
apply::SomeClass<16> r{Rcpp::as<Rcpp::CharacterVector>(x), f};
return r.run();
} else if (TYPEOF(x) == LGLSXP) {
apply::SomeClass<10> r{Rcpp::as<Rcpp::LogicalVector>(x), f};
return r.run();
} else if (TYPEOF(x) == CPLXSXP) {
apply::SomeClass<15> r{Rcpp::as<Rcpp::ComplexVector>(x), f};
return r.run();
} else {
Rcpp::stop("Invalid data type - only integer, numeric, character, factor, date, logical, complex vectors are possible.");
}
return R_NilValue;
}
R calls
apply_fun(c(1.5, 2.5, 3.5), f = function(x) { x + 10})
# 11.5 12.5 13.5
apply_fun(letters[1:3], f = function(x) paste(x, "-"))
# Error in apply_run(letters[1:3], f = function(x) x) :
# Evaluation error: unimplemented type 'char' in 'eval'

QtConcurrent::map segmentation fault

When I have been trying to implement "parallel for" using QtConcurrent::map:
QFuture<void> parForAsync(size_t n, std::function<void (size_t)> Op)
{
size_t nThreads =
static_cast<size_t>(QThreadPool::globalInstance()->maxThreadCount());
size_t nn = n/nThreads + 1;
using Sequence = QVector<std::function<void()>>;
Sequence vFuns;
for(size_t i = 0; i < n; i+=nn)
{
size_t firstIdx = i,
lastIdx = i + nn > n ? n : i + nn;
vFuns.push_back([=]()->void
{
for(size_t i = firstIdx; i < lastIdx; ++i)
{
Op(i);
}
});
}
return QtConcurrent::map<Sequence> //<-Segmentation fault!
(vFuns, [](std::function<void()> f)
{
f();
});
}
I've got segmentation fault in this place:
template<typename _Res, typename... _ArgTypes>
function<_Res(_ArgTypes...)>::
function(const function& __x)
: _Function_base()
{
if (static_cast<bool>(__x))
{
__x._M_manager(_M_functor, __x._M_functor, __clone_functor); //<-Segmentation fault!
_M_invoker = __x._M_invoker;
_M_manager = __x._M_manager;
}
}
Why is this happening? It seems that std::function had passed checking. How can I make this code working?
Thanks in advance!
I cannot reproduce your case but I can give you some example to illustrate issue
QFuture<void> test ()
{
QVector<int> v; // LOCAL VARIABLE IN SCOPE OF test FUNCTION
// preparing v vector
QFuture<void> f = QtConcurrent::map(v,someFunction); // returns immediately
return f;
}
[1] QtConcurrent::map takes v by reference NOT BY COPY.
[2] QtConcurrent::map returns immediately.
[3] So when test function ends, parallel operations started by map use v vector which was deleted because it is local variable in test function.
You can use waitForFinished for QFuture but then your function doesn't make sense because it blocks until parallel task ends.

How to access elements of a vector in a Rcpp::List

I am puzzled.
The following compile and work fine:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
List test(){
List l;
IntegerVector v(5, NA_INTEGER);
l.push_back(v);
return l;
}
In R:
R) test()
[[1]]
[1] NA NA NA NA NA
But when I try to set the IntegerVector in the list:
// [[Rcpp::export]]
List test(){
List l;
IntegerVector v(5, NA_INTEGER);
l.push_back(v);
l[0][1] = 1;
return l;
}
It does not compile:
test.cpp:121:8: error: invalid use of incomplete type 'struct SEXPREC'
C:/PROGRA~1/R/R-30~1.0/include/Rinternals.h:393:16: error: forward declaration of 'struct SEXPREC'
It is because of this line:
l[0][1] = 1;
The compiler has no idea that l is a list of integer vectors. In essence l[0] gives you a SEXP (the generic type for all R objects), and SEXP is an opaque pointer to SEXPREC of which we don't have access to te definition (hence opaque). So when you do the [1], you attempt to get the second SEXPREC and so the opacity makes it impossible, and it is not what you wanted anyway.
You have to be specific that you are extracting an IntegerVector, so you can do something like this:
as<IntegerVector>(l[0])[1] = 1;
or
v[1] = 1 ;
or
IntegerVector x = l[0] ; x[1] = 1 ;
All of these options work on the same underlying data structure.
Alternatively, if you really wanted the syntax l[0][1] you could define your own data structure expressing "list of integer vectors". Here is a sketch:
template <class T>
class ListOf {
public:
ListOf( List data_) : data(data_){}
T operator[](int i){
return as<T>( data[i] ) ;
}
operator List(){ return data ; }
private:
List data ;
} ;
Which you can use, e.g. like this:
// [[Rcpp::export]]
List test2(){
ListOf<IntegerVector> l = List::create( IntegerVector(5, NA_INTEGER) ) ;
l[0][1] = 1 ;
return l;
}
Also note that using .push_back on Rcpp vectors (including lists) requires a complete copy of the list data, which can cause slow you down. Only use resizing functions when you don't have a choice.

R: Question about Optimizing - Invalid Function Value in Optimize

We have not been able to pinpoint what is causing the error of Invalid Function Value in Optimize in our Optimizing code. If you could offer any insight, it would be appreciated.
H_fun <- function(c)
{
val = -current_c_weight*c - X_counts%*%log(
exp(rep(c,length(current_Theta))*current_Theta) -
current_elongation_rates )
print('#########iteration display#############')
print('c')
print(c)
print('val')
print(val)
print('current_c_weight')
print(current_c_weight)
print('current_Theta')
print(current_Theta)
print('current_elongation_rates')
print(current_elongation_rates)
}
#...snip...
# minimize -H(c) without the non-negativity constraint
#tmp = optim(c(0,1),H_fun,NULL, method = "BFGS", hessian = TRUE);
tmp = optimize(H_fun,interval = c(0,1));
Here is a link to the code:
http://www.text-upload.com/read.php?id=102950&c=8605046
Are you sure H_fun is returning a one-dimensional value?
Look at fcn1() in the R optimize() source code:
static double fcn1(double x, struct callinfo *info)
{
SEXP s;
REAL(CADR(info->R_fcall))[0] = x;
s = eval(info->R_fcall, info->R_env);
switch(TYPEOF(s)) {
case INTSXP:
if (length(s) != 1) goto badvalue;
if (INTEGER(s)[0] == NA_INTEGER) {
warning(_("NA replaced by maximum positive value"));
return DBL_MAX;
}
else return INTEGER(s)[0];
break;
case REALSXP:
if (length(s) != 1) goto badvalue;
if (!R_FINITE(REAL(s)[0])) {
warning(_("NA/Inf replaced by maximum positive value"));
return DBL_MAX;
}
else return REAL(s)[0];
break;
default:
goto badvalue;
}
badvalue:
error(_("invalid function value in 'optimize'"));
return 0;/* for -Wall */
}
goto badvalue occurs if length is not 1. Also, the package summary states that optimize() works on a one-dimensional unconstrained function.

Resources