0

Trying to solve a computer vision problem, I have to minimize a nonlinear energy function, implementing it in C++. Although I didn't find a library to help me with the specific function, I have the math for it. So what's the best way to go from symbolic math to C++ code?

Example: given the functions g(x):=x^2 and f(x):=x+2, let's imagine I am interested in converting f(g(x)) to C code; the obvious C code would be y=x^2+2; however for complicated math including jacobians, etc, it is not so easy, translating to pages and pages of operations.

I tried already Matlab and it's conversion module to C code, but the code is far from being optimized (ex: same operations repeating many times instead of reusing the result).

cDc
  • 317
  • 3
  • 9

1 Answers1

2

there exists NLopt library callable from C++, C, Matlab, Fortran, (...) for nonlinear optimizations. The implementation of minimization procedure using this library might look like this:

#include <nlopt.hpp>

nlopt::opt opt(nlopt::LD_MMA, 2);

std::vector<double> lb(2);
lb[0] = -HUGE_VAL; lb[1] = 0;
opt.set_lower_bounds(lb);

opt.set_min_objective(myfunc, NULL);

my_constraint_data data[2] = { {2,0}, {-1,1} };
opt.add_inequality_constraint(myconstraint, &data[0], 1e-8);
opt.add_inequality_constraint(myconstraint, &data[1], 1e-8);

opt.set_xtol_rel(1e-4);

std::vector<double> x(2);
x[0] = 1.234; x[1] = 5.678;
double minf;
nlopt::result result = opt.optimize(x, minf);
4pie0
  • 29,204
  • 9
  • 82
  • 118
  • That is a very interesting library, I will consider it, but it is not an answer to my question. How to convert simbolic math (ex: f(x)=x+2) to C code (for our ex it is obvious y=x+2; is the C code I needed, but for complicated math including jacobians, etc, it is not so easy)... – cDc Nov 22 '13 at 12:37
  • your question is unclear, NLopt allowas you for any (of course to some extent) math, look into it - you will find all answers. How to implement Jacobian? It is ordinary matrix , just a matrix (of partial dervatives) – 4pie0 Nov 22 '13 at 13:23
  • I'm sorry if it is still unclear, I do not know how to make it more clear. Here is one more ex of a "small" function in Maxima for which the jacobian expression fills several pages of display: X:[x0,x1,x2]$ R:[r0,r1,r2]$ C:[c0,c1,c2]$ p:[p0,p1]$ theta2:R.R$ theta:sqrt(theta2)$ ct:cos(theta)$ st:sin(theta)$ w:R/theta$ P:X-C$ cr:w~P$ dt:w.P$ ptC:express(P*ct+cr*st+w*(1-ct)*dt)$ pt:[f*ptC[1]/ptC[3], f*ptC[2]/ptC[3]]-p$ j:jacobian([pt],[R[1],R[2],R[3],C[1],C[2],C[3],f])$ – cDc Nov 22 '13 at 14:22
  • I'd be happy to discuss this in more details in private if you can (my email is in the profile), thx! – cDc Nov 22 '13 at 14:28