/* * Copyright Nick Thompson, 2024 * Use, modification and distribution are subject to the * Boost Software License, Version 1.0. (See accompanying file * LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef TEST_FUNCTIONS_FOR_OPTIMIZATION_HPP #define TEST_FUNCTIONS_FOR_OPTIMIZATION_HPP #include #include #include #if __has_include() // This is the only system boost.units still works on. // I imagine this will start to fail at some point, // and we'll have to remove this test as well. #if defined(__APPLE__) #define BOOST_MATH_TEST_UNITS_COMPATIBILITY 1 #include #include #include #include #include using namespace boost::units; using namespace boost::units::si; // This *should* return an area, but see: https://github.com/boostorg/units/issues/58 // This sadly prevents std::atomic>. // Nonetheless, we *do* get some information making the argument type dimensioned, // even if it would be better to get the full information: double dimensioned_sphere(std::vector> const & v) { quantity r(0.0*meters*meters); for (auto const & x : v) { r += (x * x); } quantity scale(1.0*meters*meters); return static_cast(r/scale); } #endif #endif // Taken from: https://en.wikipedia.org/wiki/Test_functions_for_optimization template Real ackley(std::array const &v) { using std::sqrt; using std::cos; using std::exp; using boost::math::constants::two_pi; using boost::math::constants::e; Real x = v[0]; Real y = v[1]; Real arg1 = -sqrt((x * x + y * y) / 2) / 5; Real arg2 = cos(two_pi() * x) + cos(two_pi() * y); return -20 * exp(arg1) - exp(arg2 / 2) + 20 + e(); } template auto rosenbrock_saddle(std::array const &v) { auto x = v[0]; auto y = v[1]; return 100 * (x * x - y) * (x * x - y) + (1 - x) * (1 - x); } template Real rastrigin(std::vector const &v) { using std::cos; using boost::math::constants::two_pi; auto A = static_cast(10); auto y = static_cast(10 * v.size()); for (auto x : v) { y += x * x - A * cos(two_pi() * x); } return y; } // Useful for testing return-type != scalar argument type, // and robustness to NaNs: double sphere(std::vector const &v) { double r = 0.0; for (auto x : v) { double x_ = static_cast(x); r += x_ * x_; } if (r >= 1) { return std::numeric_limits::quiet_NaN(); } return r; } template Real three_hump_camel(std::array const & v) { Real x = v[0]; Real y = v[1]; auto xsq = x*x; return 2*xsq - (1 + Real(1)/Real(20))*xsq*xsq + xsq*xsq*xsq/6 + x*y + y*y; } // Minima occurs at (3, 1/2) with value 0: template Real beale(std::array const & v) { Real x = v[0]; Real y = v[1]; Real t1 = Real(3)/Real(2) -x + x*y; Real t2 = Real(9)/Real(4) -x + x*y*y; Real t3 = Real(21)/Real(8) -x + x*y*y*y; return t1*t1 + t2*t2 + t3*t3; } #endif