BayesOpt
branin_xml.cpp
1 /*
2 -------------------------------------------------------------------------
3  This file is part of BayesOpt, an efficient C++ library for
4  Bayesian optimization.
5 
6  Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es>
7 
8  BayesOpt is free software: you can redistribute it and/or modify it
9  under the terms of the GNU Affero General Public License as published by
10  the Free Software Foundation, either version 3 of the License, or
11  (at your option) any later version.
12 
13  BayesOpt is distributed in the hope that it will be useful, but
14  WITHOUT ANY WARRANTY; without even the implied warranty of
15  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  GNU Affero General Public License for more details.
17 
18  You should have received a copy of the GNU Affero General Public License
19  along with BayesOpt. If not, see <http://www.gnu.org/licenses/>.
20 ------------------------------------------------------------------------
21 */
22 
23 #define _USE_MATH_DEFINES
24 #include <cmath>
25 #include <algorithm>
26 #include <boost/numeric/ublas/assignment.hpp>
27 #include "bayesopt/bayesopt.hpp"
28 #include "param_loader.hpp"
29 #include "fileparser.hpp"
30 
31 #ifndef M_PI
32 /* It shouldn't be necessary, but Windows is completely nuts about
33  math constants and I HATE when include order matters. */
34  #define M_PI 3.14159265358979323846
35 #endif
36 
38  private:
39  std::ifstream input;
40  std::string prefix;
41 
42  public:
43  TemplateWritter(std::string &template_filename, std::string &template_prefix)
44  :input(), prefix(template_prefix)
45  {
46  input.open(template_filename.c_str());
47  }
48 
49  ~TemplateWritter(){
50  input.close();
51  }
52 
53  // Create a file overwriting parameters from the template file
54  void createFile(std::string &filename, const vectord& xin){
55  // Move input pointer to the start of the file and create the output stream
56  input.clear();
57  input.seekg(0, std::ios::beg);
58  std::ofstream output(filename.c_str());
59 
60  bayesopt::utils::FileParser fp; // to_value() and to_string() functions access
61 
62  std::string currentLine;
63  while (getline( input, currentLine)){
64  if(currentLine.length() > 0){
65  // Search for prefixes
66  size_t prefix_index = currentLine.find(prefix);
67  while(prefix_index != std::string::npos){
68  size_t number_index = prefix_index + prefix.length();
69 
70  // Get the number after the prefix
71  std::string number_string = "";
72  while(number_index < currentLine.size() && std::isdigit(currentLine.at(number_index))){
73  number_string = number_string + currentLine.at(number_index);
74  number_index++;
75  }
76 
77  // Index of the parameter
78  size_t x_index = fp.to_value<size_t>(number_string);
79 
80  // Check xin bounds before attempting to read data
81  if(x_index >= xin.size()){
82  // Show error and print "OUT_OF_BOUNDS" on the position of the template
83  std::cout << "ERROR: parameter " << x_index << " is out of bounds" << std::endl;
84  output << currentLine.substr(0, prefix_index) << "OUT_OF_BOUNDS";
85  }
86  else{
87  // And finally, write the value on the correct position of the template
88  double x = xin(x_index);
89  output << currentLine.substr(0, prefix_index) << fp.to_string(x);
90  }
91 
92  // Change currentLine to hold unwritten data and perform a new search
93  currentLine = currentLine.substr(number_index);
94  prefix_index = currentLine.find(prefix);
95  }
96  // Write unwritten data
97  output << currentLine << std::endl;
98  }
99  }
100 
101  output.close();
102  }
103 };
104 
106 {
107 public:
109  ContinuousModel(2,par) {}
110 
111  double evaluateSample( const vectord& xin)
112  {
113  if (xin.size() != 2)
114  {
115  std::cout << "WARNING: This only works for 2D inputs." << std::endl
116  << "WARNING: Using only first two components." << std::endl;
117  }
118 
119  float y = -1;
120  double x1 = xin(0);
121  double x2 = xin(1);
122 
123  // Create XML from template
124  std::string template_filename("../examples/standalone_calls/problem_template.xml");
125  std::string template_prefix("XXXX_");
126  TemplateWritter tw(template_filename, template_prefix);
127  std::string created_filename("../examples/standalone_calls/created_file.xml");
128  tw.createFile(created_filename, xin);
129 
130  // Results filename
131  std::string results_filename("../examples/standalone_calls/results.txt");
132 
133  // Call python script
134  std::string call = "python ../examples/standalone_calls/eval_branin_xml.py " + created_filename + " " + results_filename;
135  system(call.c_str());
136 
137  // TODO (Javier): Change results to XML format
138  bayesopt::utils::FileParser fp(results_filename.c_str());
139  fp.openInput();
140  fp.read("y",y);
141 
142  return y;
143  }
144 
145  bool checkReachability(const vectord &query)
146  {return true;};
147 
148  inline double sqr( double x ){ return x*x; };
149 
150  void printOptimal()
151  {
152  vectord sv(2);
153  sv(0) = 0.1238938; sv(1) = 0.818333;
154  std::cout << "Solutions: " << sv << "->"
155  << evaluateSample(sv) << std::endl;
156  sv(0) = 0.5427728; sv(1) = 0.151667;
157  std::cout << "Solutions: " << sv << "->"
158  << evaluateSample(sv) << std::endl;
159  sv(0) = 0.961652; sv(1) = 0.1650;
160  std::cout << "Solutions: " << sv << "->"
161  << evaluateSample(sv) << std::endl;
162  }
163 
164 };
165 
166 int main(int nargs, char *args[])
167 {
169  if(nargs > 1){
170  if(!bayesopt::utils::ParamLoader::load(args[1], par)){
171  std::cout << "ERROR: provided file \"" << args[1] << "\" does not exist" << std::endl;
172  return -1;
173  }
174  }
175  else{
176  par = initialize_parameters_to_default();
177  par.n_iterations = 190;
178  par.random_seed = 0;
179  par.verbose_level = 1;
180  par.noise = 1e-10;
181  //bayesopt::utils::ParamLoader::save("system_opt.txt", par);
182  }
183 
184 
185  XMLCallsBranin branin(par);
186  vectord result(2);
187 
188  branin.optimize(result);
189  std::cout << "Result: " << result << "->"
190  << branin.evaluateSample(result) << std::endl;
191  branin.printOptimal();
192 
193  // Remove results.txt file
194  std::string filename("../examples/standalone_calls/created_file.xml");
195  if( remove( filename.c_str() ) == 0 ){
196  std::cout << "File \"" << filename << "\" successfully removed" << std::endl;
197  }
198  else{
199  std::cout << "Error: cannot remove \"" << filename << "\" file" << std::endl;
200  }
201 
202  // Remove results.txt file
203  filename = "../examples/standalone_calls/results.txt";
204  if( remove( filename.c_str() ) == 0 ){
205  std::cout << "File \"" << filename << "\" successfully removed" << std::endl;
206  }
207  else{
208  std::cout << "Error: cannot remove \"" << filename << "\" file" << std::endl;
209  }
210  return 0;
211 }
212 
213 
Bayesian optimization for functions in continuous input spaces.
Definition: bayesopt.hpp:78
BayesOpt main C++ interface.
bool checkReachability(const vectord &query)
This function checks if the query is valid or not.
Definition: branin_xml.cpp:145
size_t n_iterations
Maximum BayesOpt evaluations (budget)
Definition: parameters.hpp:66
void optimize(vectord &bestPoint)
Execute the optimization process of the function defined in evaluateSample.
double evaluateSample(const vectord &xin)
Function that defines the actual function to be optimized.
Definition: branin_xml.cpp:111
int verbose_level
Neg-Error,0-Warning,1-Info,2-Debug -> stdout 3-Error,4-Warning,5-Info,>5-Debug -> logfile...
Definition: parameters.hpp:76
double noise
Variance of observation noise (and nugget)
Definition: parameters.hpp:88
Functions to write and parse data files.
Allows to load parameters from file.
int random_seed
>=0 -> Fixed seed, <0 -> Time based (variable).
Definition: parameters.hpp:74