Skip to content

Instantly share code, notes, and snippets.

@jgillis
Created May 7, 2020 19:50
Show Gist options
  • Save jgillis/595106deade2163e83172b168d240fb7 to your computer and use it in GitHub Desktop.
Save jgillis/595106deade2163e83172b168d240fb7 to your computer and use it in GitHub Desktop.
Custom stopping criterion
from casadi import *
x=SX.sym("x")
y=SX.sym("y")
f = (1-x)**2+100*(y-x**2)**2
nlp={'x':vertcat(x,y), 'f':f,'g':x+y}
fcn = Function('f', [x, y], [f])
callback_inputs = dict()
for i, label in enumerate(nlpsol_out()):
callback_inputs[label] = i
class MyCallback(Callback):
def __init__(self,nx, ng, np):
Callback.__init__(self)
self.nx = nx
self.ng = ng
self.np = np
self.construct("mycallback", {})
def get_n_in(self): return nlpsol_n_out()
def get_n_out(self): return 1
def get_sparsity_in(self, i):
n = nlpsol_out(i)
if n=='f':
return Sparsity. scalar()
elif n in ('x', 'lam_x'):
return Sparsity.dense(self.nx)
elif n in ('g', 'lam_g'):
return Sparsity.dense(self.ng)
else:
return Sparsity(0,0)
def eval(self, arg):
objective = arg[callback_inputs["f"]]
if objective<1e-4:
# end optimization
return [1]
else:
return [0]
mycallback = MyCallback(2,1,0)
opts = {}
opts['iteration_callback'] = mycallback
solver = nlpsol('solver', 'ipopt', nlp, opts)
sol = solver(lbx=-10, ubx=10, lbg=-10, ubg=10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment