Created
January 22, 2014 09:22
-
-
Save jaeandersson/8555820 to your computer and use it in GitHub Desktop.
Get diagonal entries of the Hessian in CasADi
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <fstream> | |
#include <ctime> | |
#include <iomanip> | |
#include <symbolic/casadi.hpp> | |
#include <symbolic/stl_vector_tools.hpp> | |
using namespace CasADi; | |
using namespace std; | |
void generateCode(FX fcn, const std::string& name){ | |
cout << "Generating code for " << name << endl; | |
// Generate C code | |
fcn.generateCode(name + ".c"); | |
} | |
int main(){ | |
// Optimization variables | |
SXMatrix x = ssym("x",3); | |
// Objective | |
SXMatrix f = x[0]*x[0] + x[1]*x[1] + x[0]*x[1]*x[2]; | |
cout << "f = " << f << endl; | |
// Gradient of the objective | |
SXMatrix grad_f = gradient(f,x); | |
cout << "grad_f = " << endl; | |
grad_f.printDense(); | |
// Hessian of the objective | |
SXMatrix hess_f = hessian(f,x); | |
cout << "hess_f = " << endl; | |
hess_f.printDense(); | |
// Remove off-diagonal entries | |
SXMatrix diag_hess_f = diag(diag(hess_f)); | |
cout << "diag_hess_f = " << endl; | |
diag_hess_f.printDense(); | |
// Create functions | |
SXFunction f_fcn(x,f); | |
f_fcn.init(); | |
SXFunction grad_f_fcn(x,grad_f); | |
grad_f_fcn.init(); | |
SXFunction hess_f_fcn(x,hess_f); | |
hess_f_fcn.init(); | |
// Generate code | |
generateCode(f_fcn,"nlp"); | |
generateCode(grad_f_fcn,"grad_f"); | |
generateCode(hess_f_fcn,"hess_f"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment