solvers/callback.py

This example demonstrates how to use callback function for Ipopt.

View output (PDF) | source (python)

See also
Function object.
Definition: function.hpp:60
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 from casadi import *
28 from numpy import *
29 
30 
31 
32 
33 
34 
35 x=SX.sym("x")
36 y=SX.sym("y")
37 
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])
41 
42 import matplotlib
43 if "Agg" not in matplotlib.get_backend():
44  matplotlib.interactive(True)
45 
46 from pylab import figure, subplot, contourf, colorbar, draw, show, plot, title
47 
48 import time
49 
50 class MyCallback(Callback):
51  def __init__(self, name, nx, ng, np, opts={}):
52  Callback.__init__(self)
53 
54  self.nx = nx
55  self.ng = ng
56  self.np = np
57 
58  figure(1)
59 
60  x_,y_ = mgrid[-1:1.5:0.01,-1:1.5:0.01]
61  z_ = DM.zeros(x_.shape)
62 
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])
66  contourf(x_,y_,z_)
67  colorbar()
68  title('Iterations of Rosenbrock')
69  draw()
70 
71  self.x_sols = []
72  self.y_sols = []
73 
74 
75  self.construct(name, opts)
76 
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"
81 
82  def get_sparsity_in(self, i):
83  n = nlpsol_out(i)
84  if n=='f':
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)
90  else:
91  return Sparsity(0,0)
92  def eval(self, arg):
93 
94  darg = {}
95  for (i,s) in enumerate(nlpsol_out()): darg[s] = arg[i]
96 
97  sol = darg['x']
98  self.x_sols.append(float(sol[0]))
99  self.y_sols.append(float(sol[1]))
100 
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)
104 
105  else:
106  self.lines = plot(self.x_sols,self.y_sols,'or-')
107 
108  draw()
109  time.sleep(0.25)
110 
111  return [0]
112 
113 mycallback = MyCallback('mycallback', 2, 1, 0)
114 opts = {}
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)
120 
121 
122 
123 matplotlib.interactive(False)
124 show()
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.