13 #if TIME_WITH_SYS_TIME
14 # include <sys/time.h>
18 # include <sys/time.h>
25 #include "testfuncs.h"
27 static double urand(double a, double b)
29 return a + (rand() * (b - a) / RAND_MAX);
32 static nlopt_algorithm algorithm = NLOPT_GLOBAL_DIRECT;
33 static double ftol_rel = 0, ftol_abs = 0, xtol_rel = 0;
34 static int maxeval = 1000;
35 static double maxtime = 0.0;
37 static int test_function(int ifunc)
43 if (ifunc < 0 || ifunc >= NTESTFUNCS) {
44 fprintf(stderr, "testopt: invalid function %d\n", ifunc);
47 func = testfuncs[ifunc];
48 if (!func.has_gradient && algorithm >= NLOPT_GLOBAL_STOGO) {
50 "testopt: A function with gradients is required for %s\n",
51 nlopt_algorithm_name(algorithm));
54 x = (double *) malloc(sizeof(double) * func.n * 2);
55 if (!x) { fprintf(stderr, "testopt: Out of memory!\n"); return 0; }
58 printf("-----------------------------------------------------------\n");
59 printf("Optimizing %s (%d dims) using %s algorithm\n",
60 func.name, func.n, nlopt_algorithm_name(algorithm));
61 printf("Starting guess x = [");
62 for (i = 0; i < func.n; ++i)
63 printf(" %g", x[i] = urand(func.lb[i], func.ub[i]));
65 f0 = func.f(func.n, x, x + func.n, func.f_data);
66 printf("Starting function value = %g\n", f0);
68 if (testfuncs_verbose && func.has_gradient) {
69 printf("checking gradient:\n");
70 for (i = 0; i < func.n; ++i) {
73 f = func.f(func.n, x, NULL, func.f_data);
75 printf(" grad[%d] = %g vs. numerical derivative %g\n",
76 i, x[i + func.n], (f - f0) / (x[i] * 1e-6));
80 testfuncs_counter = 0;
81 if (nlopt_minimize(algorithm,
82 func.n, func.f, func.f_data,
85 HUGE_VAL, ftol_rel, ftol_abs, xtol_rel, NULL,
86 maxeval, maxtime) < 0) {
87 fprintf(stderr, "testopt: error in nlopt_minimize\n");
90 printf("Found minimum f = %g after %d evaluations.\n",
91 fmin, testfuncs_counter);
92 printf("Minimum at x = [");
93 for (i = 0; i < func.n; ++i) printf(" %g", x[i]);
95 printf("vs. global minimum f = %g at x = [", func.fmin);
96 for (i = 0; i < func.n; ++i) printf(" %g", func.xmin[i]);
98 printf("|f - fmin| = %g, |f - fmin| / |fmin| = %e\n",
99 fabs(fmin - func.fmin), fabs(fmin - func.fmin) / fabs(func.fmin));
105 static void usage(FILE *f)
107 fprintf(f, "Usage: testopt [OPTIONS]\n"
109 " -h : print this help\n"
110 " -v : verbose mode\n"
111 " -r <s> : use random seed <s> for starting guesses\n"
112 " -a <n> : use optimization algorithm <n>\n"
113 " -o <n> : use objective function <n>\n"
114 " -e <n> : use at most <n> evals (default: %d)\n",
118 int main(int argc, char **argv)
122 srand((unsigned) time(NULL));
123 testfuncs_verbose = 0;
125 while ((c = getopt(argc, argv, "hvra:o:e:")) != -1)
131 testfuncs_verbose = 1;
134 srand((unsigned) atoi(optarg));
138 if (c < 0 || c >= NLOPT_NUM_ALGORITHMS) {
139 fprintf(stderr, "testopt: invalid algorithm %d\n", c);
142 algorithm = (nlopt_algorithm) c;
145 if (!test_function(atoi(optarg)))
149 maxeval = atoi(optarg);
152 fprintf(stderr, "harminv: invalid argument -%c\n", c);