Using external function in nlpsol codegen #3674
-
Hi, from casadi import *
x = MX.sym('x', 2)
slack = MX.sym('slack')
radius = MX.sym('radius')
J = x[0] + x[1]
obj_function = Function('objective', [x], [J])
obj_function.generate('J.c')
external_obj_function = external('objective', 'J.so', {'enable_fd': True})
J = external_obj_function(x)
g = x[0]**2 + x[1]**2 - radius + slack
prob = {'f': J, 'x': vertcat(x, slack), 'g': g, 'p': radius}
solver = nlpsol('solver', 'ipopt', prob, {'ipopt.print_level': 5})
solver.generate_dependencies('nlp.c')
res = solver(lbg = 0, ubg = 0, lbx = [-inf, -inf, 0], ubx = [inf, inf, inf], p = [4])
print(res) The objective function code generates and builds without issues but I get compiler errors when trying to compile the generated nlp.c file even though the optimization problem runs fine inside the python example:
I could also manually code the derivatives but I am not sure what functions are needed to do this. In my project I need to have part of the objective function as an external function. I assume I need atleast the jacobian and hessian but not sure about the naming conventions for that. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I don't know exactly what's up with the first errors, but the last one has happened to me and is reproducible as such (3.6.5):
Comment one of the fun_map_MX to check it out. I've had this problem in the above case and also in a similar case as OP's. Quick fix hack is to use this (works in my code, IDK if there's other edge cases):
Also don't forget to link the external function to the final nlp.so. In any case:
Here's your code working + defining and loading external derivative information. Import thing is to name properly (jac_functionname for jacobian, jac_jac_functionname for the jacobian of the jacobian) and have the correct inputs and outputs. I don't remember if there's an easier way to load the NLP as an external function, but this works. |
Beta Was this translation helpful? Give feedback.
I don't know exactly what's up with the first errors, but the last one has happened to me and is reproducible as such (3.6.5):