chiark / gitweb /
recommend building in a subdir
[nlopt.git] / src / octave / nlopt_optimize-oct.cc
1 /* Copyright (c) 2007-2014 Massachusetts Institute of Technology
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining
4  * a copy of this software and associated documentation files (the
5  * "Software"), to deal in the Software without restriction, including
6  * without limitation the rights to use, copy, modify, merge, publish,
7  * distribute, sublicense, and/or sell copies of the Software, and to
8  * permit persons to whom the Software is furnished to do so, subject to
9  * the following conditions:
10  * 
11  * The above copyright notice and this permission notice shall be
12  * included in all copies or substantial portions of the Software.
13  * 
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
18  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
19  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 
21  */
22
23 #include <octave/oct.h>
24 #include <octave/oct-map.h>
25 #include <octave/ov.h>
26 #include <math.h>
27 #include <stdio.h>
28
29 #include "nlopt.h"
30 #include "nlopt_optimize_usage.h"
31
32 #include <octave/version.h>
33 #if OCTAVE_MAJOR_VERSION < 3 || (OCTAVE_MAJOR_VERSION == 3 && OCTAVE_MINOR_VERSION < 8)
34 #  define octave_map Octave_map
35 #endif
36
37 static int struct_val_default(octave_map &m, const std::string& k,
38                                  int dflt)
39 {
40   if (m.contains(k)) {
41     if (m.contents(k).length() == 1 && (m.contents(k))(0).is_real_scalar())
42       return (m.contents(k))(0).int_value();
43   }
44   return dflt;
45 }
46
47 static double struct_val_default(octave_map &m, const std::string& k,
48                                  double dflt)
49 {
50   if (m.contains(k)) {
51     if (m.contents(k).length() == 1 && (m.contents(k))(0).is_real_scalar())
52       return (m.contents(k))(0).double_value();
53   }
54   return dflt;
55 }
56
57 static Matrix struct_val_default(octave_map &m, const std::string& k,
58                                  Matrix &dflt)
59 {
60   if (m.contains(k)) {
61     if ((m.contents(k)).length() == 1) {
62       if ((m.contents(k))(0).is_real_scalar())
63         return Matrix(1, dflt.length(), (m.contents(k))(0).double_value());
64       else if ((m.contents(k))(0).is_real_matrix())
65         return (m.contents(k))(0).matrix_value();
66     }
67   }
68   return dflt;
69 }
70
71 typedef struct {
72   octave_function *f;
73   int neval, verbose;
74   nlopt_opt opt;
75 } user_function_data;
76
77 static double user_function(unsigned n, const double *x,
78                             double *gradient, /* NULL if not needed */
79                             void *data_)
80 {
81   user_function_data *data = (user_function_data *) data_;
82   octave_value_list args(1, 0);
83   Matrix xm(1,n);
84   for (unsigned i = 0; i < n; ++i)
85     xm(i) = x[i];
86   args(0) = xm;
87   octave_value_list res = data->f->do_multi_index_op(gradient ? 2 : 1, args); 
88   if (res.length() < (gradient ? 2 : 1))
89     gripe_user_supplied_eval("nlopt_optimize");
90   else if (!res(0).is_real_scalar()
91            || (gradient && !res(1).is_real_matrix()
92                && !(n == 1 && res(1).is_real_scalar())))
93     gripe_user_returned_invalid("nlopt_optimize");
94   else {
95     if (gradient) {
96       if (n == 1 && res(1).is_real_scalar())
97         gradient[0] = res(1).double_value();
98       else {
99         Matrix grad = res(1).matrix_value();
100         for (unsigned i = 0; i < n; ++i)
101           gradient[i] = grad(i);
102       }
103     }
104     data->neval++;
105     if (data->verbose) printf("nlopt_optimize eval #%d: %g\n", 
106                               data->neval, res(0).double_value());
107     double f = res(0).double_value();
108     if (f != f /* isnan(f) */) nlopt_force_stop(data->opt);
109     return f;
110   }
111   return 0;
112 }                                
113
114 static double user_function1(unsigned n, const double *x,
115                             double *gradient, /* NULL if not needed */
116                             void *data_)
117 {
118   octave_function *f = (octave_function *) data_;
119   octave_value_list args(1, 0);
120   Matrix xm(1,n);
121   for (unsigned i = 0; i < n; ++i)
122     xm(i) = x[i];
123   args(0) = xm;
124   octave_value_list res = f->do_multi_index_op(gradient ? 2 : 1, args); 
125   if (res.length() < (gradient ? 2 : 1))
126     gripe_user_supplied_eval("nlopt_optimize");
127   else if (!res(0).is_real_scalar()
128            || (gradient && !res(1).is_real_matrix()
129                && !(n == 1 && res(1).is_real_scalar())))
130     gripe_user_returned_invalid("nlopt_optimize");
131   else {
132     if (gradient) {
133       if (n == 1 && res(1).is_real_scalar())
134         gradient[0] = res(1).double_value();
135       else {
136         Matrix grad = res(1).matrix_value();
137         for (unsigned i = 0; i < n; ++i)
138           gradient[i] = grad(i);
139       }
140     }
141     return res(0).double_value();
142   }
143   return 0;
144 }                                
145
146 #define CHECK1(cond, msg) if (!(cond)) { fprintf(stderr, msg "\n\n"); nlopt_destroy(opt); nlopt_destroy(local_opt); return NULL; }
147
148 nlopt_opt make_opt(octave_map &opts, int n)
149 {
150   nlopt_opt opt = NULL, local_opt = NULL;
151
152   nlopt_algorithm algorithm = 
153     nlopt_algorithm(struct_val_default(opts, "algorithm", 
154                                        NLOPT_NUM_ALGORITHMS));
155   CHECK1(((int)algorithm) >= 0 && algorithm < NLOPT_NUM_ALGORITHMS,
156         "invalid opt.algorithm");
157
158   opt = nlopt_create(algorithm, n);
159   CHECK1(opt, "nlopt: out of memory");
160
161   Matrix m_inf(1, n, -HUGE_VAL);
162   Matrix lb = struct_val_default(opts, "lower_bounds", m_inf);
163   CHECK1(n == lb.length(), "wrong length of opt.lower_bounds");
164   CHECK1(nlopt_set_lower_bounds(opt, lb.data()) > 0, "nlopt: out of memory");
165
166   Matrix p_inf(1, n, +HUGE_VAL);
167   Matrix ub = struct_val_default(opts, "upper_bounds", p_inf);
168   CHECK1(n == ub.length(), "wrong length of opt.upper_bounds");
169   CHECK1(nlopt_set_upper_bounds(opt, ub.data()) > 0, "nlopt: out of memory");
170
171   nlopt_set_stopval(opt, struct_val_default(opts, "stopval", -HUGE_VAL));
172   nlopt_set_ftol_rel(opt, struct_val_default(opts, "ftol_rel", 0.0));
173   nlopt_set_ftol_abs(opt, struct_val_default(opts, "ftol_abs", 0.0));
174   nlopt_set_xtol_rel(opt, struct_val_default(opts, "xtol_rel", 0.0));
175
176   {
177     Matrix zeros(1, n, 0.0);
178     Matrix xtol_abs = struct_val_default(opts, "xtol_abs", zeros);
179     CHECK1(n == xtol_abs.length(), "stop.xtol_abs must have same length as x");
180     CHECK1(nlopt_set_xtol_abs(opt, xtol_abs.data())>0, "nlopt: out of memory");
181   }
182
183   nlopt_set_maxeval(opt, struct_val_default(opts, "maxeval", 0) < 0 ?
184                     0 : struct_val_default(opts, "maxeval", 0));
185   nlopt_set_maxtime(opt, struct_val_default(opts, "maxtime", 0.0));
186
187   nlopt_set_population(opt, struct_val_default(opts, "population", 0));
188   nlopt_set_vector_storage(opt, struct_val_default(opts, "vector_storage", 0));
189
190   if (opts.contains("initial_step")) {
191     Matrix zeros(1, n, 0.0);
192     Matrix initial_step = struct_val_default(opts, "initial_step", zeros);
193     CHECK1(n == initial_step.length(),
194           "stop.initial_step must have same length as x");
195     CHECK1(nlopt_set_initial_step(opt, initial_step.data()) > 0,
196           "nlopt: out of memory");
197   }
198
199   if (opts.contains("local_optimizer")) {
200     CHECK1(opts.contents("local_optimizer").length() == 1 
201           && (opts.contents("local_optimizer"))(0).is_map(),
202           "opt.local_optimizer must be a structure");
203     octave_map local_opts = (opts.contents("local_optimizer"))(0).map_value();
204     CHECK1((local_opt = make_opt(local_opts, n)), 
205           "error initializing local optimizer");
206     nlopt_set_local_optimizer(opt, local_opt);
207     nlopt_destroy(local_opt); local_opt = NULL;
208   }
209
210   return opt;
211 }
212
213 #define CHECK(cond, msg) if (!(cond)) { fprintf(stderr, msg "\n\n"); nlopt_destroy(opt); return retval; }
214
215 DEFUN_DLD(nlopt_optimize, args, nargout, NLOPT_OPTIMIZE_USAGE)
216 {
217   octave_value_list retval;
218   double A;
219   nlopt_opt opt = NULL;
220
221   CHECK(args.length() == 2 && nargout <= 3, "wrong number of args");
222
223   CHECK(args(0).is_map(), "opt must be structure")
224   octave_map opts = args(0).map_value();
225
226   CHECK(args(1).is_real_matrix() || args(1).is_real_scalar(),
227         "x must be real vector");
228   Matrix x = args(1).is_real_scalar() ?
229     Matrix(1, 1, args(1).double_value()) : args(1).matrix_value();
230   int n = x.length();
231
232   CHECK((opt = make_opt(opts, n)), "error initializing nlopt options");
233
234   user_function_data d;
235   d.neval = 0;
236   d.verbose = struct_val_default(opts, "verbose", 0);
237   d.opt = opt;
238   if (opts.contains("min_objective")) {
239     CHECK(opts.contents("min_objective").length() == 1 
240           && (opts.contents("min_objective"))(0).is_function_handle(),
241           "opt.min_objective must be a function");
242       d.f = (opts.contents("min_objective"))(0).function_value();
243       nlopt_set_min_objective(opt, user_function, &d);
244   }
245   else if (opts.contains("max_objective")) {
246     CHECK(opts.contents("max_objective").length() == 1 
247           && (opts.contents("max_objective"))(0).is_function_handle(),
248           "opt.max_objective must be a function");
249       d.f = (opts.contents("max_objective"))(0).function_value();
250       nlopt_set_max_objective(opt, user_function, &d);
251   }
252   else {
253     CHECK(0,"either opt.min_objective or opt.max_objective must exist");
254   }
255
256   if (opts.contains("fc") && opts.contents("fc").length() == 1) {
257     CHECK((opts.contents("fc"))(0).is_cell(), "opt.fc must be cell array");
258     Cell fc = (opts.contents("fc"))(0).cell_value();
259     Matrix zeros(1, fc.length(), 0.0);
260     Matrix fc_tol = struct_val_default(opts, "fc_tol", zeros);
261     CHECK(fc_tol.length() == fc.length(), 
262           "opt.fc must have same length as opt.fc_tol");
263     for (int i = 0; i < fc.length(); ++i) {
264       CHECK(fc(i).is_function() || fc(i).is_function_handle(),
265             "opt.fc must be a cell array of function handles");
266       CHECK(nlopt_add_inequality_constraint(opt, user_function1,
267                                             fc(i).function_value(),
268                                             fc_tol(i)) > 0,
269             "nlopt error adding inequality constraint");
270     }
271   }
272
273   if (opts.contains("h") && opts.contents("h").length() == 1) {
274     CHECK((opts.contents("h"))(0).is_cell(), "opt.h must be cell array");
275     Cell h = (opts.contents("h"))(0).cell_value();
276     Matrix zeros(1, h.length(), 0.0);
277     Matrix h_tol = struct_val_default(opts, "h_tol", zeros);
278     CHECK(h_tol.length() == h.length(), 
279           "opt.h must have same length as opt.h_tol");
280     for (int i = 0; i < h.length(); ++i) {
281       CHECK(h(i).is_function() || h(i).is_function_handle(),
282             "opt.h must be a cell array of function handles");
283       CHECK(nlopt_add_equality_constraint(opt, user_function1,
284                                             h(i).function_value(),
285                                             h_tol(i)) > 0,
286             "nlopt error adding equality constraint");
287     }
288   }
289
290
291   double opt_f;
292   nlopt_result ret = nlopt_optimize(opt, x.fortran_vec(), &opt_f);
293                                     
294   retval(0) = x;
295   if (nargout > 1)
296     retval(1) = opt_f;
297   if (nargout > 2)
298     retval(2) = int(ret);
299
300   nlopt_destroy(opt);
301
302   return retval;
303 }