How to use log_sum_exp in C++ without stan::math::var?

I am trying to use the log_sum_exp function in my Rcpp function, but cannot compile the .cpp file using sourceCpp unless I use the stan::math::var type. Example .cpp file as follows:

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


#include <Rcpp.h>
#include <stan/math.hpp>

using namespace Rcpp;

// [[Rcpp::export]]
double tmp_fn_log_sum_exp_bug(
        NumericVector tmp_vector) {
    
    
    // does not compile
    // return log_sum_exp(tmp_vector);
    
    
    // // compiles
    std::vector<stan::math::var> tmp_vector_(tmp_vector.size());
    
    for (int i = 0; i < tmp_vector.size(); i++) {
     
     
     tmp_vector_[i] = tmp_vector[i];
        
    }
    
    return value_of(log_sum_exp(tmp_vector_));
    
    
    
}

I am a stan and c++ newbie, so apologies if I have missed anything.

1 Like

In the math library, the non-variable version log_sum_exp is defined for std::vector<double> which is a different type from NumericVector (see stdvector - Convert R::vector to std::vector - Stack Overflow for instructions to convert).

Additionally, I think you need to qualify the log_sum_exp with the stan::math namespace (i.e. use stan::math::log_sum_exp). You don’t need to this when passing stan::math::var as the parameter as C++ will “magically” look for the function also in the same namespace as the parameters are defined.

(I can’t currently test the code locally, so hope this would make it work).

Best of luck!

1 Like

Can you try it with an Eigen vector? That should work as well

1 Like

Thank you, I would have never got it without you: I had been trying my best to assign outputs to the right type, and may have eventually hit on the fact that I was passing in the wrong type, but I would never have worked out that you needed to preface the namespace. For the record, both

    std::vector<double> tmp_vector_ = Rcpp::as<std::vector<double> >(tmp_vector);


    return stan::math::log_sum_exp(tmp_vector_);

and

    std::vector<double> tmp_vector_(tmp_vector.size());


    for (int i = 0; i < tmp_vector.size(); i++) {




        tmp_vector_[i] = tmp_vector[i];

    }

    return stan::math::log_sum_exp(tmp_vector_);

compile.

Sorry I do not know what Eigen vectors are, or I would attempt them.