/* Point_bayes.cpp - use bayesian optimization James S. Plank CS494/594 Lecture notes. Mon May 18 12:10:21 EDT 2020 */ #include "points.hpp" #include "bayesopt/bayesopt.h" // This is what you include to get the "C" API #include #include #include #include #include #include #include using namespace std; typedef std::runtime_error SRE; bool Print = false; /* To use BayesOpt, you need to define a testing function with their prototype: */ double min_function(unsigned int n, // Number of dimensions const double *x, // The point to test - an array of n dobules double *gradient, // Just set this to NULL. void *func_data) // You use this to pass data to the function. // In our case, it will be a pointer to the Points class { Points *p; vector xv; unsigned int i; double rv; gradient = NULL; // We don't use this, so set it to NULL /* My code simply converts the data from their format into a Min_Distance() call. */ p = (Points *) func_data; for (i = 0; i < n; i++) xv.push_back(x[i]); rv = p->Min_Distance(xv); if (Print) { for (i = 0; i < n; i++) printf(" %lg", x[i]); printf(" %lg\n", rv); } return -rv; /* I return the negation, because the optimizer does minimization. */ } int main(int argc, char **argv) { Points points; double *lower, *upper, *x, *minf; long long seed; long long iterations; bopt_params params; size_t i; if (argc != 4) { fprintf(stderr, "usage: points_bayes iterations seed print(t/f) - points on stdin\n"); exit(1); } if (sscanf(argv[1], "%lld", &iterations) != 1) { fprintf(stderr, "Bad iterations\n"); exit(0); } if (sscanf(argv[2], "%lld", &seed) != 1) { fprintf(stderr, "Bad seed\n"); exit(0); } if ((string) argv[3] == "t") Print = true; /* Read the points from stdin. */ try { points.Read(cin); } catch (const SRE &e) { fprintf(stderr, "Error reading points on stdin:\n%s\n", e.what()); exit(1); } /* Set the parameters of the Bayesian Optimizer */ params = initialize_parameters_to_default(); params.n_iterations = iterations; params.random_seed = seed; params.verbose_level = 0; lower = (double *) malloc(sizeof(double) * points.p[0].size()); upper = (double *) malloc(sizeof(double) * points.p[0].size()); x = (double *) malloc(sizeof(double) * points.p[0].size()); minf = (double *) malloc(sizeof(double) * points.p[0].size()); for (i = 0; i < points.p[0].size(); i++) { lower[i] = 1.0; upper[i] = 9.0; } bayes_optimization((int) points.p[0].size(), min_function, (void *) &points, lower, upper, x, minf, params); printf("Best x:"); for (i = 0; i < points.p[0].size(); i++) printf(" %lg", x[i]); printf("\n"); printf("Max: %lg\n", -minf[0]); return 0; }