# Minimization¶

Author: Omar Zapata
This notebook tutorial was automatically generated with ROOTBOOK-izer from the macro found in the ROOT repository on Sunday, September 19, 2021 at 08:24 AM.

In [ ]:
%%cpp -d
#include<TRInterface.h>


in the next function the *double pointer must be changed by a TVectorD, because the pointer has no meaning in R enviroment.

In [ ]:
%%cpp -d
Double_t RosenBrock(const TVectorD xx )
{
const Double_t x = xx;
const Double_t y = xx;
const Double_t tmp1 = y-x*x;
const Double_t tmp2 = 1-x;
return 100*tmp1*tmp1+tmp2*tmp2;
}


A helper function is created:

In [ ]:
%%cpp -d
{
const Double_t x = xx;
const Double_t y = xx;
grad=-400 * x * (y - x * x) - 2 * (1 - x);
grad=200 * (y - x * x);
}

In [ ]:
ROOT::R::TRInterface &r=ROOT::R::TRInterface::Instance();


Passsing rosenbrock function to r

In [ ]:
r["RosenBrock"]=ROOT::R::TRFunctionExport(RosenBrock);


In [ ]:
r["RosenBrockGrad"]=ROOT::R::TRFunctionExport(RosenBrockGrad);


The option "method" could be "nelder-mead", "bfgs", "cg", "l-bfgs-b", "sann","brent"

The option "control" lets you put some constraints like "maxit" The maximum number of iterations. "abstol" The absolute convergence tolerance.

In [ ]:
r.Execute("result <- optim( c(0.01,0.01), RosenBrock,method='BFGS',control = list(maxit = 1000000) )");


"reltol" relative convergence tolerance.

Getting results from r

In [ ]:
TVectorD  min=r.Eval("result$par"); std::cout.precision(8);  Printing results In [ ]: std::cout<<"-----------------------------------------"<<std::endl; std::cout<<"Minimum x="<<min<<" y="<<min<<std::endl; std::cout<<"Value at minimum ="<<RosenBrock(min)<<std::endl;  Using the gradient In [ ]: r.Execute("optimHess(result$par, RosenBrock, RosenBrockGrad)");
r.Execute("hresult <- optim(c(-1.2,1), RosenBrock, NULL, method = 'BFGS', hessian = TRUE)");


Getting the min calculated with the gradient

In [ ]:
TVectorD  hmin=r.Eval("hresult\$par");


Printing results

In [ ]:
std::cout<<"-----------------------------------------"<<std::endl;