This example demonstrates how to use callback function for Ipopt.
38 f = (1-x)**2+100*(y-x**2)**2
39 nlp={
'x':vertcat(x,y),
'f':f,
'g':x+y}
40 fcn = Function(
'f', [x, y], [f])
43 if "Agg" not in matplotlib.get_backend():
44 matplotlib.interactive(
True)
46 from pylab
import figure, subplot, contourf, colorbar, draw, show, plot, title
50 class MyCallback(Callback):
51 def __init__(self, name, nx, ng, np, opts={}):
52 Callback.__init__(self)
60 x_,y_ = mgrid[-1:1.5:0.01,-1:1.5:0.01]
61 z_ = DM.zeros(x_.shape)
63 for i
in range(x_.shape[0]):
64 for j
in range(x_.shape[1]):
65 z_[i,j] = fcn(x_[i,j],y_[i,j])
68 title(
'Iterations of Rosenbrock')
75 self.construct(name, opts)
77 def get_n_in(self):
return nlpsol_n_out()
78 def get_n_out(self):
return 1
79 def get_name_in(self, i):
return nlpsol_out(i)
80 def get_name_out(self, i):
return "ret"
82 def get_sparsity_in(self, i):
85 return Sparsity. scalar()
86 elif n
in (
'x',
'lam_x'):
87 return Sparsity.dense(self.nx)
88 elif n
in (
'g',
'lam_g'):
89 return Sparsity.dense(self.ng)
95 for (i,s)
in enumerate(
nlpsol_out()): darg[s] = arg[i]
98 self.x_sols.append(float(sol[0]))
99 self.y_sols.append(float(sol[1]))
101 if hasattr(self,
'lines'):
102 if "template" not in matplotlib.get_backend():
103 self.lines[0].set_data(self.x_sols,self.y_sols)
106 self.lines = plot(self.x_sols,self.y_sols,
'or-')
113 mycallback = MyCallback(
'mycallback', 2, 1, 0)
115 opts[
'iteration_callback'] = mycallback
116 opts[
'ipopt.tol'] = 1e-8
117 opts[
'ipopt.max_iter'] = 50
118 solver =
nlpsol(
'solver',
'ipopt', nlp, opts)
119 sol = solver(lbx=-10, ubx=10, lbg=-10, ubg=10)
123 matplotlib.interactive(
False)
CASADI_EXPORT Function nlpsol(const std::string &name, const std::string &solver, const SXDict &nlp, const Dict &opts=Dict())
CASADI_EXPORT std::vector< std::string > nlpsol_out()
Get NLP solver output scheme of NLP solvers.