test_optimizers.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. #include <catch2/catch.hpp>
  2. #include <test_utils.hpp>
  3. #include <libslic3r/Optimize/BruteforceOptimizer.hpp>
  4. #include <libslic3r/Optimize/NLoptOptimizer.hpp>
  5. void check_opt_result(double score, double ref, double abs_err, double rel_err)
  6. {
  7. double abs_diff = std::abs(score - ref);
  8. double rel_diff = std::abs(abs_diff / std::abs(ref));
  9. bool abs_reached = abs_diff < abs_err;
  10. bool rel_reached = rel_diff < rel_err;
  11. bool precision_reached = abs_reached || rel_reached;
  12. REQUIRE(precision_reached);
  13. }
  14. template<class Opt> void test_sin(Opt &&opt)
  15. {
  16. using namespace Slic3r::opt;
  17. auto optfunc = [](const auto &in) {
  18. auto [phi] = in;
  19. return std::sin(phi);
  20. };
  21. auto init = initvals({PI});
  22. auto optbounds = bounds({ {0., 2 * PI}});
  23. Result result_min = opt.to_min().optimize(optfunc, init, optbounds);
  24. Result result_max = opt.to_max().optimize(optfunc, init, optbounds);
  25. check_opt_result(result_min.score, -1., 1e-2, 1e-4);
  26. check_opt_result(result_max.score, 1., 1e-2, 1e-4);
  27. }
  28. template<class Opt> void test_sphere_func(Opt &&opt)
  29. {
  30. using namespace Slic3r::opt;
  31. Result result = opt.to_min().optimize([](const auto &in) {
  32. auto [x, y] = in;
  33. return x * x + y * y + 1.;
  34. }, initvals({.6, -0.2}), bounds({{-1., 1.}, {-1., 1.}}));
  35. check_opt_result(result.score, 1., 1e-2, 1e-4);
  36. }
  37. TEST_CASE("Test brute force optimzer for basic 1D and 2D functions", "[Opt]") {
  38. using namespace Slic3r::opt;
  39. Optimizer<AlgBruteForce> opt;
  40. test_sin(opt);
  41. test_sphere_func(opt);
  42. }