Use the explaining matchers in the tests of the expectation helpers The ExpectClose and ExpectArraysClose helpers and several file-local matchers neither print the compared values nor locate mismatches, and the relative comparison of Jets is implemented three times. System tests abort the whole test program if a solve fails. Replace the helpers and the file-local matchers by the shared matchers and remove the helpers. Report system test failures as test failures. Change-Id: I8912345d89c686939cfc598a750973b6a2830607
diff --git a/internal/ceres/gradient_checker_test.cc b/internal/ceres/gradient_checker_test.cc index e82f77f..18842ff 100644 --- a/internal/ceres/gradient_checker_test.cc +++ b/internal/ceres/gradient_checker_test.cc
@@ -33,6 +33,7 @@ #include "ceres/gradient_checker.h" #include <cmath> +#include <limits> #include <random> #include <utility> #include <vector> @@ -40,17 +41,24 @@ #include "absl/container/fixed_array.h" #include "absl/log/check.h" #include "absl/log/log.h" +#include "absl/types/span.h" #include "ceres/cost_function.h" #include "ceres/manifold.h" #include "ceres/numeric_diff_options.h" #include "ceres/problem.h" #include "ceres/solver.h" #include "ceres/test_util.h" +#include "gmock/gmock.h" #include "gtest/gtest.h" namespace ceres::internal { +using ::testing::Each; +using ::testing::IsEmpty; +using ::testing::Not; + const double kTolerance = 1e-12; +constexpr double kEpsilon = std::numeric_limits<double>::epsilon(); // We pick a (non-quadratic) function whose derivative are easy: // @@ -235,11 +243,11 @@ << results.error_log; // Check that results contain sensible data. - ASSERT_EQ(results.return_value, true); + ASSERT_TRUE(results.return_value); ASSERT_EQ(results.residuals.size(), 1); CheckDimensions(results, parameter_sizes, parameter_sizes, 1); EXPECT_GE(results.maximum_relative_error, 0.0); - EXPECT_TRUE(results.error_log.empty()); + EXPECT_THAT(results.error_log, IsEmpty()); // Test that if the cost function return false, Probe should return false. good_term.SetReturnValue(false); @@ -250,15 +258,16 @@ << results.error_log; // Check that results contain sensible data. - ASSERT_EQ(results.return_value, false); + ASSERT_FALSE(results.return_value); ASSERT_EQ(results.residuals.size(), 1); CheckDimensions(results, parameter_sizes, parameter_sizes, 1); for (int i = 0; i < num_parameters; ++i) { - EXPECT_EQ(results.local_jacobians.at(i).norm(), 0); - EXPECT_EQ(results.local_numeric_jacobians.at(i).norm(), 0); + EXPECT_THAT(absl::MakeConstSpan(results.local_jacobians.at(i)), Each(0.0)); + EXPECT_THAT(absl::MakeConstSpan(results.local_numeric_jacobians.at(i)), + Each(0.0)); } EXPECT_EQ(results.maximum_relative_error, 0.0); - EXPECT_FALSE(results.error_log.empty()); + EXPECT_THAT(results.error_log, Not(IsEmpty())); // Test that Probe returns false for incorrect Jacobians. BadTestTerm bad_term(num_parameters, parameter_sizes.data(), randu); @@ -270,21 +279,21 @@ bad_gradient_checker.Probe(parameters.data(), kTolerance, &results)); // Check that results contain sensible data. - ASSERT_EQ(results.return_value, true); + ASSERT_TRUE(results.return_value); ASSERT_EQ(results.residuals.size(), 1); CheckDimensions(results, parameter_sizes, parameter_sizes, 1); EXPECT_GT(results.maximum_relative_error, kTolerance); - EXPECT_FALSE(results.error_log.empty()); + EXPECT_THAT(results.error_log, Not(IsEmpty())); // Setting a high threshold should make the test pass. EXPECT_TRUE(bad_gradient_checker.Probe(parameters.data(), 1.0, &results)); // Check that results contain sensible data. - ASSERT_EQ(results.return_value, true); + ASSERT_TRUE(results.return_value); ASSERT_EQ(results.residuals.size(), 1); CheckDimensions(results, parameter_sizes, parameter_sizes, 1); EXPECT_GT(results.maximum_relative_error, 0.0); - EXPECT_TRUE(results.error_log.empty()); + EXPECT_THAT(results.error_log, IsEmpty()); for (int j = 0; j < num_parameters; j++) { delete[] parameters[j]; @@ -353,13 +362,6 @@ Vector residuals_offset_; }; -// Helper function to compare two Eigen matrices (used in the test below). -static void ExpectMatricesClose(Matrix p, Matrix q, double tolerance) { - ASSERT_EQ(p.rows(), q.rows()); - ASSERT_EQ(p.cols(), q.cols()); - ExpectArraysClose(p.size(), p.data(), q.data(), tolerance); -} - // Helper manifold that multiplies the delta vector by the given // jacobian and adds it to the parameter. class MatrixManifold : public Manifold { @@ -434,9 +436,10 @@ Matrix residual_expected = residual_offset + j0 * param0 + j1 * param1; - ExpectMatricesClose(j1_out, j0, std::numeric_limits<double>::epsilon()); - ExpectMatricesClose(j2_out, j1, std::numeric_limits<double>::epsilon()); - ExpectMatricesClose(residual, residual_expected, kTolerance); + EXPECT_THAT(j1_out, MatrixPointwise(RelativelyNear(kEpsilon), j0)); + EXPECT_THAT(j2_out, MatrixPointwise(RelativelyNear(kEpsilon), j1)); + EXPECT_THAT(residual, + MatrixPointwise(RelativelyNear(kTolerance), residual_expected)); // Create manifold. Eigen::Matrix<double, 3, 2, Eigen::RowMajor> global_to_local; @@ -453,14 +456,15 @@ Eigen::Matrix<double, 3, 2, Eigen::RowMajor> global_to_local_out; manifold.PlusJacobian(x.data(), global_to_local_out.data()); - ExpectMatricesClose(global_to_local_out, - global_to_local, - std::numeric_limits<double>::epsilon()); + EXPECT_THAT(global_to_local_out, + MatrixPointwise(RelativelyNear(kEpsilon), global_to_local)); Eigen::Vector3d x_plus_delta; manifold.Plus(x.data(), delta.data(), x_plus_delta.data()); Eigen::Vector3d x_plus_delta_expected = x + (global_to_local * delta); - ExpectMatricesClose(x_plus_delta, x_plus_delta_expected, kTolerance); + EXPECT_THAT( + x_plus_delta, + MatrixPointwise(RelativelyNear(kTolerance), x_plus_delta_expected)); // Now test GradientChecker. std::vector<const Manifold*> manifolds(2); @@ -488,26 +492,30 @@ << results.error_log; // Check that results contain correct data. - ASSERT_EQ(results.return_value, true); - ExpectMatricesClose( - results.residuals, residual, std::numeric_limits<double>::epsilon()); + ASSERT_TRUE(results.return_value); + EXPECT_THAT(results.residuals, + MatrixPointwise(RelativelyNear(kEpsilon), residual)); CheckDimensions(results, parameter_sizes, tangent_sizes, 3); - ExpectMatricesClose( - results.local_jacobians.at(0), j0 * global_to_local, kTolerance); - ExpectMatricesClose(results.local_jacobians.at(1), - j1, - std::numeric_limits<double>::epsilon()); - ExpectMatricesClose( - results.local_numeric_jacobians.at(0), j0 * global_to_local, kTolerance); - ExpectMatricesClose(results.local_numeric_jacobians.at(1), j1, kTolerance); - ExpectMatricesClose( - results.jacobians.at(0), j0, std::numeric_limits<double>::epsilon()); - ExpectMatricesClose( - results.jacobians.at(1), j1, std::numeric_limits<double>::epsilon()); - ExpectMatricesClose(results.numeric_jacobians.at(0), j0, kTolerance); - ExpectMatricesClose(results.numeric_jacobians.at(1), j1, kTolerance); + EXPECT_THAT( + results.local_jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), j0 * global_to_local)); + EXPECT_THAT(results.local_jacobians.at(1), + MatrixPointwise(RelativelyNear(kEpsilon), j1)); + EXPECT_THAT( + results.local_numeric_jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), j0 * global_to_local)); + EXPECT_THAT(results.local_numeric_jacobians.at(1), + MatrixPointwise(RelativelyNear(kTolerance), j1)); + EXPECT_THAT(results.jacobians.at(0), + MatrixPointwise(RelativelyNear(kEpsilon), j0)); + EXPECT_THAT(results.jacobians.at(1), + MatrixPointwise(RelativelyNear(kEpsilon), j1)); + EXPECT_THAT(results.numeric_jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), j0)); + EXPECT_THAT(results.numeric_jacobians.at(1), + MatrixPointwise(RelativelyNear(kTolerance), j1)); EXPECT_GE(results.maximum_relative_error, 0.0); - EXPECT_TRUE(results.error_log.empty()); + EXPECT_THAT(results.error_log, IsEmpty()); // Test interaction with the 'check_gradients' option in Solver. Solver::Options solver_options; @@ -534,28 +542,32 @@ << results.error_log; // Check that results contain correct data. - ASSERT_EQ(results.return_value, true); - ExpectMatricesClose( - results.residuals, residual, std::numeric_limits<double>::epsilon()); + ASSERT_TRUE(results.return_value); + EXPECT_THAT(results.residuals, + MatrixPointwise(RelativelyNear(kEpsilon), residual)); CheckDimensions(results, parameter_sizes, tangent_sizes, 3); ASSERT_EQ(results.local_jacobians.size(), 2); ASSERT_EQ(results.local_numeric_jacobians.size(), 2); - ExpectMatricesClose(results.local_jacobians.at(0), - (j0 + j0_offset) * global_to_local, - kTolerance); - ExpectMatricesClose(results.local_jacobians.at(1), - j1, - std::numeric_limits<double>::epsilon()); - ExpectMatricesClose( - results.local_numeric_jacobians.at(0), j0 * global_to_local, kTolerance); - ExpectMatricesClose(results.local_numeric_jacobians.at(1), j1, kTolerance); - ExpectMatricesClose(results.jacobians.at(0), j0 + j0_offset, kTolerance); - ExpectMatricesClose( - results.jacobians.at(1), j1, std::numeric_limits<double>::epsilon()); - ExpectMatricesClose(results.numeric_jacobians.at(0), j0, kTolerance); - ExpectMatricesClose(results.numeric_jacobians.at(1), j1, kTolerance); + EXPECT_THAT(results.local_jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), + (j0 + j0_offset) * global_to_local)); + EXPECT_THAT(results.local_jacobians.at(1), + MatrixPointwise(RelativelyNear(kEpsilon), j1)); + EXPECT_THAT( + results.local_numeric_jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), j0 * global_to_local)); + EXPECT_THAT(results.local_numeric_jacobians.at(1), + MatrixPointwise(RelativelyNear(kTolerance), j1)); + EXPECT_THAT(results.jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), j0 + j0_offset)); + EXPECT_THAT(results.jacobians.at(1), + MatrixPointwise(RelativelyNear(kEpsilon), j1)); + EXPECT_THAT(results.numeric_jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), j0)); + EXPECT_THAT(results.numeric_jacobians.at(1), + MatrixPointwise(RelativelyNear(kTolerance), j1)); EXPECT_GT(results.maximum_relative_error, 0.0); - EXPECT_FALSE(results.error_log.empty()); + EXPECT_THAT(results.error_log, Not(IsEmpty())); // Test interaction with the 'check_gradients' option in Solver. param0_solver = param0; @@ -573,29 +585,32 @@ << results.error_log; // Check that results contain correct data. - ASSERT_EQ(results.return_value, true); - ExpectMatricesClose( - results.residuals, residual, std::numeric_limits<double>::epsilon()); + ASSERT_TRUE(results.return_value); + EXPECT_THAT(results.residuals, + MatrixPointwise(RelativelyNear(kEpsilon), residual)); CheckDimensions(results, parameter_sizes, tangent_sizes, 3); ASSERT_EQ(results.local_jacobians.size(), 2); ASSERT_EQ(results.local_numeric_jacobians.size(), 2); - ExpectMatricesClose(results.local_jacobians.at(0), - (j0 + j0_offset) * manifold.global_to_local_, - kTolerance); - ExpectMatricesClose(results.local_jacobians.at(1), - j1, - std::numeric_limits<double>::epsilon()); - ExpectMatricesClose(results.local_numeric_jacobians.at(0), - j0 * manifold.global_to_local_, - kTolerance); - ExpectMatricesClose(results.local_numeric_jacobians.at(1), j1, kTolerance); - ExpectMatricesClose(results.jacobians.at(0), j0 + j0_offset, kTolerance); - ExpectMatricesClose( - results.jacobians.at(1), j1, std::numeric_limits<double>::epsilon()); - ExpectMatricesClose(results.numeric_jacobians.at(0), j0, kTolerance); - ExpectMatricesClose(results.numeric_jacobians.at(1), j1, kTolerance); + EXPECT_THAT(results.local_jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), + (j0 + j0_offset) * manifold.global_to_local_)); + EXPECT_THAT(results.local_jacobians.at(1), + MatrixPointwise(RelativelyNear(kEpsilon), j1)); + EXPECT_THAT(results.local_numeric_jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), + j0 * manifold.global_to_local_)); + EXPECT_THAT(results.local_numeric_jacobians.at(1), + MatrixPointwise(RelativelyNear(kTolerance), j1)); + EXPECT_THAT(results.jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), j0 + j0_offset)); + EXPECT_THAT(results.jacobians.at(1), + MatrixPointwise(RelativelyNear(kEpsilon), j1)); + EXPECT_THAT(results.numeric_jacobians.at(0), + MatrixPointwise(RelativelyNear(kTolerance), j0)); + EXPECT_THAT(results.numeric_jacobians.at(1), + MatrixPointwise(RelativelyNear(kTolerance), j1)); EXPECT_GE(results.maximum_relative_error, 0.0); - EXPECT_TRUE(results.error_log.empty()); + EXPECT_THAT(results.error_log, IsEmpty()); // Test interaction with the 'check_gradients' option in Solver. param0_solver = param0;
diff --git a/internal/ceres/jet_test.cc b/internal/ceres/jet_test.cc index 419378a..12851f2 100644 --- a/internal/ceres/jet_test.cc +++ b/internal/ceres/jet_test.cc
@@ -34,8 +34,10 @@ #include <algorithm> #include <cfenv> #include <cmath> +#include <string> -#include "absl/log/log.h" +#include "absl/strings/str_format.h" +#include "absl/types/span.h" #include "ceres/test_util.h" #include "gmock/gmock.h" #include "gtest/gtest.h" @@ -58,6 +60,9 @@ constexpr double kE = 2.71828182845904523536; +using ::testing::Each; +using ::testing::IsNan; + using J = Jet<double, 2>; // Don't care about the dual part for scalar part categorization and comparison // tests @@ -76,63 +81,18 @@ constexpr double kTolerance = 1e-13; -// Stores the floating-point environment containing active floating-point -// exceptions, rounding mode, etc., and restores it upon destruction. -// -// Useful for avoiding side-effects. -class Fenv { - public: - Fenv() { std::fegetenv(&e); } - ~Fenv() { std::fesetenv(&e); } - - Fenv(const Fenv&) = delete; - Fenv& operator=(const Fenv&) = delete; - - private: - std::fenv_t e; -}; - -bool AreAlmostEqual(double x, double y, double max_abs_relative_difference) { - if (std::isnan(x) && std::isnan(y)) { - return true; - } - - if (std::isinf(x) && std::isinf(y)) { - return (std::signbit(x) == std::signbit(y)); - } - - Fenv env; // Do not leak floating-point exceptions to the caller - double absolute_difference = std::abs(x - y); - double relative_difference; - - if (std::fpclassify(x) == FP_ZERO || std::fpclassify(y) == FP_ZERO) { - // If x or y is exactly zero, then relative difference doesn't have any - // meaning. Take the absolute difference instead. - relative_difference = absolute_difference; - } else { - relative_difference = - absolute_difference / std::max(std::abs(x), std::abs(y)); - } - return std::islessequal(relative_difference, max_abs_relative_difference); +// Matches a Jet whose parts are each RelativelyNear those of expected. +auto IsAlmostEqualTo(const J& expected) { + return RelativelyNear(expected, kTolerance); } -MATCHER_P2(IsAlmostEqualToWithTolerance, - y, - tolerance, - "is almost equal to " + testing::PrintToString(y) + - " with tolerance " + testing::PrintToString(tolerance)) { - const bool result = (AreAlmostEqual(arg.a, y.a, tolerance) && - AreAlmostEqual(arg.v[0], y.v[0], tolerance) && - AreAlmostEqual(arg.v[1], y.v[1], tolerance)); - if (!result) { - *result_listener << "\nexpected - actual : " << y - arg; - } - return result; -} - -MATCHER_P(IsAlmostEqualTo, y, "") { - return ExplainMatchResult( - IsAlmostEqualToWithTolerance(y, kTolerance), arg, result_listener); +// Describes the operands and the result of pow for tracing failures. +template <typename Base, typename Exponent> +std::string DescribePow(const Base& a, const Exponent& b, const J& c) { + return absl::StrFormat("\na: %s\nb: %s\na^b: %s", + testing::PrintToString(a), + testing::PrintToString(b), + testing::PrintToString(c)); } const double kStep = 1e-8; @@ -144,9 +104,8 @@ const double exact_dx = f(MakeJet(x, 1.0, 0.0)).v[0]; const double estimated_dx = (f(J(x + kStep)).a - f(J(x - kStep)).a) / (2.0 * kStep); - VLOG(1) << name << "(" << x << "), exact dx: " << exact_dx - << ", estimated dx: " << estimated_dx; - ExpectClose(exact_dx, estimated_dx, kNumericalTolerance); + SCOPED_TRACE(absl::StrFormat("%s(%v)", name, x)); + EXPECT_THAT(exact_dx, RelativelyNear(estimated_dx, kNumericalTolerance)); } // Same as NumericalTest, but given a function taking two arguments. @@ -155,6 +114,7 @@ const Function& f, const double x, const double y) { + SCOPED_TRACE(absl::StrFormat("%s(%v, %v)", name, x, y)); const J exact_delta = f(MakeJet(x, 1.0, 0.0), MakeJet(y, 0.0, 1.0)); const double exact_dx = exact_delta.v[0]; const double exact_dy = exact_delta.v[1]; @@ -169,12 +129,8 @@ (f(J(x + kStep), J(y)).a - f(J(x - kStep), J(y)).a) / (2.0 * kStep); const double estimated_dy = (f(J(x), J(y + kStep)).a - f(J(x), J(y - kStep)).a) / (2.0 * kStep); - VLOG(1) << name << "(" << x << ", " << y << "), exact dx: " << exact_dx - << ", estimated dx: " << estimated_dx; - ExpectClose(exact_dx, estimated_dx, kNumericalTolerance); - VLOG(1) << name << "(" << x << ", " << y << "), exact dy: " << exact_dy - << ", estimated dy: " << estimated_dy; - ExpectClose(exact_dy, estimated_dy, kNumericalTolerance); + EXPECT_THAT(exact_dx, RelativelyNear(estimated_dx, kNumericalTolerance)); + EXPECT_THAT(exact_dy, RelativelyNear(estimated_dy, kNumericalTolerance)); } } // namespace @@ -313,9 +269,9 @@ constexpr double kRelaxedTolerance = 10 * kTolerance; // See formula http://dlmf.nist.gov/10.6.E1 - EXPECT_THAT(cyl_bessel_j(0, z) + cyl_bessel_j(2, z), - IsAlmostEqualToWithTolerance((2.0 / z) * cyl_bessel_j(1, z), - kRelaxedTolerance)); + EXPECT_THAT( + cyl_bessel_j(0, z) + cyl_bessel_j(2, z), + RelativelyNear((2.0 / z) * cyl_bessel_j(1, z), kRelaxedTolerance)); // MSVC does not throw an exception on invalid first argument #ifndef _MSC_VER @@ -419,7 +375,7 @@ IsAlmostEqualTo(MakeJet(9.9999999999999998e-17, 1e-8, 1e-4))); // log(1 + x) collapses to 0 J v = log(J{1} + x); - EXPECT_TRUE(v.a == 0); + EXPECT_EQ(v.a, 0); } } @@ -432,7 +388,7 @@ EXPECT_THAT(expm1(x), IsAlmostEqualTo(MakeJet(1e-16, 1e-8, 1e-4))); // exp(x) - 1 collapses to 0 J v = exp(x) - J{1}; - EXPECT_TRUE(v.a == 0); + EXPECT_EQ(v.a, 0); } } @@ -492,23 +448,20 @@ J a = MakeJet(0, 1, 2); J b = MakeJet(i * 0.1, 3, 4); // b = 0.1 ... 0.9 J c = pow(a, b); - EXPECT_EQ(c.a, 0.0) << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[0])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[1])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; + SCOPED_TRACE(DescribePow(a, b, c)); + EXPECT_EQ(c.a, 0.0); + EXPECT_FALSE(isfinite(c.v[0])); + EXPECT_FALSE(isfinite(c.v[1])); } for (int i = -10; i < 0; i++) { J a = MakeJet(0, 1, 2); J b = MakeJet(i * 0.1, 3, 4); // b = -1,-0.9 ... -0.1 J c = pow(a, b); - EXPECT_FALSE(isfinite(c.a)) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[0])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[1])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; + SCOPED_TRACE(DescribePow(a, b, c)); + EXPECT_FALSE(isfinite(c.a)); + EXPECT_FALSE(isfinite(c.v[0])); + EXPECT_FALSE(isfinite(c.v[1])); } // The special case of 0^0 = 1 defined by the C standard. @@ -516,11 +469,10 @@ J a = MakeJet(0, 1, 2); J b = MakeJet(0, 3, 4); J c = pow(a, b); - EXPECT_EQ(c.a, 1.0) << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[0])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[1])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; + SCOPED_TRACE(DescribePow(a, b, c)); + EXPECT_EQ(c.a, 1.0); + EXPECT_FALSE(isfinite(c.v[0])); + EXPECT_FALSE(isfinite(c.v[1])); } } @@ -532,16 +484,13 @@ for (int i = -10; i <= 10; i++) { J b = MakeJet(i, 0, 5); J c = pow(a, b); + SCOPED_TRACE(DescribePow(a, b, c)); - EXPECT_TRUE(AreAlmostEqual(c.a, pow(-1.5, i), kTolerance)) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_TRUE(isfinite(c.v[0])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[1])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_TRUE( - AreAlmostEqual(c.v[0], i * pow(-1.5, i - 1) * 3.0, kTolerance)) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; + EXPECT_THAT(c.a, RelativelyNear(pow(-1.5, i), kTolerance)); + EXPECT_TRUE(isfinite(c.v[0])); + EXPECT_FALSE(isfinite(c.v[1])); + EXPECT_THAT(c.v[0], + RelativelyNear(i * pow(-1.5, i - 1) * 3.0, kTolerance)); } } @@ -550,12 +499,10 @@ J a = MakeJet(-1.5, 3, 4); J b = MakeJet(-2.5, 0, 5); J c = pow(a, b); - EXPECT_FALSE(isfinite(c.a)) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[0])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[1])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; + SCOPED_TRACE(DescribePow(a, b, c)); + EXPECT_FALSE(isfinite(c.a)); + EXPECT_FALSE(isfinite(c.v[0])); + EXPECT_FALSE(isfinite(c.v[1])); } // pow(0,y) == 0 for y == 2, with the second argument a Jet. @@ -567,12 +514,11 @@ for (int i = -10; i <= 10; i++) { J b = MakeJet(i, 3, 0); J c = pow(a, b); - ExpectClose(c.a, pow(-1.5, i), kTolerance); - EXPECT_FALSE(isfinite(c.v[0])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_TRUE(isfinite(c.v[1])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - ExpectClose(c.v[1], 0, kTolerance); + SCOPED_TRACE(DescribePow(a, b, c)); + EXPECT_THAT(c.a, RelativelyNear(pow(-1.5, i), kTolerance)); + EXPECT_FALSE(isfinite(c.v[0])); + EXPECT_TRUE(isfinite(c.v[1])); + EXPECT_THAT(c.v[1], RelativelyNear(0.0, kTolerance)); } } @@ -581,12 +527,10 @@ double a = -1.5; J b = MakeJet(-3.14, 3, 0); J c = pow(a, b); - EXPECT_FALSE(isfinite(c.a)) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[0])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; - EXPECT_FALSE(isfinite(c.v[1])) - << "\na: " << a << "\nb: " << b << "\na^b: " << c; + SCOPED_TRACE(DescribePow(a, b, c)); + EXPECT_FALSE(isfinite(c.a)); + EXPECT_FALSE(isfinite(c.v[0])); + EXPECT_FALSE(isfinite(c.v[1])); } } @@ -806,7 +750,7 @@ } TEST(Jet, FmaxJetWithJet) { - Fenv env; + const ScopedFloatEnvironment float_environment_scope; // Clear all exceptions to ensure none are set by the following function // calls. std::feclearexcept(FE_ALL_EXCEPT); @@ -831,7 +775,7 @@ } TEST(Jet, FmaxJetWithScalar) { - Fenv env; + const ScopedFloatEnvironment float_environment_scope; // Clear all exceptions to ensure none are set by the following function // calls. std::feclearexcept(FE_ALL_EXCEPT); @@ -861,7 +805,7 @@ } TEST(Jet, FminJetWithJet) { - Fenv env; + const ScopedFloatEnvironment float_environment_scope; // Clear all exceptions to ensure none are set by the following function // calls. std::feclearexcept(FE_ALL_EXCEPT); @@ -886,7 +830,7 @@ } TEST(Jet, FminJetWithScalar) { - Fenv env; + const ScopedFloatEnvironment float_environment_scope; // Clear all exceptions to ensure none are set by the following function // calls. std::feclearexcept(FE_ALL_EXCEPT); @@ -916,7 +860,7 @@ } TEST(Jet, Fdim) { - Fenv env; + const ScopedFloatEnvironment float_environment_scope; // Clear all exceptions to ensure none are set by the following function // calls. std::feclearexcept(FE_ALL_EXCEPT); @@ -999,26 +943,22 @@ { // copysign(+0, +0) J z = copysign(MakeJet(+0, 1, 2), J{+0}); EXPECT_FALSE(std::signbit(z.a)) << z; - EXPECT_TRUE(isnan(z.v[0])) << z; - EXPECT_TRUE(isnan(z.v[1])) << z; + EXPECT_THAT(absl::MakeConstSpan(z.v), Each(IsNan())) << z; } { // copysign(+0, -0) J z = copysign(MakeJet(+0, 1, 2), J{-0}); EXPECT_FALSE(std::signbit(z.a)) << z; - EXPECT_TRUE(isnan(z.v[0])) << z; - EXPECT_TRUE(isnan(z.v[1])) << z; + EXPECT_THAT(absl::MakeConstSpan(z.v), Each(IsNan())) << z; } { // copysign(-0, +0) J z = copysign(MakeJet(-0, 1, 2), J{+0}); EXPECT_FALSE(std::signbit(z.a)) << z; - EXPECT_TRUE(isnan(z.v[0])) << z; - EXPECT_TRUE(isnan(z.v[1])) << z; + EXPECT_THAT(absl::MakeConstSpan(z.v), Each(IsNan())) << z; } { // copysign(-0, -0) J z = copysign(MakeJet(-0, 1, 2), J{-0}); EXPECT_FALSE(std::signbit(z.a)) << z; - EXPECT_TRUE(isnan(z.v[0])) << z; - EXPECT_TRUE(isnan(z.v[1])) << z; + EXPECT_THAT(absl::MakeConstSpan(z.v), Each(IsNan())) << z; } { // copysign(1, -nan) J z = copysign(MakeJet(1, 2, 3), @@ -1395,17 +1335,17 @@ JJJ y = x * x * x; - ExpectClose(y.a.a.a, 1, kTolerance); - ExpectClose(y.v[0].a.a, 3., kTolerance); - ExpectClose(y.v[0].v[0].a, 6., kTolerance); - ExpectClose(y.v[0].v[0].v[0], 6., kTolerance); + EXPECT_THAT(y.a.a.a, RelativelyNear(1.0, kTolerance)); + EXPECT_THAT(y.v[0].a.a, RelativelyNear(3., kTolerance)); + EXPECT_THAT(y.v[0].v[0].a, RelativelyNear(6., kTolerance)); + EXPECT_THAT(y.v[0].v[0].v[0], RelativelyNear(6., kTolerance)); JJJ e = exp(x); - ExpectClose(e.a.a.a, kE, kTolerance); - ExpectClose(e.v[0].a.a, kE, kTolerance); - ExpectClose(e.v[0].v[0].a, kE, kTolerance); - ExpectClose(e.v[0].v[0].v[0], kE, kTolerance); + EXPECT_THAT(e.a.a.a, RelativelyNear(kE, kTolerance)); + EXPECT_THAT(e.v[0].a.a, RelativelyNear(kE, kTolerance)); + EXPECT_THAT(e.v[0].v[0].a, RelativelyNear(kE, kTolerance)); + EXPECT_THAT(e.v[0].v[0].v[0], RelativelyNear(kE, kTolerance)); } using Types = testing::Types<std::int16_t,
diff --git a/internal/ceres/numeric_diff_test_utils.cc b/internal/ceres/numeric_diff_test_utils.cc index 4c1b2e2..6e2ba09 100644 --- a/internal/ceres/numeric_diff_test_utils.cc +++ b/internal/ceres/numeric_diff_test_utils.cc
@@ -36,13 +36,18 @@ #include <algorithm> #include <cmath> +#include "absl/strings/str_format.h" #include "ceres/cost_function.h" #include "ceres/test_util.h" #include "ceres/types.h" +#include "gmock/gmock.h" #include "gtest/gtest.h" namespace ceres::internal { +using ::testing::ElementsAreArray; +using ::testing::Pointwise; + bool EasyFunctor::operator()(const double* x1, const double* x2, double* residuals) const { @@ -76,9 +81,7 @@ double expected_residuals[3]; EasyFunctor functor; functor(x1, x2, expected_residuals); - EXPECT_EQ(expected_residuals[0], residuals[0]); - EXPECT_EQ(expected_residuals[1], residuals[1]); - EXPECT_EQ(expected_residuals[2], residuals[2]); + EXPECT_THAT(residuals, ElementsAreArray(expected_residuals)); double tolerance = 0.0; switch (method) { @@ -96,16 +99,21 @@ break; } + double expected_dydx1[15]; + double expected_dydx2[15]; for (int i = 0; i < 5; ++i) { // clang-format off - ExpectClose(x2[i], dydx1[5 * 0 + i], tolerance); // y1 - ExpectClose(x1[i], dydx2[5 * 0 + i], tolerance); - ExpectClose(2 * x2[i] * residuals[0], dydx1[5 * 1 + i], tolerance); // y2 - ExpectClose(2 * x1[i] * residuals[0], dydx2[5 * 1 + i], tolerance); - ExpectClose(0.0, dydx1[5 * 2 + i], tolerance); // y3 - ExpectClose(2 * x2[i], dydx2[5 * 2 + i], tolerance); + expected_dydx1[5 * 0 + i] = x2[i]; // y1 + expected_dydx2[5 * 0 + i] = x1[i]; + expected_dydx1[5 * 1 + i] = 2 * x2[i] * residuals[0]; // y2 + expected_dydx2[5 * 1 + i] = 2 * x1[i] * residuals[0]; + expected_dydx1[5 * 2 + i] = 0.0; // y3 + expected_dydx2[5 * 2 + i] = 2 * x2[i]; // clang-format on } + + EXPECT_THAT(dydx1, Pointwise(RelativelyNear(tolerance), expected_dydx1)); + EXPECT_THAT(dydx2, Pointwise(RelativelyNear(tolerance), expected_dydx2)); } bool TranscendentalFunctor::operator()(const double* x1, @@ -151,6 +159,9 @@ // clang-format on for (auto& test : kTests) { + SCOPED_TRACE(absl::StrFormat("x1 = %s, x2 = %s", + ::testing::PrintToString(test.x1), + ::testing::PrintToString(test.x2))); double* x1 = &(test.x1[0]); double* x2 = &(test.x2[0]); double* parameters[] = {x1, x2}; @@ -184,14 +195,19 @@ break; } + double expected_dydx1[10]; + double expected_dydx2[10]; for (int i = 0; i < 5; ++i) { // clang-format off - ExpectClose( x2[i] * cos(x1x2), dydx1[5 * 0 + i], tolerance); - ExpectClose( x1[i] * cos(x1x2), dydx2[5 * 0 + i], tolerance); - ExpectClose(-x2[i] * exp(-x1x2 / 10.) / 10., dydx1[5 * 1 + i], tolerance); - ExpectClose(-x1[i] * exp(-x1x2 / 10.) / 10., dydx2[5 * 1 + i], tolerance); + expected_dydx1[5 * 0 + i] = x2[i] * cos(x1x2); + expected_dydx2[5 * 0 + i] = x1[i] * cos(x1x2); + expected_dydx1[5 * 1 + i] = -x2[i] * exp(-x1x2 / 10.) / 10.; + expected_dydx2[5 * 1 + i] = -x1[i] * exp(-x1x2 / 10.) / 10.; // clang-format on } + + EXPECT_THAT(dydx1, Pointwise(RelativelyNear(tolerance), expected_dydx1)); + EXPECT_THAT(dydx2, Pointwise(RelativelyNear(tolerance), expected_dydx2)); } } @@ -209,6 +225,7 @@ const double kTolerance = 2e-14; for (double& test : kTests) { + SCOPED_TRACE(absl::StrFormat("x = %v", test)); double* parameters[] = {&test}; double dydx; double* jacobians[1] = {&dydx}; @@ -220,10 +237,10 @@ double expected_result = exp(test); // Expect residual to be close to exp(x). - ExpectClose(residual, expected_result, kTolerance); + EXPECT_THAT(residual, RelativelyNear(expected_result, kTolerance)); // Check evaluated differences. dydx should also be close to exp(x). - ExpectClose(dydx, expected_result, kTolerance); + EXPECT_THAT(dydx, RelativelyNear(expected_result, kTolerance)); } } @@ -240,6 +257,7 @@ const double kTolerance = 2e-4; for (double& test : kTests) { + SCOPED_TRACE(absl::StrFormat("x = %v", test)); double* parameters[] = {&test}; double dydx; double* jacobians[1] = {&dydx}; @@ -249,10 +267,10 @@ cost_function.Evaluate(¶meters[0], &residual, &jacobians[0])); // Expect residual to be close to x^2 w.r.t. noise factor. - ExpectClose(residual, test * test, noise_factor_); + EXPECT_THAT(residual, RelativelyNear(test * test, noise_factor_)); // Check evaluated differences. (dy/dx = ~2x) - ExpectClose(dydx, 2 * test, kTolerance); + EXPECT_THAT(dydx, RelativelyNear(2 * test, kTolerance)); } }
diff --git a/internal/ceres/polynomial_test.cc b/internal/ceres/polynomial_test.cc index b00bf2c..a4e1a27 100644 --- a/internal/ceres/polynomial_test.cc +++ b/internal/ceres/polynomial_test.cc
@@ -37,14 +37,19 @@ #include <limits> #include <vector> +#include "absl/types/span.h" +#include "ceres/eigen.h" #include "ceres/function_sample.h" #include "ceres/test_util.h" +#include "gmock/gmock.h" #include "gtest/gtest.h" namespace ceres::internal { namespace { +using ::testing::UnorderedElementsAre; + // For IEEE-754 doubles, machine precision is about 2e-16. const double kEpsilon = 1e-13; const double kEpsilonLoose = 1e-9; @@ -102,18 +107,17 @@ } Vector* const real_ptr = use_real ? &real : nullptr; Vector* const imaginary_ptr = use_imaginary ? &imaginary : nullptr; - bool success = FindPolynomialRoots(poly, real_ptr, imaginary_ptr); + ASSERT_TRUE(FindPolynomialRoots(poly, real_ptr, imaginary_ptr)); - EXPECT_EQ(success, true); if (use_real) { - EXPECT_EQ(real.size(), N); real = SortVector(real); - ExpectArraysClose(N, real.data(), real_roots, epsilon); + EXPECT_THAT(real, + MatrixPointwise(RelativelyNear(epsilon), + ConstVectorRef(real_roots, N))); } if (use_imaginary) { - EXPECT_EQ(imaginary.size(), N); - const Vector zeros = Vector::Zero(N); - ExpectArraysClose(N, imaginary.data(), zeros.data(), epsilon); + EXPECT_THAT(imaginary, + MatrixPointwise(RelativelyNear(epsilon), Vector::Zero(N))); } } } // namespace @@ -124,18 +128,15 @@ Vector poly(0, 1); Vector real; Vector imag; - bool success = FindPolynomialRoots(poly, &real, &imag); - - EXPECT_EQ(success, false); + EXPECT_FALSE(FindPolynomialRoots(poly, &real, &imag)); } TEST(Polynomial, ConstantPolynomialReturnsNoRoots) { Vector poly = ConstantPolynomial(1.23); Vector real; Vector imag; - bool success = FindPolynomialRoots(poly, &real, &imag); + ASSERT_TRUE(FindPolynomialRoots(poly, &real, &imag)); - EXPECT_EQ(success, true); EXPECT_EQ(real.size(), 0); EXPECT_EQ(imag.size(), 0); } @@ -176,16 +177,15 @@ Vector poly = ConstantPolynomial(1.23); poly = AddComplexRootPair(poly, 42.42, 4.2); - bool success = FindPolynomialRoots(poly, &real, &imag); + ASSERT_TRUE(FindPolynomialRoots(poly, &real, &imag)); - EXPECT_EQ(success, true); - EXPECT_EQ(real.size(), 2); - EXPECT_EQ(imag.size(), 2); - ExpectClose(real(0), 42.42, kEpsilon); - ExpectClose(real(1), 42.42, kEpsilon); - ExpectClose(std::abs(imag(0)), 4.2, kEpsilon); - ExpectClose(std::abs(imag(1)), 4.2, kEpsilon); - ExpectClose(std::abs(imag(0) + imag(1)), 0.0, kEpsilon); + EXPECT_THAT( + real, + MatrixPointwise(RelativelyNear(kEpsilon), Eigen::Vector2d(42.42, 42.42))); + // The complex roots form a conjugate pair. + EXPECT_THAT(absl::MakeConstSpan(imag), + UnorderedElementsAre(RelativelyNear(4.2, kEpsilon), + RelativelyNear(-4.2, kEpsilon))); } TEST(Polynomial, QuarticPolynomialWorks) { @@ -234,8 +234,7 @@ Vector polynomial(1); polynomial(0) = 1.0; const Vector derivative = DifferentiatePolynomial(polynomial); - EXPECT_EQ(derivative.rows(), 1); - EXPECT_EQ(derivative(0), 0); + EXPECT_THAT(derivative, MatrixEq(Vector::Zero(1))); } TEST(Polynomial, DifferentiateQuadraticPolynomial) { @@ -246,9 +245,7 @@ polynomial(2) = 3.0; const Vector derivative = DifferentiatePolynomial(polynomial); - EXPECT_EQ(derivative.rows(), 2); - EXPECT_EQ(derivative(0), 2.0); - EXPECT_EQ(derivative(1), 2.0); + EXPECT_THAT(derivative, MatrixEq(Eigen::Vector2d(2.0, 2.0))); } TEST(Polynomial, MinimizeConstantPolynomial) { @@ -314,7 +311,7 @@ EXPECT_EQ(optimal_value, 0.0); } -TEST(Polymomial, ConstantInterpolatingPolynomial) { +TEST(Polynomial, ConstantInterpolatingPolynomial) { // p(x) = 1.0 Vector true_polynomial(1); true_polynomial << 1.0; @@ -327,7 +324,7 @@ samples.push_back(sample); const Vector polynomial = FindInterpolatingPolynomial(samples); - EXPECT_NEAR((true_polynomial - polynomial).norm(), 0.0, 1e-15); + EXPECT_THAT(polynomial, NormNear(true_polynomial, 1e-15)); } TEST(Polynomial, LinearInterpolatingPolynomial) { @@ -345,7 +342,7 @@ samples.push_back(sample); const Vector polynomial = FindInterpolatingPolynomial(samples); - EXPECT_NEAR((true_polynomial - polynomial).norm(), 0.0, 1e-15); + EXPECT_THAT(polynomial, NormNear(true_polynomial, 1e-15)); } TEST(Polynomial, QuadraticInterpolatingPolynomial) { @@ -373,7 +370,7 @@ } Vector polynomial = FindInterpolatingPolynomial(samples); - EXPECT_NEAR((true_polynomial - polynomial).norm(), 0.0, 1e-15); + EXPECT_THAT(polynomial, NormNear(true_polynomial, 1e-15)); } TEST(Polynomial, DeficientCubicInterpolatingPolynomial) { @@ -403,7 +400,7 @@ } const Vector polynomial = FindInterpolatingPolynomial(samples); - EXPECT_NEAR((true_polynomial - polynomial).norm(), 0.0, 1e-14); + EXPECT_THAT(polynomial, NormNear(true_polynomial, 1e-14)); } TEST(Polynomial, CubicInterpolatingPolynomialFromValues) { @@ -445,7 +442,7 @@ } const Vector polynomial = FindInterpolatingPolynomial(samples); - EXPECT_NEAR((true_polynomial - polynomial).norm(), 0.0, 1e-14); + EXPECT_THAT(polynomial, NormNear(true_polynomial, 1e-14)); } TEST(Polynomial, CubicInterpolatingPolynomialFromValuesAndOneGradient) { @@ -482,7 +479,7 @@ } const Vector polynomial = FindInterpolatingPolynomial(samples); - EXPECT_NEAR((true_polynomial - polynomial).norm(), 0.0, 1e-14); + EXPECT_THAT(polynomial, NormNear(true_polynomial, 1e-14)); } TEST(Polynomial, CubicInterpolatingPolynomialFromValuesAndGradients) { @@ -513,7 +510,7 @@ } const Vector polynomial = FindInterpolatingPolynomial(samples); - EXPECT_NEAR((true_polynomial - polynomial).norm(), 0.0, 1e-14); + EXPECT_THAT(polynomial, NormNear(true_polynomial, 1e-14)); } } // namespace ceres::internal
diff --git a/internal/ceres/rotation_test.cc b/internal/ceres/rotation_test.cc index a4cfdee..fe9674a 100644 --- a/internal/ceres/rotation_test.cc +++ b/internal/ceres/rotation_test.cc
@@ -42,11 +42,11 @@ #include "Eigen/Core" #include "absl/log/log.h" #include "absl/strings/str_format.h" +#include "absl/types/span.h" #include "ceres/constants.h" #include "ceres/eigen.h" #include "ceres/internal/euler_angles.h" #include "ceres/internal/export.h" -#include "ceres/is_close.h" #include "ceres/jet.h" #include "ceres/test_util.h" #include "gmock/gmock.h" @@ -55,6 +55,10 @@ namespace ceres { namespace internal { +using ::testing::DoubleNear; +using ::testing::ElementsAreArray; +using ::testing::Pointwise; + inline constexpr double kPi = constants::pi; // A tolerance value for floating-point comparisons. @@ -980,48 +984,6 @@ } // namespace -// Use EXPECT_THAT(x, testing::PointWise(JetClose(prec), y); to achieve Jet -// array comparison -MATCHER_P(JetClose, relative_precision, "") { - using internal::IsClose; - using LHSJetType = std::remove_reference_t<std::tuple_element_t<0, arg_type>>; - using RHSJetType = std::remove_reference_t<std::tuple_element_t<1, arg_type>>; - - constexpr int kDualPartDimension = LHSJetType::DIMENSION; - static_assert( - kDualPartDimension == RHSJetType::DIMENSION, - "Can only compare Jets with dual parts having equal dimensions"); - auto&& [x, y] = arg; - double relative_error; - double absolute_error; - if (!IsClose( - x.a, y.a, relative_precision, &relative_error, &absolute_error)) { - *result_listener << "Real part mismatch: x.a = " << x.a - << " and y.a = " << y.a - << " where the relative error between them is " - << relative_error - << " and the absolute error between them is " - << absolute_error; - return false; - } - for (int i = 0; i < kDualPartDimension; i++) { - if (!IsClose(x.v[i], - y.v[i], - relative_precision, - &relative_error, - &absolute_error)) { - *result_listener << "Dual part mismatch: x.v[" << i << "] = " << x.v[i] - << " and y.v[" << i << "] = " << y.v[i] - << " where the relative error between them is " - << relative_error - << " and the absolute error between them is " - << absolute_error; - return false; - } - } - return true; -} - // Log-10 of a value well below machine precision. static const int kSmallTinyCutoff = static_cast<int>( 2 * log(std::numeric_limits<double>::epsilon()) / log(10.0)); @@ -1045,7 +1007,8 @@ MakeJ3(0, 0, sin(theta / 2) / theta, 0), MakeJ3(0, 0, 0, sin(theta / 2) / theta)); AngleAxisToQuaternion<Order>(axis_angle, quaternion); - EXPECT_THAT(quaternion, testing::Pointwise(JetClose(kTolerance), expected)); + EXPECT_THAT(quaternion, + testing::Pointwise(RelativelyNear(kTolerance), expected)); } } @@ -1067,7 +1030,8 @@ MakeJ3(0, 0, 0.5, 0), MakeJ3(0, 0, 0, 0.5)); AngleAxisToQuaternion<Order>(axis_angle, quaternion); - EXPECT_THAT(quaternion, testing::Pointwise(JetClose(kTolerance), expected)); + EXPECT_THAT(quaternion, + testing::Pointwise(RelativelyNear(kTolerance), expected)); } } @@ -1082,7 +1046,8 @@ MakeJ3(0, 0, 0.5, 0), MakeJ3(0, 0, 0, 0.5)); AngleAxisToQuaternion<Order>(axis_angle, quaternion); - EXPECT_THAT(quaternion, testing::Pointwise(JetClose(kTolerance), expected)); + EXPECT_THAT(quaternion, + testing::Pointwise(RelativelyNear(kTolerance), expected)); } // Test that exact conversion works for small angles. @@ -1105,7 +1070,8 @@ }; // clang-format on QuaternionToAngleAxis<Order>(quaternion.data(), axis_angle); - EXPECT_THAT(axis_angle, testing::Pointwise(JetClose(kTolerance), expected)); + EXPECT_THAT(axis_angle, + testing::Pointwise(RelativelyNear(kTolerance), expected)); } } @@ -1132,7 +1098,8 @@ }; // clang-format on QuaternionToAngleAxis<Order>(quaternion.data(), axis_angle); - EXPECT_THAT(axis_angle, testing::Pointwise(JetClose(kTolerance), expected)); + EXPECT_THAT(axis_angle, + testing::Pointwise(RelativelyNear(kTolerance), expected)); } } @@ -1148,7 +1115,8 @@ MakeJ4(0, 0, 0, 0, 2.0), }; QuaternionToAngleAxis<Order>(quaternion.data(), axis_angle); - EXPECT_THAT(axis_angle, testing::Pointwise(JetClose(kTolerance), expected)); + EXPECT_THAT(axis_angle, + testing::Pointwise(RelativelyNear(kTolerance), expected)); } // The following 4 test cases cover the conversion of Euler Angles to rotation @@ -1186,7 +1154,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_euler[1], euler_angles); @@ -1206,7 +1174,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_euler[2], euler_angles); @@ -1226,7 +1194,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } } @@ -1252,7 +1220,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_euler[1], euler_angles); @@ -1272,7 +1240,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_euler[2], euler_angles); @@ -1292,7 +1260,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } } @@ -1320,7 +1288,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_euler[1], euler_angles); @@ -1340,7 +1308,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_euler[2], euler_angles); @@ -1360,7 +1328,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } } @@ -1386,7 +1354,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_euler[1], euler_angles); @@ -1406,7 +1374,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_euler[2], euler_angles); @@ -1426,7 +1394,7 @@ }; // clang-format on EXPECT_THAT(rotation_matrix, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } } @@ -1487,16 +1455,18 @@ // The axes of the ZXZ sequence are (2, 0, 1), i.e., R(j, k) = R(0, 1). J expected_identity[3] = {J(0.0), J(0.0), J(0.0)}; expected_identity[2].v[1] = -1.0; - EXPECT_THAT(angles, - testing::Pointwise(JetClose(kTolerance), expected_identity)); + EXPECT_THAT( + angles, + testing::Pointwise(RelativelyNear(kTolerance), expected_identity)); make_matrix(kQuarterTurnAboutY, matrix); RotationMatrixToEulerAngles<IntrinsicZYX>(matrix.data(), angles); // The axes of the ZYX sequence are (0, 1, 2), i.e., R(j, k) = R(1, 2). J expected_quarter_turn[3] = {J(0.0), J(kPi / 2), J(0.0)}; expected_quarter_turn[2].v[5] = -1.0; - EXPECT_THAT(angles, - testing::Pointwise(JetClose(kTolerance), expected_quarter_turn)); + EXPECT_THAT( + angles, + testing::Pointwise(RelativelyNear(kTolerance), expected_quarter_turn)); } // Differentiating the norm at gimbal lock divides zero by zero, even if the @@ -1545,7 +1515,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_matrices[1], rotation_matrix); @@ -1559,7 +1529,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_matrices[2], rotation_matrix); @@ -1573,7 +1543,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } } @@ -1593,7 +1563,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_matrices[1], rotation_matrix); @@ -1607,7 +1577,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_matrices[2], rotation_matrix); @@ -1621,7 +1591,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } } @@ -1644,7 +1614,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_matrices[1], rotation_matrix); @@ -1658,7 +1628,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_matrices[2], rotation_matrix); @@ -1672,7 +1642,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } } @@ -1692,7 +1662,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_matrices[1], rotation_matrix); @@ -1706,7 +1676,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } ArrayToArrayOfJets(sample_matrices[2], rotation_matrix); @@ -1720,7 +1690,7 @@ }; // clang-format on EXPECT_THAT(euler_angles, - testing::Pointwise(JetClose(kLooseTolerance), expected)); + testing::Pointwise(RelativelyNear(kLooseTolerance), expected)); } } @@ -1747,11 +1717,15 @@ // Compute R from q and compare to known answer. double Rq[3][3]; QuaternionToScaledRotation<Order>(q.data(), Rq[0]); - ExpectArraysClose(9, Q[0], Rq[0], kTolerance); + EXPECT_THAT( + absl::MakeConstSpan(Rq[0], 9), + Pointwise(RelativelyNear(kTolerance), absl::MakeConstSpan(Q[0], 9))); // Now do the same but compute R with normalization. QuaternionToRotation<Order>(q.data(), Rq[0]); - ExpectArraysClose(9, R[0], Rq[0], kTolerance); + EXPECT_THAT( + absl::MakeConstSpan(Rq[0], 9), + Pointwise(RelativelyNear(kTolerance), absl::MakeConstSpan(R[0], 9))); } TEST(Quaternion, RotatePointGivesSameAnswerForDifferentQuaternionOrders) { @@ -1776,7 +1750,7 @@ double result2[3]; QuaternionRotatePoint<EigenQuaternionOrder>(q2.data(), p, result2); - ExpectArraysClose(3, result1, result2, kTolerance); + EXPECT_THAT(result1, Pointwise(RelativelyNear(kTolerance), result2)); } TEST(Quaternion, RotatePointGivesSameAnswerForDifferentUnitQuaternionOrders) { @@ -1801,7 +1775,7 @@ double result2[3]; UnitQuaternionRotatePoint<EigenQuaternionOrder>(q2.data(), p, result2); - ExpectArraysClose(3, result1, result2, kTolerance); + EXPECT_THAT(result1, Pointwise(RelativelyNear(kTolerance), result2)); } TYPED_TEST(QuaternionTest, RotatePointGivesSameAnswerAsRotationByMatrix) { @@ -1825,7 +1799,7 @@ double result2[3]; VectorRef(result2, 3) = ConstMatrixRef(R, 3, 3) * ConstVectorRef(p, 3); - ExpectArraysClose(3, result1, result2, kTolerance); + EXPECT_THAT(result1, Pointwise(RelativelyNear(kTolerance), result2)); } // Verify that (a * b) * c == a * (b * c).
diff --git a/internal/ceres/test_util.cc b/internal/ceres/test_util.cc index 0416b93..a2743b8 100644 --- a/internal/ceres/test_util.cc +++ b/internal/ceres/test_util.cc
@@ -44,8 +44,6 @@ #include <utility> #include "Eigen/Cholesky" -#include "absl/log/check.h" -#include "absl/log/log.h" #include "absl/strings/str_format.h" #include "ceres/file.h" #include "ceres/is_close.h" @@ -63,88 +61,6 @@ namespace ceres { namespace internal { -bool ExpectClose(double x, double y, double max_abs_relative_difference) { - if (std::isinf(x) && std::isinf(y)) { - EXPECT_EQ(std::signbit(x), std::signbit(y)); - return true; - } - - if (std::isnan(x) && std::isnan(y)) { - return true; - } - - double absolute_difference = fabs(x - y); - double relative_difference; - if (std::fpclassify(x) == FP_ZERO || std::fpclassify(y) == FP_ZERO) { - // If x or y is exactly zero, then relative difference doesn't have any - // meaning. Take the absolute difference instead. - relative_difference = absolute_difference; - } else { - relative_difference = - absolute_difference / std::max(std::fabs(x), std::fabs(y)); - } - if (relative_difference > max_abs_relative_difference) { - VLOG(1) << absl::StrFormat("x=%17g y=%17g abs=%17g rel=%17g", - x, - y, - absolute_difference, - relative_difference); - } - - EXPECT_NEAR(relative_difference, 0.0, max_abs_relative_difference); - return relative_difference <= max_abs_relative_difference; -} - -void ExpectArraysCloseUptoScale(int n, - const double* p, - const double* q, - double tol) { - CHECK_GT(n, 0); - CHECK(p); - CHECK(q); - - double p_max = 0; - double q_max = 0; - int p_i = 0; - int q_i = 0; - - for (int i = 0; i < n; ++i) { - if (std::abs(p[i]) > p_max) { - p_max = std::abs(p[i]); - p_i = i; - } - if (std::abs(q[i]) > q_max) { - q_max = std::abs(q[i]); - q_i = i; - } - } - - // If both arrays are all zeros, they are equal up to scale, but - // for testing purposes, that's more likely to be an error than - // a desired result. - CHECK_NE(p_max, 0.0); - CHECK_NE(q_max, 0.0); - - for (int i = 0; i < n; ++i) { - double p_norm = p[i] / p[p_i]; - double q_norm = q[i] / q[q_i]; - - EXPECT_NEAR(p_norm, q_norm, tol) << "i=" << i; - } -} - -void ExpectArraysClose(int n, const double* p, const double* q, double tol) { - CHECK_GT(n, 0); - CHECK(p); - CHECK(q); - - for (int i = 0; i < n; ++i) { - EXPECT_TRUE(ExpectClose(p[i], q[i], tol)) << "p[" << i << "]" << p[i] << " " - << "q[" << i << "]" << q[i] << " " - << "tol: " << tol; - } -} - double RelativeDifference(double actual, double expected) { if (std::isnan(actual) || std::isnan(expected)) { return std::isnan(actual) && std::isnan(expected)
diff --git a/internal/ceres/test_util.h b/internal/ceres/test_util.h index 9ccebf9..449902a 100644 --- a/internal/ceres/test_util.h +++ b/internal/ceres/test_util.h
@@ -40,7 +40,6 @@ #include <tuple> #include <vector> -#include "absl/log/check.h" #include "absl/strings/str_format.h" #include "absl/types/span.h" #include "ceres/block_structure.h" @@ -58,34 +57,6 @@ namespace ceres { namespace internal { -// Expects that x and y have a relative difference of no more than -// max_abs_relative_difference. If either x or y is zero, then the relative -// difference is interpreted as an absolute difference. -// If x and y have the same non-finite value (inf or nan) we treat them as being -// close. In such a case no error is thrown and true is returned. -CERES_NO_EXPORT bool ExpectClose(double x, - double y, - double max_abs_relative_difference); - -// Expects that for all i = 1,.., n - 1 -// -// |p[i] - q[i]| / max(|p[i]|, |q[i]|) < tolerance -CERES_NO_EXPORT void ExpectArraysClose(int n, - const double* p, - const double* q, - double tolerance); - -// Expects that for all i = 1,.., n - 1 -// -// |p[i] / max_norm_p - q[i] / max_norm_q| < tolerance -// -// where max_norm_p and max_norm_q are the max norms of the arrays p -// and q respectively. -CERES_NO_EXPORT void ExpectArraysCloseUptoScale(int n, - const double* p, - const double* q, - double tolerance); - // √2/2, i.e., the sine and cosine of π/4. Halving is exact in binary // floating-point arithmetic, so the value is correctly rounded. // @@ -425,29 +396,27 @@ protected: void SetUp() final { SystemTestProblem system_test_problem; - SolveAndEvaluateFinalResiduals( + ASSERT_NO_FATAL_FAILURE(SolveAndEvaluateFinalResiduals( *system_test_problem.mutable_solver_options(), system_test_problem.mutable_problem(), - &expected_final_residuals_); + &expected_final_residuals_)); } void RunSolverForConfigAndExpectResidualsMatch(const Solver::Options& options, Problem* problem) { std::vector<double> final_residuals; - SolveAndEvaluateFinalResiduals(options, problem, &final_residuals); + ASSERT_NO_FATAL_FAILURE( + SolveAndEvaluateFinalResiduals(options, problem, &final_residuals)); // We compare solutions by comparing their residual vectors. We do // not compare parameter vectors because it is much more brittle // and error prone to do so, since the same problem can have // nearly the same residuals at two completely different positions // in parameter space. - CHECK_EQ(expected_final_residuals_.size(), final_residuals.size()); - for (int i = 0; i < final_residuals.size(); ++i) { - EXPECT_NEAR(final_residuals[i], - expected_final_residuals_[i], - SystemTestProblem::kResidualTolerance) - << "Not close enough residual:" << i; - } + EXPECT_THAT(final_residuals, + ::testing::Pointwise(::testing::DoubleNear( + SystemTestProblem::kResidualTolerance), + expected_final_residuals_)); } void SolveAndEvaluateFinalResiduals(const Solver::Options& options, @@ -455,14 +424,14 @@ std::vector<double>* final_residuals) { Solver::Summary summary; Solve(options, problem, &summary); - CHECK_NE(summary.termination_type, ceres::FAILURE); + ASSERT_NE(summary.termination_type, ceres::FAILURE) << summary.message; EXPECT_EQ(summary.mixed_precision_solves_used, options.use_mixed_precision_solves); - CHECK(problem->Evaluate(Problem::EvaluateOptions(), - nullptr, - final_residuals, - nullptr, - nullptr)); + ASSERT_TRUE(problem->Evaluate(Problem::EvaluateOptions(), + nullptr, + final_residuals, + nullptr, + nullptr)); } std::vector<double> expected_final_residuals_;