Add SphereManifold.

This MR adds SphereManifold ported from
HomogeneousVectorParameterization. Additionally the minus operator
and jacobian evaluation was implemented.

The unit tests were almost completly reimplemented and uses the
test facilities provided for manifolds.

Change-Id: Iccf72a2333bc921ff24c4d831db35020c653ee86
diff --git a/include/ceres/internal/householder_vector.h b/include/ceres/internal/householder_vector.h
index 55f68e5..e5fc9bf 100644
--- a/include/ceres/internal/householder_vector.h
+++ b/include/ceres/internal/householder_vector.h
@@ -82,6 +82,14 @@
   v->head(v->rows() - 1) /= v_pivot;
 }
 
+template <typename XVectorType, typename Scalar, int N>
+Eigen::Matrix<Scalar, N, 1> ApplyHouseholderVector(
+    const XVectorType& y,
+    const Eigen::Matrix<Scalar, N, 1>& v,
+    const Scalar& beta) {
+  return (y - v * (beta * (v.transpose() * y)));
+}
+
 }  // namespace internal
 }  // namespace ceres
 
diff --git a/include/ceres/internal/sphere_manifold.h b/include/ceres/internal/sphere_manifold.h
new file mode 100644
index 0000000..c29fbcc
--- /dev/null
+++ b/include/ceres/internal/sphere_manifold.h
@@ -0,0 +1,186 @@
+// Ceres Solver - A fast non-linear least squares minimizer
+// Copyright 2022 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: vitus@google.com (Mike Vitus)
+//         jodebo_beck@gmx.de (Johannes Beck)
+
+#include "ceres/internal/householder_vector.h"
+
+namespace ceres {
+
+template <int AmbientSpaceDimension>
+SphereManifold<AmbientSpaceDimension>::SphereManifold()
+    : size_{AmbientSpaceDimension} {
+  static_assert(
+      AmbientSpaceDimension != Eigen::Dynamic,
+      "The size is set to dynamic. Please call the constructor with a size.");
+}
+
+template <int AmbientSpaceDimension>
+SphereManifold<AmbientSpaceDimension>::SphereManifold(int size) : size_{size} {
+  if (AmbientSpaceDimension != Eigen::Dynamic) {
+    CHECK_EQ(AmbientSpaceDimension, size)
+        << "Specified size by template parameter differs from the supplied "
+           "one.";
+  } else {
+    CHECK_GT(size_, 1)
+        << "The size of the manifold needs to be greater than 1.";
+  }
+}
+
+template <int AmbientSpaceDimension>
+bool SphereManifold<AmbientSpaceDimension>::Plus(
+    const double* x_ptr,
+    const double* delta_ptr,
+    double* x_plus_delta_ptr) const {
+  Eigen::Map<const AmbientVector> x(x_ptr, size_);
+  Eigen::Map<const TangentVector> delta(delta_ptr, size_ - 1);
+  Eigen::Map<AmbientVector> x_plus_delta(x_plus_delta_ptr, size_);
+
+  const double norm_delta = delta.norm();
+
+  if (norm_delta == 0.0) {
+    x_plus_delta = x;
+    return true;
+  }
+
+  // Map the delta from the minimum representation to the over parameterized
+  // homogeneous vector. See B.2 p.25 equation (106) - (107) for more details.
+  const double norm_delta_div_2 = 0.5 * norm_delta;
+  const double sin_delta_by_delta =
+      std::sin(norm_delta_div_2) / norm_delta_div_2;
+
+  AmbientVector y(size_);
+  y.head(size_ - 1) = 0.5 * sin_delta_by_delta * delta;
+  y(size_ - 1) = std::cos(norm_delta_div_2);
+
+  AmbientVector v(size_);
+  double beta;
+
+  // NOTE: The explicit template arguments are needed here because
+  // ComputeHouseholderVector is templated and some versions of MSVC
+  // have trouble deducing the type of v automatically.
+  internal::ComputeHouseholderVector<Eigen::Map<const AmbientVector>,
+                                     double,
+                                     AmbientSpaceDimension>(x, &v, &beta);
+
+  // Apply the delta update to remain on the sphere.
+  x_plus_delta = x.norm() * internal::ApplyHouseholderVector(y, v, beta);
+
+  return true;
+}
+
+template <int AmbientSpaceDimension>
+bool SphereManifold<AmbientSpaceDimension>::PlusJacobian(
+    const double* x_ptr, double* jacobian_ptr) const {
+  Eigen::Map<const AmbientVector> x(x_ptr, size_);
+  Eigen::Map<MatrixPlusJacobian> jacobian(jacobian_ptr, size_, size_ - 1);
+
+  AmbientVector v(size_);
+  double beta;
+
+  // NOTE: The explicit template arguments are needed here because
+  // ComputeHouseholderVector is templated and some versions of MSVC
+  // have trouble deducing the type of v automatically.
+  internal::ComputeHouseholderVector<Eigen::Map<const AmbientVector>,
+                                     double,
+                                     AmbientSpaceDimension>(x, &v, &beta);
+
+  // The Jacobian is equal to J = 0.5 * H.leftCols(size_ - 1) where H is the
+  // Householder matrix (H = I - beta * v * v').
+  for (int i = 0; i < size_ - 1; ++i) {
+    jacobian.col(i) = -0.5 * beta * v(i) * v;
+    jacobian.col(i)(i) += 0.5;
+  }
+  jacobian *= x.norm();
+
+  return true;
+}
+
+template <int AmbientSpaceDimension>
+bool SphereManifold<AmbientSpaceDimension>::Minus(const double* y_ptr,
+                                                  const double* x_ptr,
+                                                  double* y_minus_x_ptr) const {
+  AmbientVector y = Eigen::Map<const AmbientVector>(y_ptr, size_);
+  Eigen::Map<const AmbientVector> x(x_ptr, size_);
+  Eigen::Map<TangentVector> y_minus_x(y_minus_x_ptr, size_ - 1);
+
+  // Apply hoseholder transformation.
+  AmbientVector v(size_);
+  double beta;
+
+  // NOTE: The explicit template arguments are needed here because
+  // ComputeHouseholderVector is templated and some versions of MSVC
+  // have trouble deducing the type of v automatically.
+  internal::ComputeHouseholderVector<Eigen::Map<const AmbientVector>,
+                                     double,
+                                     AmbientSpaceDimension>(x, &v, &beta);
+
+  const AmbientVector hy =
+      internal::ApplyHouseholderVector(y, v, beta) / x.norm();
+
+  // Calculate y - x. See B.2 p.25 equation (108).
+  double y_last = hy[size_ - 1];
+  double hy_norm = hy.head(size_ - 1).norm();
+  if (hy_norm == 0.0) {
+    y_minus_x.setZero();
+  } else {
+    y_minus_x =
+        2.0 * std::atan2(hy_norm, y_last) / hy_norm * hy.head(size_ - 1);
+  }
+
+  return true;
+}
+
+template <int AmbientSpaceDimension>
+bool SphereManifold<AmbientSpaceDimension>::MinusJacobian(
+    const double* x_ptr, double* jacobian_ptr) const {
+  Eigen::Map<const AmbientVector> x(x_ptr, size_);
+  Eigen::Map<MatrixMinusJacobian> jacobian(jacobian_ptr, size_ - 1, size_);
+
+  AmbientVector v(size_);
+  double beta;
+
+  // NOTE: The explicit template arguments are needed here because
+  // ComputeHouseholderVector is templated and some versions of MSVC
+  // have trouble deducing the type of v automatically.
+  internal::ComputeHouseholderVector<Eigen::Map<const AmbientVector>,
+                                     double,
+                                     AmbientSpaceDimension>(x, &v, &beta);
+
+  // The Jacobian is equal to J = 2.0 * H.leftCols(size_ - 1) where H is the
+  // Householder matrix (H = I - beta * v * v').
+  for (int i = 0; i < size_ - 1; ++i) {
+    jacobian.row(i) = -2.0 * beta * v(i) * v;
+    jacobian.row(i)(i) += 2.0;
+  }
+  jacobian /= x.norm();
+
+  return true;
+}
+}  // namespace ceres
\ No newline at end of file
diff --git a/include/ceres/manifold.h b/include/ceres/manifold.h
index 85394b7..ef4b2a7 100644
--- a/include/ceres/manifold.h
+++ b/include/ceres/manifold.h
@@ -31,12 +31,14 @@
 #ifndef CERES_PUBLIC_MANIFOLD_H_
 #define CERES_PUBLIC_MANIFOLD_H_
 
+#include <Eigen/Core>
 #include <array>
 #include <memory>
 #include <vector>
 
 #include "ceres/internal/disable_warnings.h"
 #include "ceres/internal/port.h"
+#include "ceres/types.h"
 
 namespace ceres {
 
@@ -407,8 +409,87 @@
   bool MinusJacobian(const double* x, double* jacobian) const override;
 };
 
+// This provides a manifold on a sphere meaning that the norm of the vector
+// stays the same. Such cases often arises in Structure for Motion
+// problems. One example where they are used is in representing points whose
+// triangulation is ill-conditioned. Here it is advantageous to use an
+// over-parameterization since homogeneous vectors can represent points at
+// infinity.
+//
+// The plus operator is defined as
+//  Plus(x, delta) =
+//    [sin(0.5 * |delta|) * delta / |delta|, cos(0.5 * |delta|)] * x
+//
+// The minus operator is defined as
+//  Minus(x, y) = 2 atan2(nhy, y[-1]) / nhy * hy[0 : size_ - 1]
+// with nhy = norm(hy[0 : size_ - 1])
+//
+// with * defined as an operator which applies the update orthogonal to x to
+// remain on the sphere. The ambient space dimension is required to be greater
+// than 1.
+//
+// The class works with dynamic and static ambient space dimensions. If the
+// ambient space dimensions is know at compile time use
+//    SphereManifold<3> manifold;
+// If the ambient space dimensions is not known at compile time the template
+// parameter needs to be set to ceres::DYNAMIC and the actual dimension needs to
+// be provided as a constructor argument:
+//    SphereManifold<ceres::DYNAMIC> manifold(ambient_dim);
+//
+// See  section B.2 (p.25) in "Integrating Generic Sensor Fusion Algorithms with
+// Sound State Representations through Encapsulation of Manifolds" by C.
+// Hertzberg, R. Wagner, U. Frese and L. Schroder for more details
+// (https://arxiv.org/pdf/1107.1119.pdf)
+template <int AmbientSpaceDimension>
+class SphereManifold : public Manifold {
+ public:
+  static_assert(
+      AmbientSpaceDimension == DYNAMIC || AmbientSpaceDimension > 1,
+      "The size of the homogeneous vector needs to be greater than 1.");
+  static_assert(DYNAMIC == Eigen::Dynamic,
+                "ceres::DYNAMIC needs to be the same as Eigen::Dynamic.");
+
+  SphereManifold();
+  explicit SphereManifold(int size);
+
+  int AmbientSize() const override {
+    return AmbientSpaceDimension == ceres::DYNAMIC ? size_
+                                                   : AmbientSpaceDimension;
+  }
+  int TangentSize() const override { return AmbientSize() - 1; }
+
+  bool Plus(const double* x,
+            const double* delta,
+            double* x_plus_delta) const override;
+  bool PlusJacobian(const double* x, double* jacobian) const override;
+
+  bool Minus(const double* y,
+             const double* x,
+             double* y_minus_x) const override;
+  bool MinusJacobian(const double* x, double* jacobian) const override;
+
+ private:
+  static constexpr int TangentSpaceDimension =
+      AmbientSpaceDimension > 0 ? AmbientSpaceDimension - 1 : Eigen::Dynamic;
+
+  using AmbientVector = Eigen::Matrix<double, AmbientSpaceDimension, 1>;
+  using TangentVector = Eigen::Matrix<double, TangentSpaceDimension, 1>;
+  using MatrixPlusJacobian = Eigen::Matrix<double,
+                                           AmbientSpaceDimension,
+                                           TangentSpaceDimension,
+                                           Eigen::RowMajor>;
+  using MatrixMinusJacobian = Eigen::Matrix<double,
+                                            TangentSpaceDimension,
+                                            AmbientSpaceDimension,
+                                            Eigen::RowMajor>;
+
+  const int size_{};
+};
+
 }  // namespace ceres
 
+#include "internal/sphere_manifold.h"
+
 // clang-format off
 #include "ceres/internal/reenable_warnings.h"
 
diff --git a/internal/ceres/manifold_test.cc b/internal/ceres/manifold_test.cc
index 11d6977..89e0ec7 100644
--- a/internal/ceres/manifold_test.cc
+++ b/internal/ceres/manifold_test.cc
@@ -337,7 +337,7 @@
   return true;
 }
 
-Vector RandomQuaternion() {
+static Vector RandomQuaternion() {
   Vector x = Vector::Random(4);
   x.normalize();
   return x;
@@ -451,5 +451,112 @@
   }
 }
 
+TEST(SphereManifold, ZeroTest) {
+  Eigen::Vector4d x{0.0, 0.0, 0.0, 1.0};
+  Eigen::Vector3d delta = Eigen::Vector3d::Zero();
+  Eigen::Vector4d y = Eigen::Vector4d::Zero();
+
+  SphereManifold<4> manifold;
+  manifold.Plus(x.data(), delta.data(), y.data());
+  EXPECT_THAT_MANIFOLD_INVARIANTS_HOLD(manifold, x, delta, y, kTolerance);
+}
+
+TEST(SphereManifold, NearZeroTest1) {
+  Eigen::Vector4d x{1e-5, 1e-5, 1e-5, 1.0};
+  x.normalize();
+  Eigen::Vector3d delta{0.0, 1.0, 0.0};
+  Eigen::Vector4d y = Eigen::Vector4d::Zero();
+
+  SphereManifold<4> manifold;
+  manifold.Plus(x.data(), delta.data(), y.data());
+  EXPECT_THAT_MANIFOLD_INVARIANTS_HOLD(manifold, x, delta, y, kTolerance);
+}
+
+TEST(SphereManifold, NearZeroTest2) {
+  Eigen::Vector4d x{0.001, 0.0, 0.0, 0.0};
+  Eigen::Vector3d delta{0.0, 1.0, 0.0};
+  Eigen::Vector4d y = Eigen::Vector4d::Zero();
+  SphereManifold<4> manifold;
+  manifold.Plus(x.data(), delta.data(), y.data());
+  EXPECT_THAT_MANIFOLD_INVARIANTS_HOLD(manifold, x, delta, y, kTolerance);
+}
+
+TEST(SphereManifold, Plus) {
+  Eigen::Vector3d x{0.0, 0.0, 1.0};
+  SphereManifold<3> manifold;
+
+  {
+    Eigen::Vector2d delta{M_PI, 0.0};
+    Eigen::Vector3d y = Eigen::Vector3d::Zero();
+    EXPECT_TRUE(manifold.Plus(x.data(), delta.data(), y.data()));
+    const Eigen::Vector3d gtY = Eigen::Vector3d::UnitX();
+    EXPECT_LT((y - gtY).norm(), kTolerance);
+  }
+
+  {
+    Eigen::Vector2d delta{0.0, M_PI};
+    Eigen::Vector3d y = Eigen::Vector3d::Zero();
+    EXPECT_TRUE(manifold.Plus(x.data(), delta.data(), y.data()));
+    const Eigen::Vector3d gtY = Eigen::Vector3d::UnitY();
+    EXPECT_LT((y - gtY).norm(), kTolerance);
+  }
+
+  {
+    Eigen::Vector2d delta = Eigen::Vector2d(1, 1).normalized() * M_PI;
+    Eigen::Vector3d y = Eigen::Vector3d::Zero();
+    EXPECT_TRUE(manifold.Plus(x.data(), delta.data(), y.data()));
+    const Eigen::Vector3d gtY(std::sqrt(2.0) / 2.0, std::sqrt(2.0) / 2.0, 0.0);
+    EXPECT_LT((y - gtY).norm(), kTolerance);
+  }
+}
+
+TEST(SphereManifold, DeathTests) {
+  EXPECT_DEATH_IF_SUPPORTED(SphereManifold<Eigen::Dynamic> x(1), "size");
+}
+
+TEST(SphereManifold, NormalFunctionTest) {
+  SphereManifold<4> manifold;
+  EXPECT_EQ(manifold.AmbientSize(), 4);
+  EXPECT_EQ(manifold.TangentSize(), 3);
+
+  Vector zero_tangent = Vector::Zero(manifold.TangentSize());
+  for (int trial = 0; trial < kNumTrials; ++trial) {
+    const Vector x = Vector::Random(manifold.AmbientSize());
+    Vector y = Vector::Random(manifold.AmbientSize());
+    Vector delta = Vector::Random(manifold.TangentSize());
+
+    if (x.norm() == 0.0 || y.norm() == 0.0) {
+      continue;
+    }
+
+    // X and y need to have the same length.
+    y *= x.norm() / y.norm();
+
+    EXPECT_THAT_MANIFOLD_INVARIANTS_HOLD(manifold, x, delta, y, kTolerance);
+  }
+}
+
+TEST(SphereManifold, NormalFunctionTestDynamic) {
+  SphereManifold<Eigen::Dynamic> manifold(5);
+  EXPECT_EQ(manifold.AmbientSize(), 5);
+  EXPECT_EQ(manifold.TangentSize(), 4);
+
+  Vector zero_tangent = Vector::Zero(manifold.TangentSize());
+  for (int trial = 0; trial < kNumTrials; ++trial) {
+    const Vector x = Vector::Random(manifold.AmbientSize());
+    Vector y = Vector::Random(manifold.AmbientSize());
+    Vector delta = Vector::Random(manifold.TangentSize());
+
+    if (x.norm() == 0.0 || y.norm() == 0.0) {
+      continue;
+    }
+
+    // X and y need to have the same length.
+    y *= x.norm() / y.norm();
+
+    EXPECT_THAT_MANIFOLD_INVARIANTS_HOLD(manifold, x, delta, y, kTolerance);
+  }
+}
+
 }  // namespace internal
 }  // namespace ceres