grid_search.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "grid_search.h"
  2. #include <iostream>
  3. #include <cassert>
  4. template <
  5. typename Scalar,
  6. typename DerivedX,
  7. typename DerivedLB,
  8. typename DerivedUB,
  9. typename DerivedI>
  10. IGL_INLINE Scalar igl::grid_search(
  11. const std::function< Scalar (DerivedX &) > f,
  12. const Eigen::MatrixBase<DerivedLB> & LB,
  13. const Eigen::MatrixBase<DerivedUB> & UB,
  14. const Eigen::MatrixBase<DerivedI> & I,
  15. DerivedX & X)
  16. {
  17. Scalar fval = std::numeric_limits<Scalar>::max();
  18. const int dim = LB.size();
  19. assert(UB.size() == dim && "UB should match LB size");
  20. assert(I.size() == dim && "I should match LB size");
  21. X.resize(dim);
  22. // Working X value
  23. DerivedX Xrun(dim);
  24. std::function<void(const int, DerivedX &)> looper;
  25. int calls = 0;
  26. looper = [&](
  27. const int d,
  28. DerivedX & Xrun)
  29. {
  30. assert(d < dim);
  31. Eigen::Matrix<Scalar,Eigen::Dynamic,1> vals =
  32. Eigen::Matrix<Scalar,Eigen::Dynamic,1>::LinSpaced(I(d),LB(d),UB(d));
  33. for(int c = 0;c<I(d);c++)
  34. {
  35. Xrun(d) = vals(c);
  36. if(d+1 < dim)
  37. {
  38. looper(d+1,Xrun);
  39. }else
  40. {
  41. //std::cout<<"call: "<<calls<<std::endl;
  42. // Base case
  43. const Scalar val = f(Xrun);
  44. calls++;
  45. if(val < fval)
  46. {
  47. fval = val;
  48. X = Xrun;
  49. std::cout<<calls<<": "<<fval<<" | "<<X<<std::endl;
  50. }
  51. }
  52. }
  53. };
  54. looper(0,Xrun);
  55. return fval;
  56. }
  57. #ifdef IGL_STATIC_LIBRARY
  58. template double igl::grid_search<double, Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<double, 1, 3, 1, 1, 3>, Eigen::Matrix<int, 1, 3, 1, 1, 3> >(std::function<double (Eigen::Matrix<double, 1, 3, 1, 1, 3>&)>, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<double, 1, 3, 1, 1, 3> > const&, Eigen::MatrixBase<Eigen::Matrix<int, 1, 3, 1, 1, 3> > const&, Eigen::Matrix<double, 1, 3, 1, 1, 3>&);
  59. template float igl::grid_search<float, Eigen::Matrix<float, 1, -1, 1, 1, -1>, Eigen::Matrix<float, 1, -1, 1, 1, -1>, Eigen::Matrix<float, 1, -1, 1, 1, -1>, Eigen::Matrix<int, 1, -1, 1, 1, -1> >(std::function<float (Eigen::Matrix<float, 1, -1, 1, 1, -1>&)>, Eigen::MatrixBase<Eigen::Matrix<float, 1, -1, 1, 1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<float, 1, -1, 1, 1, -1> > const&, Eigen::MatrixBase<Eigen::Matrix<int, 1, -1, 1, 1, -1> > const&, Eigen::Matrix<float, 1, -1, 1, 1, -1>&);
  60. #endif