testWackerOptimization.cpp 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. /**
  2. * @file testWackerOptimization.cpp
  3. * @brief test the downhill simplex method on a toy example
  4. * @author Erik Rodner
  5. * @date 01/31/2012
  6. */
  7. #include "core/basics/Config.h"
  8. #include "optimization/DownhillSimplexOptimizer.h"
  9. #include "optimization/GoldenCutLineSearcher.h"
  10. #include "optimization/FileLog.h"
  11. using namespace std;
  12. using namespace NICE;
  13. const int dim = 1;
  14. class MyCostFunction : public CostFunction
  15. {
  16. public:
  17. MyCostFunction() : CostFunction(dim)
  18. {
  19. }
  20. virtual double evaluate(const optimization::matrix_type & x)
  21. {
  22. double f;
  23. cerr << x.rows() << " x " << x.cols() << endl;
  24. if ( x.rows() == 1 )
  25. {
  26. cerr << "current position: " << x[0][0] << endl;
  27. f = pow(x[0][0] - 0.3, 2.0);
  28. cerr << "function value: " << f << endl;
  29. } else {
  30. cerr << "current position: " << x[0][0] << " " << x[1][0] << endl;
  31. f = pow(x[0][0] - 0.3, 2.0) + pow( x[1][0] - 0.2, 2.0 );
  32. cerr << "function value: " << f << endl;
  33. }
  34. return f;
  35. }
  36. };
  37. /**
  38. test the downhill simplex method on a toy example
  39. */
  40. int main (int argc, char **argv)
  41. {
  42. std::set_terminate(__gnu_cxx::__verbose_terminate_handler);
  43. Config conf ( argc, argv );
  44. CostFunction *func = new MyCostFunction();
  45. optimization::matrix_type initialParams (dim, 1);
  46. initialParams.Set(0.8);
  47. if ( dim == 2 )
  48. cerr << initialParams[0][0] << " " << initialParams[1][0] << endl;
  49. optimization::matrix_type scales (dim, 1);
  50. scales.Set(1.0);
  51. SimpleOptProblem optProblem ( func, initialParams, scales );
  52. bool useDownhill = conf.gB("main", "use_downhill", true );
  53. if ( useDownhill ) {
  54. DownhillSimplexOptimizer optimizer;
  55. optimizer.setMaxNumIter(true, conf.gI("main", "max_iterations", 10));
  56. optimizer.optimizeProb ( optProblem );
  57. /* Contraints are not working for DownhillSimplexOptimizer
  58. optProblem.setUpperBound(0, 1.0);
  59. optProblem.setLowerBound(0, 0.0);
  60. optProblem.setUpperBound(1, 1.0);
  61. optProblem.setLowerBound(1, 0.0);
  62. */
  63. } else {
  64. FileLog fl ("/tmp/optimizer.log");
  65. GoldenCutLineSearcher optimizer ( func, &fl );
  66. optimizer.setBounds(0.0, 1.0);
  67. optimizer.optimize();
  68. }
  69. delete func;
  70. return 0;
  71. }