chiark / gitweb /
rename subspace_dim to vector_storage, since not necessarily a subspace (and can...
[nlopt.git] / octave / nlopt_optimize-mex.c
1 /* Copyright (c) 2007-2010 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 /* Matlab MEX interface to NLopt, and in particular to nlopt_optimize */
24
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <math.h>
29 #include <mex.h>
30
31 #include "nlopt.h"
32
33 #define CHECK0(cond, msg) if (!(cond)) mexErrMsgTxt(msg);
34
35 static double struct_val_default(const mxArray *s, const char *name, double dflt)
36 {
37      mxArray *val = mxGetField(s, 0, name);
38      if (val) {
39           CHECK0(mxIsNumeric(val) && !mxIsComplex(val) 
40                 && mxGetM(val) * mxGetN(val) == 1,
41                 "opt fields, other than xtol_abs, must be real scalars");
42           return mxGetScalar(val);
43      }
44      return dflt;
45 }
46
47 static double *struct_arrval(const mxArray *s, const char *name, unsigned n,
48                              double *dflt)
49 {
50      mxArray *val = mxGetField(s, 0, name);
51      if (val) {
52           CHECK0(mxIsNumeric(val) && !mxIsComplex(val) 
53                 && mxGetM(val) * mxGetN(val) == n,
54                 "opt vector field is not of length n");
55           return mxGetPr(val);
56      }
57      return dflt;
58 }
59
60 static mxArray *struct_funcval(const mxArray *s, const char *name)
61 {
62      mxArray *val = mxGetField(s, 0, name);
63      if (val) {
64           CHECK0(mxIsChar(val) || mxIsFunctionHandle(val),
65                  "opt function field is not a function handle/name");
66           return val;
67      }
68      return NULL;
69 }
70
71 static double *fill(double *arr, unsigned n, double val)
72 {
73      unsigned i;
74      for (i = 0; i < n; ++i) arr[i] = val;
75      return arr;
76 }
77
78 #define FLEN 128 /* max length of user function name */
79 #define MAXRHS 2 /* max nrhs for user function */
80 typedef struct {
81      char f[FLEN];
82      mxArray *plhs[2];
83      mxArray *prhs[MAXRHS];
84      int xrhs, nrhs;
85      int verbose, neval;
86 } user_function_data;
87
88 static double user_function(unsigned n, const double *x,
89                             double *gradient, /* NULL if not needed */
90                             void *d_)
91 {
92   user_function_data *d = (user_function_data *) d_;
93   double f;
94
95   d->plhs[0] = d->plhs[1] = NULL;
96   memcpy(mxGetPr(d->prhs[d->xrhs]), x, n * sizeof(double));
97
98   CHECK0(0 == mexCallMATLAB(gradient ? 2 : 1, d->plhs, 
99                            d->nrhs, d->prhs, d->f),
100         "error calling user function");
101
102   CHECK0(mxIsNumeric(d->plhs[0]) && !mxIsComplex(d->plhs[0]) 
103         && mxGetM(d->plhs[0]) * mxGetN(d->plhs[0]) == 1,
104         "user function must return real scalar");
105   f = mxGetScalar(d->plhs[0]);
106   mxDestroyArray(d->plhs[0]);
107   if (gradient) {
108      CHECK0(mxIsDouble(d->plhs[1]) && !mxIsComplex(d->plhs[1])
109            && (mxGetM(d->plhs[1]) == 1 || mxGetN(d->plhs[1]) == 1)
110            && mxGetM(d->plhs[1]) * mxGetN(d->plhs[1]) == n,
111            "gradient vector from user function is the wrong size");
112      memcpy(gradient, mxGetPr(d->plhs[1]), n * sizeof(double));
113      mxDestroyArray(d->plhs[1]);
114   }
115   d->neval++;
116   if (d->verbose) mexPrintf("nlopt_optimize eval #%d: %g\n", d->neval, f);
117   return f;
118 }
119
120 #define CHECK1(cond, msg) if (!(cond)) { mxFree(tmp); nlopt_destroy(opt); nlopt_destroy(local_opt); mexWarnMsgTxt(msg); return NULL; };
121
122 nlopt_opt make_opt(const mxArray *opts, unsigned n)
123 {
124      nlopt_opt opt = NULL, local_opt = NULL;
125      nlopt_algorithm algorithm;
126      double *tmp = NULL;
127      unsigned i;
128
129      algorithm = (nlopt_algorithm)
130           struct_val_default(opts, "algorithm", NLOPT_NUM_ALGORITHMS);
131      CHECK1(((int)algorithm) >= 0 && algorithm < NLOPT_NUM_ALGORITHMS,
132             "invalid opt.algorithm");
133
134      tmp = (double *) mxCalloc(n, sizeof(double));
135      opt = nlopt_create(algorithm, n);
136      CHECK1(opt, "nlopt: out of memory");
137
138      nlopt_set_lower_bounds(opt, struct_arrval(opts, "lower_bounds", n,
139                                                fill(tmp, n, -HUGE_VAL)));
140      nlopt_set_upper_bounds(opt, struct_arrval(opts, "upper_bounds", n,
141                                                fill(tmp, n, +HUGE_VAL)));
142
143      nlopt_set_stopval(opt, struct_val_default(opts, "stopval", -HUGE_VAL));
144      nlopt_set_ftol_rel(opt, struct_val_default(opts, "ftol_rel", 0.0));
145      nlopt_set_ftol_abs(opt, struct_val_default(opts, "ftol_abs", 0.0));
146      nlopt_set_xtol_rel(opt, struct_val_default(opts, "xtol_rel", 0.0));
147      nlopt_set_xtol_abs(opt, struct_arrval(opts, "xtol_abs", n,
148                                            fill(tmp, n, 0.0)));
149      nlopt_set_maxeval(opt, struct_val_default(opts, "maxeval", 0.0) < 0 ?
150                        0 : struct_val_default(opts, "maxeval", 0.0));
151      nlopt_set_maxtime(opt, struct_val_default(opts, "maxtime", 0.0));
152
153      nlopt_set_population(opt, struct_val_default(opts, "population", 0));
154      nlopt_set_vector_storage(opt, struct_val_default(opts, "vector_storage", 0));
155
156      if (struct_arrval(opts, "initial_step", n, NULL))
157           nlopt_set_initial_step(opt,
158                                  struct_arrval(opts, "initial_step", n, NULL));
159      
160      if (mxGetField(opts, 0, "local_optimizer")) {
161           const mxArray *local_opts = mxGetField(opts, 0, "local_optimizer");
162           CHECK1(mxIsStruct(local_opts),
163                  "opt.local_optimizer must be a structure");
164           CHECK1(local_opt = make_opt(local_opts, n),
165                  "error initializing local optimizer");
166           nlopt_set_local_optimizer(opt, local_opt);
167           nlopt_destroy(local_opt); local_opt = NULL;
168      }
169
170      mxFree(tmp);
171      return opt;
172 }
173
174 #define CHECK(cond, msg) if (!(cond)) { mxFree(dh); mxFree(dfc); nlopt_destroy(opt); mexErrMsgTxt(msg); }
175
176 void mexFunction(int nlhs, mxArray *plhs[],
177                  int nrhs, const mxArray *prhs[])
178 {
179      unsigned n;
180      double *x, *x0, opt_f;
181      nlopt_result ret;
182      mxArray *x_mx, *mx;
183      user_function_data d, *dfc = NULL, *dh = NULL;
184      nlopt_opt opt = NULL;
185
186      CHECK(nrhs == 2 && nlhs <= 3, "wrong number of arguments");
187
188      /* options = prhs[0] */
189      CHECK(mxIsStruct(prhs[0]), "opt must be a struct");
190      
191      /* x0 = prhs[1] */
192      CHECK(mxIsDouble(prhs[1]) && !mxIsComplex(prhs[1])
193            && (mxGetM(prhs[1]) == 1 || mxGetN(prhs[1]) == 1),
194            "x must be real row or column vector");
195      n = mxGetM(prhs[1]) * mxGetN(prhs[1]),
196      x0 = mxGetPr(prhs[1]);
197
198      CHECK(opt = make_opt(prhs[0], n), "error initializing nlopt options");
199
200      d.neval = 0;
201      d.verbose = (int) struct_val_default(prhs[0], "verbose", 0);
202
203      /* function f = prhs[1] */
204      mx = struct_funcval(prhs[0], "min_objective");
205      if (!mx) mx = struct_funcval(prhs[0], "max_objective");
206      CHECK(mx, "either opt.min_objective or opt.max_objective must exist");
207      if (mxIsChar(mx)) {
208           CHECK(mxGetString(mx, d.f, FLEN) == 0,
209                 "error reading function name string (too long?)");
210           d.nrhs = 1;
211           d.xrhs = 0;
212      }
213      else {
214           d.prhs[0] = mx;
215           strcpy(d.f, "feval");
216           d.nrhs = 2;
217           d.xrhs = 1;
218      }
219      d.prhs[d.xrhs] = mxCreateDoubleMatrix(1, n, mxREAL);
220      if (struct_funcval(prhs[0], "min_objective"))
221           nlopt_set_min_objective(opt, user_function, &d);
222      else
223           nlopt_set_max_objective(opt, user_function, &d);
224      
225
226      if ((mx = mxGetField(prhs[0], 0, "fc"))) {
227           int j, m;
228           double *fc_tol;
229           
230           CHECK(mxIsCell(mx), "fc must be a Cell array");
231           m = mxGetM(mx) * mxGetN(mx);;
232           dfc = (user_function_data *) mxCalloc(m, sizeof(user_function_data));
233           fc_tol = struct_arrval(prhs[0], "fc_tol", m, NULL);
234
235           for (j = 0; j < m; ++j) {
236                mxArray *fc = mxGetCell(mx, j);
237                CHECK(mxIsChar(fc) || mxIsFunctionHandle(fc),
238                      "fc must contain function handles or function names");
239                if (mxIsChar(fc)) {
240                     CHECK(mxGetString(fc, dfc[j].f, FLEN) == 0,
241                      "error reading function name string (too long?)");
242                     dfc[j].nrhs = 1;
243                     dfc[j].xrhs = 0;
244                }
245                else {
246                     dfc[j].prhs[0] = fc;
247                     strcpy(dfc[j].f, "feval");
248                     dfc[j].nrhs = 2;
249                     dfc[j].xrhs = 1;
250                }
251                dfc[j].verbose = d.verbose > 1;
252                dfc[j].neval = 0;
253                dfc[j].prhs[dfc[j].xrhs] = d.prhs[d.xrhs];
254                CHECK(nlopt_add_inequality_constraint(opt, user_function,
255                                                      dfc + j,
256                                                      fc_tol ? fc_tol[j] : 0)
257                      > 0, "nlopt error adding inequality constraint");
258           }
259      }
260
261
262      if ((mx = mxGetField(prhs[0], 0, "h"))) {
263           int j, m;
264           double *h_tol;
265           
266           CHECK(mxIsCell(mx), "h must be a Cell array");
267           m = mxGetM(mx) * mxGetN(mx);;
268           dh = (user_function_data *) mxCalloc(m, sizeof(user_function_data));
269           h_tol = struct_arrval(prhs[0], "h_tol", m, NULL);
270
271           for (j = 0; j < m; ++j) {
272                mxArray *h = mxGetCell(mx, j);
273                CHECK(mxIsChar(h) || mxIsFunctionHandle(h),
274                      "h must contain function handles or function names");
275                if (mxIsChar(h)) {
276                     CHECK(mxGetString(h, dh[j].f, FLEN) == 0,
277                      "error reading function name string (too long?)");
278                     dh[j].nrhs = 1;
279                     dh[j].xrhs = 0;
280                }
281                else {
282                     dh[j].prhs[0] = h;
283                     strcpy(dh[j].f, "feval");
284                     dh[j].nrhs = 2;
285                     dh[j].xrhs = 1;
286                }
287                dh[j].verbose = d.verbose > 1;
288                dh[j].neval = 0;
289                dh[j].prhs[dh[j].xrhs] = d.prhs[d.xrhs];
290                CHECK(nlopt_add_equality_constraint(opt, user_function,
291                                                      dh + j,
292                                                    h_tol ? h_tol[j] : 0)
293                      > 0, "nlopt error adding equality constraint");
294           }
295      }
296
297
298      x_mx = mxCreateDoubleMatrix(mxGetM(prhs[1]), mxGetN(prhs[1]), mxREAL);
299      x = mxGetPr(x_mx);
300      memcpy(x, x0, sizeof(double) * n);
301
302      ret = nlopt_optimize(opt, x, &opt_f);
303
304      mxFree(dh);
305      mxFree(dfc);
306      mxDestroyArray(d.prhs[d.xrhs]);
307      nlopt_destroy(opt);
308
309      plhs[0] = x_mx;
310      if (nlhs > 1) {
311           plhs[1] = mxCreateDoubleMatrix(1, 1, mxREAL);
312           *(mxGetPr(plhs[1])) = opt_f;
313      }
314      if (nlhs > 2) {
315           plhs[2] = mxCreateDoubleMatrix(1, 1, mxREAL);
316           *(mxGetPr(plhs[2])) = (int) ret;
317      }
318 }