Skip to content

Instantly share code, notes, and snippets.

@stephenjbarr
Created August 30, 2012 05:36
Show Gist options
  • Save stephenjbarr/3522857 to your computer and use it in GitHub Desktop.
Save stephenjbarr/3522857 to your computer and use it in GitHub Desktop.
an example of using R's optim to optimize a C++ function exposed via Rcpp::InternalFunction
// -*- mode: C++; c-indent-level: 4; c-basic-offset: 4; tab-width: 8; -*-
//
// Simple example showing how expose a C++ function
//
// Copyright (C) 2010 Dirk Eddelbuettel and Romain Francois
#include <RInside.h> // for the embedded R via RInside
// a c++ function we wish to expose to R
const char* hello( std::string who ){
std::string result( "hello " ) ;
result += who ;
return result.c_str() ;
}
const double doubler( double input ){
return 2.0 * input;
}
//const double ary_sum( double *input[] ){
const double ary_sum( const Rcpp::NumericVector & input ){
double asum = 0.0;
for(int i = 0; i < 3; i++) {
asum += input[i];
}
return asum;
}
//const double ary_sum( double *input[] ){
const double my_objective_fn( const Rcpp::NumericVector & input ){
double asum = 0.0;
asum = ((input[0] - 3.0)*(input[0] - 3.0)) +
((input[1] - 5.5)*(input[1] - 5.5));
return asum;
}
int main(int argc, char *argv[]) {
// create an embedded R instance
RInside R(argc, argv);
// expose the "hello" function in the global environment
R["hello"] = Rcpp::InternalFunction( &hello ) ;
R["doubler"] = Rcpp::InternalFunction( &doubler );
R["ary_sum"] = Rcpp::InternalFunction( &ary_sum );
R["my_objective_fn"] = Rcpp::InternalFunction( &my_objective_fn );
// call it and display the result
std::string result = R.parseEval("hello('world')") ;
std::cout << "hello( 'world') = " << result << std::endl ;
double ans = R.parseEval("doubler(3.0)");
std::cout << "doubler(3.0) = " << ans << std::endl ;
ans = R.parseEval("ary_sum(c(3.0, 4.5, 2.1))");
std::cout << "ary_sum(c(3.0, 4.5, 2.1)) = " << ans << std::endl ;
ans = 0.0;
ans = R.parseEval("my_objective_fn(c(1.0, 2.0))");
std::cout << "my_objective_fn(c(1.0, 2.0)) = " << ans << std::endl ;
Rcpp::List x = R.parseEval("optim(c(.2,.8), my_objective_fn)");
Rcpp::NumericVector optimum_point = Rcpp::as<Rcpp::NumericVector>(x[0]);
std::cout << "OPT.0: " << optimum_point(0) << std::endl;
std::cout << "OPT.1: " << optimum_point(1) << std::endl;
exit(0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment