chiark / gitweb /
rename files from C++ to C
[nlopt.git] / test / testopt.c
1 /* Copyright (c) 2007-2011 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 <stdlib.h>
24 #include <stdio.h>
25 #include <math.h>
26 #include <string.h>
27
28 #include "nlopt_config.h"
29
30 #ifdef HAVE_UNISTD_H
31 #  include <unistd.h>
32 #endif
33 #ifdef HAVE_GETOPT_H
34 #  include <getopt.h>
35 #else
36 #  include "nlopt-getopt.h"
37 #endif
38
39 #define USE_FEENABLEEXCEPT 0
40 #if USE_FEENABLEEXCEPT
41 #  include <fenv.h>
42 extern "C" int feenableexcept (int EXCEPTS);
43 #endif
44
45
46 #include "nlopt.h"
47 #include "nlopt-util.h"
48 #include "testfuncs.h"
49
50 static nlopt_algorithm algorithm = NLOPT_GN_DIRECT_L;
51 static double ftol_rel = 0, ftol_abs = 0, xtol_rel = 0, xtol_abs = 0, minf_max_delta = -HUGE_VAL;
52 static int maxeval = 1000, iterations = 1, center_start = 0;
53 static double maxtime = 0.0;
54 static double xinit_tol = -1;
55 static int force_constraints = 0;
56 static int fix_bounds[100] = {0,0,0,0,0,0,0,0,0,0,
57                               0,0,0,0,0,0,0,0,0,0,
58                               0,0,0,0,0,0,0,0,0,0,
59                               0,0,0,0,0,0,0,0,0,0,
60                               0,0,0,0,0,0,0,0,0,0,
61                               0,0,0,0,0,0,0,0,0,0,
62                               0,0,0,0,0,0,0,0,0,0,
63                               0,0,0,0,0,0,0,0,0,0,
64                               0,0,0,0,0,0,0,0,0,0,
65                               0,0,0,0,0,0,0,0,0,0};
66
67 static void listalgs(FILE *f)
68 {
69   int i;
70   fprintf(f, "Available algorithms:\n");
71   for (i = 0; i < NLOPT_NUM_ALGORITHMS; ++i)
72     fprintf(f, "  %2d: %s\n", i, nlopt_algorithm_name((nlopt_algorithm) i));
73 }
74
75 static void listfuncs(FILE *f)
76 {
77   int i;
78   fprintf(f, "Available objective functions:\n");
79   for (i = 0; i < NTESTFUNCS; ++i)
80     fprintf(f, "  %2d: %s (%d dims)\n", i, testfuncs[i].name, testfuncs[i].n);
81 }
82
83 typedef struct {
84   const double *lb, *ub;
85   nlopt_func f;
86   void *f_data;
87 } bounds_wrap_data;
88
89 static double bounds_wrap_func(int n, const double *x, double *grad, void *d_)
90 {
91   bounds_wrap_data *d = (bounds_wrap_data *) d_;
92   int i;
93   double b = 0;
94   for (i = 0; i < n; ++i) {
95     if (x[i] < d->lb[i]) {
96       b = d->lb[i];
97       break; 
98     }
99     else if (x[i] > d->ub[i]) {
100       b = d->ub[i];
101       break;
102     }
103   }
104   if (i < n)
105     fprintf(stderr, "WARNING: bounds violated by x[%d] = %g = %g + %g\n",
106             i, x[i], b, x[i] - b);
107   return d->f(n, x, grad, d->f_data);
108 }
109
110 static int test_function(int ifunc)
111 {
112   testfunc func;
113   int i, iter;
114   double *x, minf, minf_max, f0, *xtabs, *lb, *ub;
115   nlopt_result ret;
116   double start = nlopt_seconds();
117   int total_count = 0, max_count = 0, min_count = 1<<30;
118   double total_err = 0, max_err = 0;
119   bounds_wrap_data bw;
120   
121   if (ifunc < 0 || ifunc >= NTESTFUNCS) {
122     fprintf(stderr, "testopt: invalid function %d\n", ifunc);
123     listfuncs(stderr);
124     return 0;
125   }
126   func = testfuncs[ifunc];
127   x = (double *) malloc(sizeof(double) * func.n * 5);
128   if (!x) { fprintf(stderr, "testopt: Out of memory!\n"); return 0; }
129
130   lb = x + func.n * 3;
131   ub = lb + func.n;
132   xtabs = x + func.n * 2;
133   bw.lb = lb;
134   bw.ub = ub;
135   bw.f = func.f;
136   bw.f_data = func.f_data;
137
138   for (i = 0; i < func.n; ++i) xtabs[i] = xtol_abs;
139   minf_max = minf_max_delta > (-HUGE_VAL) ? minf_max_delta + func.minf : (-HUGE_VAL);
140   
141   printf("-----------------------------------------------------------\n");
142   printf("Optimizing %s (%d dims) using %s algorithm\n",
143          func.name, func.n, nlopt_algorithm_name(algorithm));
144   printf("lower bounds at lb = [");
145   for (i = 0; i < func.n; ++i) printf(" %g", func.lb[i]);
146   printf("]\n");
147   printf("upper bounds at ub = [");
148   for (i = 0; i < func.n; ++i) printf(" %g", func.ub[i]);
149   printf("]\n");
150   memcpy(lb, func.lb, func.n * sizeof(double));
151   memcpy(ub, func.ub, func.n * sizeof(double));
152   for (i = 0; i < func.n; ++i) if (fix_bounds[i]) {
153       printf("fixing bounds for dim[%d] to xmin[%d]=%g\n",
154              i, i, func.xmin[i]);
155       lb[i] = ub[i] = func.xmin[i];
156   }
157   if (force_constraints) {
158     for (i = 0; i < func.n; ++i) {
159       if (nlopt_iurand(2) == 0)
160         ub[i] = nlopt_urand(lb[i], func.xmin[i]);
161       else
162         lb[i] = nlopt_urand(func.xmin[i], ub[i]);
163     }
164     printf("adjusted lower bounds at lb = [");
165     for (i = 0; i < func.n; ++i) printf(" %g", lb[i]);
166     printf("]\n");
167     printf("adjusted upper bounds at ub = [");
168     for (i = 0; i < func.n; ++i) printf(" %g", ub[i]);
169     printf("]\n");
170   }
171
172   if (fabs(func.f(func.n, func.xmin, 0, func.f_data) - func.minf) > 1e-8) {
173     fprintf(stderr, "BUG: function does not achieve given lower bound!\n");
174     fprintf(stderr, "f(%g", func.xmin[0]);
175     for (i = 1; i < func.n; ++i) fprintf(stderr, ", %g", func.xmin[i]);
176     fprintf(stderr, ") = %0.16g instead of %0.16g, |diff| = %g\n", 
177             func.f(func.n, func.xmin, 0, func.f_data), func.minf,
178             fabs(func.f(func.n, func.xmin, 0, func.f_data) - func.minf));
179     return 0;
180   }
181
182   for (iter = 0; iter < iterations; ++iter) {
183     double val;
184     testfuncs_counter = 0;
185
186     printf("Starting guess x = [");
187     for (i = 0; i < func.n; ++i) {
188       if (center_start)
189         x[i] = (ub[i] + lb[i]) * 0.5;
190       else if (xinit_tol < 0) { /* random starting point near center of box */
191         double dx = (ub[i] - lb[i]) * 0.25;
192         double xm = 0.5 * (ub[i] + lb[i]);
193         x[i] = nlopt_urand(xm - dx, xm + dx);
194       }
195       else {
196         x[i] = nlopt_urand(-xinit_tol, xinit_tol)
197           + (1 + nlopt_urand(-xinit_tol, xinit_tol)) * func.xmin[i];
198         if (x[i] > ub[i]) x[i] = ub[i];
199         else if (x[i] < lb[i]) x[i] = lb[i];
200       }
201       printf(" %g", x[i]);
202     }
203     printf("]\n");
204     f0 = func.f(func.n, x, x + func.n, func.f_data);
205     printf("Starting function value = %g\n", f0);
206     
207     if (iter == 0 && testfuncs_verbose && func.has_gradient) {
208       printf("checking gradient:\n");
209       for (i = 0; i < func.n; ++i) {
210         double f;
211         x[i] *= 1 + 1e-6;
212         f = func.f(func.n, x, NULL, func.f_data);
213         x[i] /= 1 + 1e-6;
214         printf("  grad[%d] = %g vs. numerical derivative %g\n",
215                i, x[i + func.n], (f - f0) / (x[i] * 1e-6));
216       }
217     }
218     
219     testfuncs_counter = 0;
220     ret = nlopt_minimize(algorithm,
221                          func.n, bounds_wrap_func, &bw,
222                          lb, ub,
223                          x, &minf,
224                          minf_max, ftol_rel, ftol_abs, xtol_rel, xtabs,
225                          maxeval, maxtime);
226     printf("finished after %g seconds.\n", nlopt_seconds() - start);
227     printf("return code %d from nlopt_minimize\n", ret);
228     if (ret < 0 && ret != NLOPT_ROUNDOFF_LIMITED
229         && ret != NLOPT_FORCED_STOP) {
230       fprintf(stderr, "testopt: error in nlopt_minimize\n");
231       free(x);
232       return 0;
233     }
234     printf("Found minimum f = %g after %d evaluations.\n", 
235            minf, testfuncs_counter);
236     total_count += testfuncs_counter;
237     if (testfuncs_counter > max_count) max_count = testfuncs_counter;
238     if (testfuncs_counter < min_count) min_count = testfuncs_counter;
239     printf("Minimum at x = [");
240     for (i = 0; i < func.n; ++i) printf(" %g", x[i]);
241     printf("]\n");
242     if (func.minf == 0)
243       printf("|f - minf| = %g\n", fabs(minf - func.minf));
244     else
245       printf("|f - minf| = %g, |f - minf| / |minf| = %e\n",
246              fabs(minf - func.minf), fabs(minf - func.minf) / fabs(func.minf));
247     total_err += fabs(minf - func.minf);
248     if (fabs(minf - func.minf) > max_err)
249       max_err = fabs(minf - func.minf);
250     printf("vs. global minimum f = %g at x = [", func.minf);
251     for (i = 0; i < func.n; ++i) printf(" %g", func.xmin[i]);
252     printf("]\n");
253
254     val = func.f(func.n, x, NULL, func.f_data);
255     if (val != minf) {
256       fprintf(stderr, "Mismatch %g between returned minf=%g and f(x) = %g\n", 
257               minf - val, minf, val);
258       free(x);
259       return 0;
260     }
261   }
262   if (iterations > 1)
263     printf("average #evaluations = %g (%d-%d)\naverage |f-minf| = %g, max |f-minf| = %g\n", total_count * 1.0 / iterations, min_count, max_count, total_err / iterations, max_err);
264
265   free(x);
266   return 1;
267 }
268
269 static void usage(FILE *f)
270 {
271   fprintf(f, "Usage: testopt [OPTIONS]\n"
272           "Options:\n"
273           "     -h : print this help\n"
274           "     -L : list available algorithms and objective functions\n"
275           "     -v : verbose mode\n"
276           " -a <n> : use optimization algorithm <n>\n"
277           " -o <n> : use objective function <n>\n"
278           " -0 <x> : starting guess within <x> + (1+<x>) * optimum\n"
279           " -b <dim0,dim1,...>: eliminate given dims by equating bounds\n"
280           "     -c : starting guess at center of cell\n"
281           "     -C : put optimum outside of bound constraints\n"
282           " -e <n> : use at most <n> evals (default: %d, 0 to disable)\n"
283           " -t <t> : use at most <t> seconds (default: disabled)\n"
284           " -x <t> : relative tolerance <t> on x (default: disabled)\n"
285           " -X <t> : absolute tolerance <t> on x (default: disabled)\n"
286           " -f <t> : relative tolerance <t> on f (default: disabled)\n"
287           " -F <t> : absolute tolerance <t> on f (default: disabled)\n"
288           " -m <m> : stop when minf+<m> is reached (default: disabled)\n"
289           " -i <n> : iterate optimization <n> times (default: 1)\n"
290           " -r <s> : use random seed <s> for starting guesses\n"
291           , maxeval);
292 }
293
294 int main(int argc, char **argv)
295 {
296   int c;
297   
298   nlopt_srand_time();
299   testfuncs_verbose = 0;
300   
301   if (argc <= 1)
302     usage(stdout);
303
304 #if USE_FEENABLEEXCEPT
305   feenableexcept(FE_INVALID);
306 #endif
307   
308   while ((c = getopt(argc, argv, "hLvCc0:r:a:o:i:e:t:x:X:f:F:m:b:")) != -1)
309     switch (c) {
310     case 'h':
311       usage(stdout);
312       return EXIT_SUCCESS;
313     case 'L':
314       listalgs(stdout);
315       listfuncs(stdout);
316       return EXIT_SUCCESS;
317     case 'v':
318       testfuncs_verbose = 1;
319       break;
320     case 'C':
321       force_constraints = 1;
322       break;
323     case 'r':
324       nlopt_srand((unsigned long) atoi(optarg));
325       break;
326     case 'a':
327       c = atoi(optarg);
328       if (c < 0 || c >= NLOPT_NUM_ALGORITHMS) {
329         fprintf(stderr, "testopt: invalid algorithm %d\n", c);
330         listalgs(stderr);
331         return EXIT_FAILURE;
332       }
333       algorithm = (nlopt_algorithm) c;
334       break;
335     case 'o':
336       if (!test_function(atoi(optarg)))
337         return EXIT_FAILURE;
338       break;
339     case 'e':
340       maxeval = atoi(optarg);
341       break;
342     case 'i':
343       iterations = atoi(optarg);
344       break;
345     case 't':
346       maxtime = atof(optarg);
347       break;
348     case 'x':
349       xtol_rel = atof(optarg);
350       break;
351     case 'X':
352       xtol_abs = atof(optarg);
353       break;
354     case 'f':
355       ftol_rel = atof(optarg);
356       break;
357     case 'F':
358       ftol_abs = atof(optarg);
359       break;
360     case 'm':
361       minf_max_delta = atof(optarg);
362       break;
363     case 'c':
364       center_start = 1;
365       break;
366     case '0':
367       center_start = 0;
368       xinit_tol = atof(optarg);
369       break;
370     case 'b': {
371       const char *s = optarg;
372       while (s && *s) {
373         int b = atoi(s);
374         if (b < 0 || b >= 100) { 
375           fprintf(stderr, "invalid -b argument");
376           return EXIT_FAILURE;
377         }
378         fix_bounds[b] = 1;
379         s = strchr(s, ','); if (s) ++s;
380       }
381       break;
382     }
383     default:
384       fprintf(stderr, "harminv: invalid argument -%c\n", c);
385       usage(stderr);
386       return EXIT_FAILURE;
387     }
388   
389   return EXIT_SUCCESS;
390 }