Skip to content

Instantly share code, notes, and snippets.

@jaeandersson
Created January 22, 2014 09:22
Show Gist options
  • Save jaeandersson/8555820 to your computer and use it in GitHub Desktop.
Save jaeandersson/8555820 to your computer and use it in GitHub Desktop.
Get diagonal entries of the Hessian in CasADi
#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