blob: 449902a49030efbb2e8719c654e54b5e45b61a9e [file]
// Ceres Solver - A fast non-linear least squares minimizer
// Copyright 2023 Google Inc. All rights reserved.
// http://ceres-solver.org/
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Google Inc. nor the names of its contributors may be
// used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
//
// Author: keir@google.com (Keir Mierle)
#ifdef CERES_HAS_GTEST
#ifndef CERES_INTERNAL_TEST_UTIL_H_
#define CERES_INTERNAL_TEST_UTIL_H_
#include <cfenv>
#include <cmath>
#include <ostream>
#include <string>
#include <tuple>
#include <vector>
#include "absl/strings/str_format.h"
#include "absl/types/span.h"
#include "ceres/block_structure.h"
#include "ceres/compressed_row_sparse_matrix.h"
#include "ceres/eigen.h"
#include "ceres/internal/disable_warnings.h"
#include "ceres/internal/export.h"
#include "ceres/jet.h"
#include "ceres/problem.h"
#include "ceres/solver.h"
#include "ceres/sparse_matrix.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace ceres {
namespace internal {
// √2/2, i.e., the sine and cosine of π/4. Halving is exact in binary
// floating-point arithmetic, so the value is correctly rounded.
//
// The constant is computed using mpmath by the following shell command:
//
// python3 - <<EOF
// from mpmath import mp
// mp.dps = 64
// print(mp.sqrt(2) / 2)
// EOF
template <typename T>
inline constexpr T kHalfSqrt2_v(
0.707106781186547524400844362104849039284835937688474036588339869L);
inline constexpr double kHalfSqrt2 = kHalfSqrt2_v<double>;
// Saves the floating-point environment, including the raised floating-point
// exceptions and the rounding mode, and restores it on destruction, so that
// changes of the environment stay within the scope of the guard.
//
// A test that checks that a computation raises no floating-point exception
// declares the guard before clearing the exception flags, so that neither the
// cleared flags nor the flags the test raises leak into later tests:
//
// TEST(Jet, FmaxRaisesNoExceptions) {
// const ScopedFloatEnvironment scoped_float_environment;
// std::feclearexcept(FE_ALL_EXCEPT);
// EXPECT_THAT(fmax(x, nan), RelativelyNear(x, kTolerance));
// EXPECT_EQ(std::fetestexcept(FE_ALL_EXCEPT & ~FE_INEXACT), 0);
// }
//
// Code that runs inside such a test and must not raise exceptions of its own
// declares the guard at the start of its computation. RelativeDifference, and
// hence RelativelyNear, does so because computing a difference can overflow
// or underflow, which would fail the check although fmax is correct:
//
// double RelativeDifference(double actual, double expected) {
// const ScopedFloatEnvironment scoped_float_environment;
// ...
// }
class CERES_NO_EXPORT ScopedFloatEnvironment {
public:
ScopedFloatEnvironment() { std::fegetenv(&environment_); }
~ScopedFloatEnvironment() { std::fesetenv(&environment_); }
ScopedFloatEnvironment(const ScopedFloatEnvironment&) = delete;
ScopedFloatEnvironment& operator=(const ScopedFloatEnvironment&) = delete;
private:
std::fenv_t environment_;
};
// Returns the relative difference
//
// |actual - expected| / max(|actual|, |expected|).
//
// Dividing by the larger magnitude makes the difference symmetric in actual and
// expected as in ExpectClose. The exceptional cases are:
//
// - If actual or expected is zero, the result is |actual - expected|.
// - If actual and expected are the same infinity, the result is zero.
// - If actual or expected is infinite otherwise, the result is infinite.
// - If both are NaN, the result is zero, so that a NaN result can be
// expected.
// - If exactly one of them is NaN, the result is NaN, which no tolerance
// accepts.
//
// The floating-point environment of the caller is left unchanged as described
// for ScopedFloatEnvironment.
CERES_NO_EXPORT double RelativeDifference(double actual, double expected);
// Matches a double whose RelativeDifference to expected does not exceed
// tolerance. Use as
//
// EXPECT_THAT(actual, RelativelyNear(expected, tolerance));
//
// The matchers below follow the conventions of gMock. The description takes
// the negation flag only to word the expectation printed for
// Not(RelativelyNear(...)), whose result gMock inverts itself. The explanation
// is written whether or not the value matches, since gMock prints it on a
// failure of either the matcher or its negation.
MATCHER_P2(RelativelyNear,
expected,
tolerance,
absl::StrFormat("%s within a relative difference of %s of %s",
negation ? "isn't" : "is",
::testing::PrintToString(tolerance),
::testing::PrintToString(expected))) {
const double relative_difference = RelativeDifference(arg, expected);
*result_listener << "which is a relative difference of "
<< relative_difference;
return std::islessequal(relative_difference, tolerance);
}
// Matches a Jet whose scalar part and each coefficient of whose dual part are
// RelativelyNear the corresponding parts of expected. Use as
//
// EXPECT_THAT(actual, RelativelyNear(expected, tolerance));
template <typename T, int N>
::testing::Matcher<Jet<T, N>> RelativelyNear(const Jet<T, N>& expected,
double tolerance);
// Matches a 2-tuple (actual, expected) of doubles or Jets with actual
// RelativelyNear expected.
//
// gMock compares containers coefficient by coefficient with
// ::testing::Pointwise, which passes each actual coefficient together with the
// corresponding expected one to a matcher of 2-tuples, such as
// ::testing::DoubleNear(tolerance) or ::testing::Eq(). This overload is the
// relative counterpart of DoubleNear(tolerance) for this purpose and is not
// meant to be applied to a tuple directly. Use as
//
// EXPECT_THAT(actual_vector, Pointwise(RelativelyNear(tolerance), expected));
// EXPECT_THAT(actual_jets, Pointwise(RelativelyNear(tolerance), expected));
// EXPECT_THAT(actual_matrix,
// MatrixPointwise(RelativelyNear(tolerance), expected));
MATCHER_P(RelativelyNear,
tolerance,
absl::StrFormat("%s within a relative difference of %s",
negation ? "aren't" : "are",
::testing::PrintToString(tolerance))) {
return ::testing::ExplainMatchResult(
RelativelyNear(std::get<1>(arg), tolerance),
std::get<0>(arg),
result_listener);
}
// Returns the entrywise p-norm of matrix, which is the vector p-norm of its
// coefficients. For p = 2, it is the Frobenius norm and for p =
// Eigen::Infinity, the largest magnitude of a coefficient.
template <int p>
double EntrywiseNorm(const Matrix& matrix) {
static_assert(p == Eigen::Infinity || p >= 1,
"p must be positive or Eigen::Infinity");
if constexpr (p == Eigen::Infinity) {
// lpNorm<Eigen::Infinity> leaves it unspecified whether a NaN coefficient
// propagates to the norm.
return matrix.size() == 0
? 0.0
: matrix.cwiseAbs().maxCoeff<Eigen::PropagateNaN>();
} else {
return matrix.lpNorm<p>();
}
}
// Polymorphic matcher comparing an Eigen matrix or vector to the expected one
// by the entrywise p-norm of their difference. Use the NormNear and
// RelativeNormNear factory functions to create it.
class CERES_NO_EXPORT NormNearMatcher {
public:
using Norm = double (*)(const Matrix&);
NormNearMatcher(
Matrix expected, double tolerance, bool relative, int p, Norm norm);
template <typename Derived>
bool MatchAndExplain(const Eigen::DenseBase<Derived>& actual,
::testing::MatchResultListener* listener) const {
return MatchAndExplainMatrix(actual.template cast<double>(), listener);
}
void DescribeTo(std::ostream* os) const;
void DescribeNegationTo(std::ostream* os) const;
private:
bool MatchAndExplainMatrix(const Matrix& actual,
::testing::MatchResultListener* listener) const;
void Describe(std::ostream* os, bool negation) const;
Matrix expected_;
double tolerance_;
bool relative_;
int p_;
Norm norm_;
};
// Matches an Eigen matrix or vector of the same dimensions as expected with
//
// ||actual - expected||_p <= tolerance,
//
// where ||.||_p is the EntrywiseNorm<p>. A NaN coefficient in actual or
// expected yields a NaN distance, which no tolerance accepts. Use as
//
// EXPECT_THAT(x, NormNear(expected_x, tolerance));
// EXPECT_THAT(x, NormNear<Eigen::Infinity>(expected_x, tolerance));
template <int p = 2, typename Derived>
::testing::PolymorphicMatcher<NormNearMatcher> NormNear(
const Eigen::DenseBase<Derived>& expected, double tolerance) {
return ::testing::MakePolymorphicMatcher(
NormNearMatcher(expected.template cast<double>(),
tolerance,
/*relative=*/false,
p,
&EntrywiseNorm<p>));
}
// Matches an Eigen matrix or vector of the same dimensions as expected with
//
// ||actual - expected||_p <= tolerance * max(||actual||_p, ||expected||_p),
//
// where ||.||_p is the EntrywiseNorm<p>. Like RelativeDifference, the distance
// is symmetric in actual and expected and becomes absolute as in NormNear if
// either of them is zero.
template <int p = 2, typename Derived>
::testing::PolymorphicMatcher<NormNearMatcher> RelativeNormNear(
const Eigen::DenseBase<Derived>& expected, double tolerance) {
return ::testing::MakePolymorphicMatcher(
NormNearMatcher(expected.template cast<double>(),
tolerance,
/*relative=*/true,
p,
&EntrywiseNorm<p>));
}
// Polymorphic matcher comparing each coefficient of an Eigen matrix or vector
// to the corresponding coefficient of the expected one using a matcher of
// 2-tuples. Use the MatrixPointwise factory function to create it.
class CERES_NO_EXPORT MatrixPointwiseMatcher {
public:
using TupleMatcher = ::testing::Matcher<std::tuple<double, double>>;
MatrixPointwiseMatcher(TupleMatcher tuple_matcher, Matrix expected);
template <typename Derived>
bool MatchAndExplain(const Eigen::DenseBase<Derived>& actual,
::testing::MatchResultListener* listener) const {
return MatchAndExplainMatrix(actual.template cast<double>(), listener);
}
void DescribeTo(std::ostream* os) const;
void DescribeNegationTo(std::ostream* os) const;
private:
bool MatchAndExplainMatrix(const Matrix& actual,
::testing::MatchResultListener* listener) const;
TupleMatcher tuple_matcher_;
Matrix expected_;
};
// Matches a matrix of the same dimensions as expected whose coefficients and
// the corresponding expected coefficients satisfy the 2-tuple matcher. It is
// the counterpart of ::testing::Pointwise for Eigen matrices and vectors and,
// unlike Pointwise, reports the row and the column of the first mismatch. Like
// Pointwise, it takes a matcher of 2-tuples (actual, expected) so that any
// comparison of two coefficients applies, such as an absolute, a relative or an
// exact one. Use as
//
// EXPECT_THAT(actual, MatrixPointwise(DoubleNear(tolerance), expected));
// EXPECT_THAT(actual, MatrixPointwise(RelativelyNear(tolerance), expected));
template <typename TupleMatcher, typename Derived>
::testing::PolymorphicMatcher<MatrixPointwiseMatcher> MatrixPointwise(
const TupleMatcher& tuple_matcher,
const Eigen::DenseBase<Derived>& expected) {
return ::testing::MakePolymorphicMatcher(MatrixPointwiseMatcher(
::testing::MatcherCast<std::tuple<double, double>>(tuple_matcher),
expected.template cast<double>()));
}
// Matches a matrix of the same dimensions as expected whose coefficients are
// equal to the corresponding expected coefficients.
template <typename Derived>
::testing::PolymorphicMatcher<MatrixPointwiseMatcher> MatrixEq(
const Eigen::DenseBase<Derived>& expected) {
return MatrixPointwise(::testing::Eq(), expected);
}
// The Jet overload of RelativelyNear is defined after MatrixPointwise, which it
// uses to compare the dual parts.
template <typename T, int N>
::testing::Matcher<Jet<T, N>> RelativelyNear(const Jet<T, N>& expected,
double tolerance) {
return ::testing::AllOf(
::testing::Field(
"a", &Jet<T, N>::a, RelativelyNear(expected.a, tolerance)),
::testing::Field("v",
&Jet<T, N>::v,
MatrixPointwise(RelativelyNear(tolerance), expected.v)));
}
// Returns the dense matrix whose columns are the products of m and the
// columns of the identity matrix computed by RightMultiplyAndAccumulate.
CERES_NO_EXPORT Matrix RightMultiplyByIdentity(const SparseMatrix& m);
// Solves the linear system whose symmetric matrix is given by the triangular
// part stored in lhs using a dense Cholesky factorization. Returns false if
// the factorization fails.
CERES_NO_EXPORT bool SolveUsingDenseCholesky(
const CompressedRowSparseMatrix& lhs, const Vector& rhs, Vector* solution);
// Prints a Block in assertion failure messages.
inline void PrintTo(const Block& block, std::ostream* os) {
*os << absl::StrFormat(
"Block(size=%d, position=%d)", block.size, block.position);
}
// Matches a CompressedRowSparseMatrix whose row offsets, column indices and
// values are equal to the given containers.
template <typename Rows, typename Cols, typename Values>
auto CompressedRowsAre(const Rows& rows,
const Cols& cols,
const Values& values) {
using ::testing::ElementsAreArray;
using ::testing::ResultOf;
return ::testing::AllOf(
ResultOf(
"row offsets",
[](const CompressedRowSparseMatrix& m) {
return absl::MakeConstSpan(m.rows(), m.num_rows() + 1);
},
ElementsAreArray(rows)),
ResultOf(
"column indices",
[](const CompressedRowSparseMatrix& m) {
return absl::MakeConstSpan(m.cols(), m.num_nonzeros());
},
ElementsAreArray(cols)),
ResultOf(
"values",
[](const CompressedRowSparseMatrix& m) {
return absl::MakeConstSpan(m.values(), m.num_nonzeros());
},
ElementsAreArray(values)));
}
// Construct a fully qualified path for the test file depending on the
// local build/testing environment.
CERES_NO_EXPORT std::string TestFileAbsolutePath(const std::string& filename);
// A templated test fixture, that is used for testing Ceres end to end
// by computing a solution to the problem for a given solver
// configuration and comparing it to a reference solver configuration.
//
// It is assumed that the SystemTestProblem has an Solver::Options
// struct that contains the reference Solver configuration.
template <typename SystemTestProblem>
class CERES_NO_EXPORT SystemTest : public ::testing::Test {
protected:
void SetUp() final {
SystemTestProblem system_test_problem;
ASSERT_NO_FATAL_FAILURE(SolveAndEvaluateFinalResiduals(
*system_test_problem.mutable_solver_options(),
system_test_problem.mutable_problem(),
&expected_final_residuals_));
}
void RunSolverForConfigAndExpectResidualsMatch(const Solver::Options& options,
Problem* problem) {
std::vector<double> 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.
EXPECT_THAT(final_residuals,
::testing::Pointwise(::testing::DoubleNear(
SystemTestProblem::kResidualTolerance),
expected_final_residuals_));
}
void SolveAndEvaluateFinalResiduals(const Solver::Options& options,
Problem* problem,
std::vector<double>* final_residuals) {
Solver::Summary summary;
Solve(options, problem, &summary);
ASSERT_NE(summary.termination_type, ceres::FAILURE) << summary.message;
EXPECT_EQ(summary.mixed_precision_solves_used,
options.use_mixed_precision_solves);
ASSERT_TRUE(problem->Evaluate(Problem::EvaluateOptions(),
nullptr,
final_residuals,
nullptr,
nullptr));
}
std::vector<double> expected_final_residuals_;
};
} // namespace internal
} // namespace ceres
#include "ceres/internal/reenable_warnings.h"
#endif // CERES_INTERNAL_TEST_UTIL_H_
#endif // CERES_HAS_GTEST