c++ - Eigen 中的自定义标量类型

标签 c++ eigen eigen3

我目前正在尝试设置一个自定义标量类型以与 Eigen3 库一起使用(atm 它是 double 的简单包装器)。我已关注https://eigen.tuxfamily.org/dox/TopicCustomizing_CustomScalar.html据我所知,基本的事情工作得很好。

我需要用我的自定义类型解决矩阵的特征值问题,而这正是事情开始崩溃的地方。我的编译器向我吐出以下错误消息:

/Eigen3/Eigen/src/Householder/Householder.h:131:18: error: no viable overloaded '-='
    this->row(0) -= tau * tmp;
    ~~~~~~~~~~~~ ^  ~~~~~~~~~
/Eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h:314:10: note: in instantiation of function template specialization 'Eigen::MatrixBase<Eigen::Block<Eigen::Matrix<MyDouble, 2,
      2, 0, 2, 2>, -1, -1, false> >::applyHouseholderOnTheLeft<Eigen::VectorBlock<Eigen::Block<Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2>, 2, 1, true>, -1> >' requested here
        .applyHouseholderOnTheLeft(matA.col(i).tail(remainingSize-1), h, &temp.coeffRef(0));
         ^
/Eigen3/Eigen/src/Eigenvalues/HessenbergDecomposition.h:161:7: note: in instantiation of member function 'Eigen::HessenbergDecomposition<Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2>
      >::_compute' requested here
      _compute(m_matrix, m_hCoeffs, m_temp);
      ^
/Eigen3/Eigen/src/Eigenvalues/./RealSchur.h:271:10: note: in instantiation of function template specialization 'Eigen::HessenbergDecomposition<Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2>
      >::compute<Eigen::CwiseBinaryOp<Eigen::internal::scalar_quotient_op<MyDouble, MyDouble>, const Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2>, const Eigen::CwiseNullaryOp<Eigen::internal::scalar_constant_op<MyDouble>, const
      Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2> > > >' requested here
  m_hess.compute(matrix.derived()/scale);
         ^
/Eigen3/Eigen/src/Eigenvalues/EigenSolver.h:389:15: note: in instantiation of function template specialization 'Eigen::RealSchur<Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2>
      >::compute<Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2> >' requested here
  m_realSchur.compute(matrix.derived(), computeEigenvectors);
              ^
/Eigen3/Eigen/src/Eigenvalues/EigenSolver.h:156:7: note: in instantiation of function template specialization 'Eigen::EigenSolver<Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2>
      >::compute<Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2> >' requested here
      compute(matrix.derived(), computeEigenvectors);
      ^
/home/adam/Documents/Git/spin_phonon_coupling/src/test.cpp:205:52: note: in instantiation of function template specialization 'Eigen::EigenSolver<Eigen::Matrix<MyDouble, 2, 2, 0, 2, 2> >::EigenSolver<Eigen::Matrix<MyDouble, 2, 2, 0, 2,
      2> >' requested here
        Eigen::EigenSolver<Eigen::Matrix<MyDouble, 2, 2>> solver(test);
                                                          ^
/Eigen3/Eigen/src/Core/DenseBase.h:298:14: note: candidate template ignored: could not match 'EigenBase<type-parameter-0-0>' against 'MyDouble'
    Derived& operator-=(const EigenBase<OtherDerived> &other);
             ^
/Eigen3/Eigen/src/Core/MatrixBase.h:161:14: note: candidate template ignored: could not match 'MatrixBase<type-parameter-0-0>' against 'MyDouble'
    Derived& operator-=(const MatrixBase<OtherDerived>& other);
             ^
/Eigen3/Eigen/src/Core/MatrixBase.h:495:46: note: candidate template ignored: could not match 'ArrayBase<type-parameter-0-0>' against 'MyDouble'
    template<typename OtherDerived> Derived& operator-=(const ArrayBase<OtherDerived>& )

因此,基本问题似乎是 -= 运算符缺少重载。问题是我不知道为什么。据我所知,我已经为我的类型定义了重载运算符,但是如果我正确理解了错误,似乎内部特征类型缺少该重载...

有人知道这里可能出现什么问题吗?


这是产生上述错误的代码:

#include <iostream>
#include <cmath>

#include <Eigen/Dense>

class MyDouble {
    public:
        double value;
        MyDouble() : value() {};
        MyDouble(double val) : value(val) {};

        template<typename T>
            MyDouble operator+(T other) const {
                return value + other;
            }
        template<>
            MyDouble operator+(MyDouble other) const {
                return MyDouble(value + other.value);
            }

        template<typename T>
            MyDouble operator-(T other) const {
                return value - other;
            }
        template<>
            MyDouble operator-(MyDouble other) const {
                return MyDouble(value - other.value);
            }

        template<typename T>
            MyDouble operator*(T other) const {
                return value * other;
            }
        template<>
            MyDouble operator*(MyDouble other) const {
                return MyDouble(value * other.value);
            }

        template<typename T>
            MyDouble operator/(T other) const {
                return value / other;
            }
        template<>
            MyDouble operator/(MyDouble other) const {
                return MyDouble(value / other.value);
            }

        template<typename T>
            MyDouble& operator+=(T other) {
                value += other;
                return *this;
            }
        template<>
            MyDouble& operator+=(MyDouble other) {
                value += other.value;
                return *this;
            }

        template<typename T>
            MyDouble& operator-=(const T &other) {
                value -= other;
                return *this;
            }
        template<>
            MyDouble& operator-=(const MyDouble &other) {
                value -= other.value;
                return *this;
            }

        template<typename T>
            MyDouble& operator*=(T other) {
                value *= other.value;
                return *this;
            }
        template<>
            MyDouble& operator*=(MyDouble other) {
                value *= other.value;
                return *this;
            }

        template<typename T>
            MyDouble& operator/=(T other) {
                value /= other;
                return *this;
            }
        template<>
            MyDouble& operator/=(MyDouble other) {
                value /= other.value;
                return *this;
            }

        MyDouble operator-() const {
            return -value;
        }

        template<typename T>
            bool operator<(T other) const {
                return value < other;
            }
        template<>
            bool operator<(MyDouble other) const {
                return value < other.value;
            }

        template<typename T>
            bool operator>(T other) const {
                return value > other;
            }
        template<>
            bool operator>(MyDouble other) const {
                return value > other.value;
            }

        template<typename T>
            bool operator<=(T other) const {
                return value <= other;
            }
        template<>
            bool operator <=(MyDouble other) const {
                return value <= other.value;
            }

        template<typename T>
            bool operator>=(T other) const {
                return value >= other;
            }
        template<>
            bool operator>=(MyDouble other) const {
                return value >= other.value;
            }

        template<typename T>
            bool operator==(T other) const {
                return value == other;
            }
        template<>
            bool operator==(MyDouble other) const {
                return value == other.value;
            }

        template<typename T>
            bool operator!=(T other) const {
                return value != other;
            }
        template<>
            bool operator!=(MyDouble other) const {
                return value != other.value;
            }

        friend std::ostream& operator<<(std::ostream& out, const MyDouble& val) {
            out << val.value << " m";
            return out;
        }

        operator double() {
            return value;
        }
};

MyDouble sqrt(MyDouble val) {
    return std::sqrt(val.value);
}
MyDouble abs(MyDouble val) {
    return std::abs(val.value);
}
MyDouble abs2(MyDouble val) {
    return val * val;
}

namespace Eigen {
    template<> struct NumTraits<MyDouble>
        : NumTraits<double> // permits to get the epsilon, dummy_precision, lowest, highest functions
        {
            typedef MyDouble Real;
            typedef MyDouble NonInteger;
            typedef MyDouble Nested;
            enum {
                IsComplex = 0,
                IsInteger = 0,
                IsSigned = 1,
                RequireInitialization = 1,
                ReadCost = 1,
                AddCost = 3,
                MulCost = 3
            };
        };
    template<typename BinaryOp>
    struct ScalarBinaryOpTraits<MyDouble,double,BinaryOp> { typedef MyDouble ReturnType;  };

    template<typename BinaryOp>
    struct ScalarBinaryOpTraits<double,MyDouble,BinaryOp> { typedef MyDouble ReturnType;  };
}

int main() {
    Eigen::Matrix<MyDouble, 2, 2> test;
    test << 1, 2, 3, 4;

    Eigen::Matrix<double, 2, 2> test2;
    test2 << 5, 6, 7, 8;

    MyDouble a = 3;
    a -= 2;
    a -= MyDouble(3);

    Eigen::EigenSolver<Eigen::Matrix<MyDouble, 2, 2>> solver(test);
    std::cout << test.trace() << std::endl;
    std::cout << solver.eigenvalues() << std::endl;
}

最佳答案

Marc Glisse 指出我的运算符重载似乎有点奇怪,所以我重写了它们,最初的问题就消失了。我不知道为什么会出现这种情况。

然后我只遇到了 Eigen 的 isfinite 函数没有为我的自定义类型定义的问题,所以我继续添加了它的实现(尽管我不确定这是否是)实际上是一个固体)。

无论如何,我的代码现在可以编译了。这是我的代码的修改版本:

#include <iostream>
#include <cmath>
#include <complex>

#include <Eigen/Dense>

class MyDouble {
    public:
        double value;
        MyDouble() : value() {};
        MyDouble(double val) : value(val) {};

        template<typename T>
            MyDouble& operator+=(T rhs) {
                value = static_cast<double>(value + rhs);
                return *this;
            }

        template<typename T>
            MyDouble& operator-=(const T &rhs) {
                value = static_cast<double>(value - rhs);
                return *this;
            }

        template<typename T>
            MyDouble& operator*=(T rhs) {
                value = static_cast<double>(value * rhs);
                return *this;
            }

        template<typename T>
            MyDouble& operator/=(T rhs) {
                value = static_cast<double>(value / rhs);
                return *this;
            }

        MyDouble operator-() const {
            return -value;
        }

        friend std::ostream& operator<<(std::ostream& out, const MyDouble& val) {
            out << val.value << " m";
            return out;
        }

        explicit operator double() {
            return value;
        }
};

#define OVERLOAD_OPERATOR(op,ret) ret operator op(const MyDouble &lhs, const MyDouble &rhs) { \
        return lhs.value op rhs.value; \
    }

OVERLOAD_OPERATOR(+, MyDouble)
OVERLOAD_OPERATOR(-, MyDouble)
OVERLOAD_OPERATOR(*, MyDouble)
OVERLOAD_OPERATOR(/, MyDouble)

OVERLOAD_OPERATOR(>, bool)
OVERLOAD_OPERATOR(<, bool)
OVERLOAD_OPERATOR(>=, bool)
OVERLOAD_OPERATOR(<=, bool)
OVERLOAD_OPERATOR(==, bool)
OVERLOAD_OPERATOR(!=, bool)


MyDouble sqrt(MyDouble val) {
    return std::sqrt(val.value);
}
MyDouble abs(MyDouble val) {
    return std::abs(val.value);
}
MyDouble abs2(MyDouble val) {
    return val * val;
}
bool isfinite(const MyDouble &) { return true; }

namespace Eigen {
    template<> struct NumTraits<MyDouble>
        : NumTraits<double> // permits to get the epsilon, dummy_precision, lowest, highest functions
        {
            typedef MyDouble Real;
            typedef MyDouble NonInteger;
            typedef MyDouble Nested;
            enum {
                IsComplex = 0,
                IsInteger = 0,
                IsSigned = 1,
                RequireInitialization = 0,
                ReadCost = 1,
                AddCost = 3,
                MulCost = 3
            };
        };

    template<typename BinaryOp>
    struct ScalarBinaryOpTraits<MyDouble,double,BinaryOp> { typedef MyDouble ReturnType;  };

    template<typename BinaryOp>
    struct ScalarBinaryOpTraits<double,MyDouble,BinaryOp> { typedef MyDouble ReturnType;  };
}

int main() {
    Eigen::Matrix<MyDouble, 2, 2> test;
    test << 1, 2, 3, 4;

    Eigen::Matrix<double, 2, 2> reference;
    reference << 1, 2, 3, 4;

    MyDouble a = 3;
    a += 2;
    a = 2 + a;
    a = a + 2;
    a -= 2;
    a -= MyDouble(3);

    a = a / a;

    std::complex<MyDouble> complexTest(3,4);
    complexTest *= 2;

    Eigen::EigenSolver<Eigen::Matrix<MyDouble, 2, 2>> solver(test);
    Eigen::EigenSolver<Eigen::Matrix<double, 2, 2>> refSolver(reference);
    std::cout << "MyDouble:" << std::endl;
    std::cout << test.trace() << std::endl;
    std::cout << solver.eigenvalues() << std::endl;
    std::cout << "\nRefernce:" << std::endl;
    std::cout << reference.trace() << std::endl;
    std::cout << refSolver.eigenvalues() << std::endl;
}

关于c++ - Eigen 中的自定义标量类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59747377/

相关文章:

optimization - Eigen :就位系数乘法

c++ - 如何从终端运行用 eclipse 编写的 c++ 程序

c++ - 通过循环展开和阻塞进行优化

c++ - 使用 show() 只打开一个 QDialog 实例,如果我关闭 QDialog,对象是否也被删除

c++ - 求解具有大矩阵的稀疏线性系统时的写访问冲突

c++ - Eigen 化合物加法给出错误的结果

c++ - 统计txt文件中的元素个数

c++ - Boost::uBLAS 与 Eigen

从头开始实现的 C++ 神经网络在 MNIST 上无法达到 50% 以上

c++ - CGAL 错误 : Eigen3 is required -> Eigen seems to be okay though