1

I use RcppNumerical for optimization and I need some variables declared in f_grad function after the optimization is completed.

To explain my question, let's take the standard example in RcppNumerical package. First of all, we need to create a class.

// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppNumerical)]]

#include <RcppNumerical.h>

using namespace Numer;

// f = 100 * (x2 - x1^2)^2 + (1 - x1)^2
// True minimum: x1 = x2 = 1
class Rosenbrock: public MFuncGrad
{
public:
double f_grad(Constvec& x, Refvec grad)
    {
     double t1 = x[1] - x[0] * x[0];
     double t2 = 1 - x[0];
     grad[0] = -400 * x[0] * t1 - 2 * t2;
     grad[1] = 200 * t1;
     return 100 * t1 * t1 + t2 * t2;
    }
};

The following code is then used for optimization.

// [[Rcpp::export]]
Rcpp::List optim_test()
{
    Eigen::VectorXd x(2);
    x[0] = -1.2;
    x[1] = 1;
    double fopt;
    Rosenbrock f;
    int res = optim_lbfgs(f, x, fopt);
    return Rcpp::List::create(
        Rcpp::Named("xopt") = x,
        Rcpp::Named("fopt") = fopt,
        Rcpp::Named("status") = res
    );
}

How can I get access to t1 or t2 value after the optimization is completed. I want to mean to value of these variables for the optimization solution.

My example may not be very good for what I am looking for because it is easy to calculate t1 ort2 outside the optimization of this example. In my case, I need some variables that are computationally cumbersome. So, if they are already calculated during optimization, why not return them (or have access to their values) after optimization without having to calculate them again outside the optimization?

1 Answer 1

1

You could use member variables for the variables of interest. For simplicity I am using public members here:

// [[Rcpp::depends(RcppEigen)]]
// [[Rcpp::depends(RcppNumerical)]]

#include <RcppNumerical.h>

using namespace Numer;

// f = 100 * (x2 - x1^2)^2 + (1 - x1)^2
// True minimum: x1 = x2 = 1
class Rosenbrock: public MFuncGrad
{
public:
  double t1;
  double t2;

  double f_grad(Constvec& x, Refvec grad)
  {
    t1 = x[1] - x[0] * x[0];
    t2 = 1 - x[0];
    grad[0] = -400 * x[0] * t1 - 2 * t2;
    grad[1] = 200 * t1;
    return 100 * t1 * t1 + t2 * t2;
  }
};

// [[Rcpp::export]]
Rcpp::List optim_test()
{
  Eigen::VectorXd x(2);
  x[0] = -1.2;
  x[1] = 1;
  double fopt;
  Rosenbrock f;
  int res = optim_lbfgs(f, x, fopt);
  return Rcpp::List::create(
    Rcpp::Named("xopt") = x,
    Rcpp::Named("fopt") = fopt,
    Rcpp::Named("status") = res,
    Rcpp::Named("t1") = f.t1,
    Rcpp::Named("t2") = f.t2
  );
}

/*** R
optim_test()
*/

Result:

> optim_test()
$xopt
[1] 1 1

$fopt
[1] 3.12499e-15

$status
[1] 0

$t1
[1] -2.849634e-09

$t2
[1] -4.809313e-08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.