Example shows numeric quadratic function use.
#include "shared-tests/fixture.hh"
#include <iostream>
#include <boost/type_traits/is_same.hpp>
using namespace roboptim;
BOOST_FIXTURE_TEST_SUITE (core, TestSuiteConfiguration)
BOOST_AUTO_TEST_CASE_TEMPLATE (numeric_quadratic_function, T, functionTypes_t)
{
boost::shared_ptr<boost::test_tools::output_test_stream>
output = retrievePattern ("numeric-quadratic-function");
for (int i = 0; i < 5; ++i)
{
a.coeffRef (i,i) = 1.;
}
(*output) << f << '\n';
(*output) << "x = " << x << '\n';
(*output) << "f(x) = " << f (x) << '\n';
(*output) <<
"J(x) = " <<
toDense (f.jacobian (x)) <<
'\n';
(*output) <<
"G(x) = " <<
toDense (f.gradient (x, 0)) <<
'\n';
(*output) <<
"H(x) = " <<
toDense (f.hessian (x, 0)) <<
'\n';
std::cout << output->str () << std::endl;
if (boost::is_same<T, EigenMatrixDense>::value)
BOOST_CHECK (output->match_pattern ());
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 5; ++j)
x[j] = std::ceil (rand () % 50);
std::cout << "x = " << x << '\n';
std::cout << "f(x) = " << f (x) << '\n';
std::cout << "J(x) = " << f.jacobian (x) << '\n';
std::cout << "G(x) = " << f.gradient (x, 0) << '\n';
std::cout << "H(x) = " << f.hessian (x, 0) << '\n';
matrix_t J (1, 5);
for (typename matrix_t::Index i = 0; i < 5; ++i)
J.coeffRef (0, i) = 2 * x[i];
for (typename matrix_t::Index i = 0; i < 5; ++i)
{
std::cout << f.jacobian (x).coeffRef (0, i) << '\n';
std::cout << J.coeffRef (0, i) << '\n';
}
BOOST_CHECK (
allclose (f.jacobian (x), J));
BOOST_CHECK (
allclose (f.hessian (x, 0), 2*a));
}
}
typedef boost::mpl::list< ::roboptim::EigenMatrixSparse> sparseOnly_t;
BOOST_AUTO_TEST_CASE_TEMPLATE (random_gradient_check, T, sparseOnly_t)
{
for (int randomTry = 0; randomTry < 10; ++randomTry)
{
a.setZero ();
b.setZero ();
x.setZero ();
a.insert (i, j) = 0.;
a.coeffRef (i, j) = a.coeffRef (j, i) = static_cast<double> (std::rand () / RAND_MAX);
for (int i = 0; i < 10; ++i)
{
for (int j = 0; j < 5; ++j)
x[j] = std::ceil (rand () % 50);
}
}
}
BOOST_AUTO_TEST_SUITE_END ()