Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • jcarpent/eigenpy
  • gsaurel/eigenpy
  • stack-of-tasks/eigenpy
3 results
Show changes
Showing
with 1219 additions and 293 deletions
/*
* Copyright 2024 INRIA
*/
#ifndef __eigenpy_decompositions_sparse_sparse_solver_base_hpp__
#define __eigenpy_decompositions_sparse_sparse_solver_base_hpp__
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/eigen/EigenBase.hpp"
#include <Eigen/SparseCholesky>
namespace eigenpy {
template <typename SimplicialDerived>
struct SparseSolverBaseVisitor
: public boost::python::def_visitor<
SparseSolverBaseVisitor<SimplicialDerived> > {
typedef SimplicialDerived Solver;
typedef typename SimplicialDerived::MatrixType MatrixType;
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::RealScalar RealScalar;
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, 1, MatrixType::Options>
DenseVectorXs;
typedef Eigen::Matrix<Scalar, Eigen::Dynamic, Eigen::Dynamic,
MatrixType::Options>
DenseMatrixXs;
template <class PyClass>
void visit(PyClass &cl) const {
cl.def("solve", &solve<DenseVectorXs>, bp::args("self", "b"),
"Returns the solution x of A x = b using the current "
"decomposition of A.")
.def("solve", &solve<DenseMatrixXs>, bp::args("self", "B"),
"Returns the solution X of A X = B using the current "
"decomposition of A where B is a right hand side matrix.")
.def("solve", &solve<MatrixType>, bp::args("self", "B"),
"Returns the solution X of A X = B using the current "
"decomposition of A where B is a right hand side matrix.");
}
private:
template <typename MatrixOrVector>
static MatrixOrVector solve(const Solver &self, const MatrixOrVector &vec) {
return self.solve(vec);
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_decompositions_sparse_sparse_solver_base_hpp__
/*
* Copyright 2024 INRIA
*/
#ifndef __eigenpy_decomposition_sparse_accelerate_accelerate_hpp__
#define __eigenpy_decomposition_sparse_accelerate_accelerate_hpp__
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/eigen/EigenBase.hpp"
#include "eigenpy/decompositions/sparse/SparseSolverBase.hpp"
#include <Eigen/AccelerateSupport>
namespace eigenpy {
template <typename AccelerateDerived>
struct AccelerateImplVisitor : public boost::python::def_visitor<
AccelerateImplVisitor<AccelerateDerived> > {
typedef AccelerateDerived Solver;
typedef typename AccelerateDerived::MatrixType MatrixType;
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::RealScalar RealScalar;
typedef MatrixType CholMatrixType;
typedef typename MatrixType::StorageIndex StorageIndex;
template <class PyClass>
void visit(PyClass &cl) const {
cl
.def("analyzePattern", &Solver::analyzePattern,
bp::args("self", "matrix"),
"Performs a symbolic decomposition on the sparcity of matrix.\n"
"This function is particularly useful when solving for several "
"problems having the same structure.")
.def(EigenBaseVisitor<Solver>())
.def(SparseSolverBaseVisitor<Solver>())
.def("compute",
(Solver & (Solver::*)(const MatrixType &matrix)) & Solver::compute,
bp::args("self", "matrix"),
"Computes the sparse Cholesky decomposition of a given matrix.",
bp::return_self<>())
.def("factorize", &Solver::factorize, bp::args("self", "matrix"),
"Performs a numeric decomposition of a given matrix.\n"
"The given matrix must has the same sparcity than the matrix on "
"which the symbolic decomposition has been performed.\n"
"See also analyzePattern().")
.def("info", &Solver::info, bp::arg("self"),
"NumericalIssue if the input contains INF or NaN values or "
"overflow occured. Returns Success otherwise.")
.def("setOrder", &Solver::setOrder, bp::arg("self"), "Set order");
}
static void expose(const std::string &name, const std::string &doc = "") {
bp::class_<Solver, boost::noncopyable>(name.c_str(), doc.c_str(),
bp::no_init)
.def(AccelerateImplVisitor())
.def(bp::init<>(bp::arg("self"), "Default constructor"))
.def(bp::init<MatrixType>(bp::args("self", "matrix"),
"Constructs and performs the "
"factorization from a given matrix."));
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_decomposition_sparse_accelerate_accelerate_hpp__
/*
* Copyright 2024 INRIA
*/
#ifndef __eigenpy_decomposition_sparse_cholmod_cholmod_base_hpp__
#define __eigenpy_decomposition_sparse_cholmod_cholmod_base_hpp__
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/eigen/EigenBase.hpp"
#include "eigenpy/decompositions/sparse/SparseSolverBase.hpp"
#include <Eigen/CholmodSupport>
namespace eigenpy {
template <typename CholdmodDerived>
struct CholmodBaseVisitor
: public boost::python::def_visitor<CholmodBaseVisitor<CholdmodDerived> > {
typedef CholdmodDerived Solver;
typedef typename CholdmodDerived::MatrixType MatrixType;
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::RealScalar RealScalar;
typedef MatrixType CholMatrixType;
typedef typename MatrixType::StorageIndex StorageIndex;
template <class PyClass>
void visit(PyClass &cl) const {
cl.def("analyzePattern", &Solver::analyzePattern,
bp::args("self", "matrix"),
"Performs a symbolic decomposition on the sparcity of matrix.\n"
"This function is particularly useful when solving for several "
"problems having the same structure.")
.def(EigenBaseVisitor<Solver>())
.def(SparseSolverBaseVisitor<Solver>())
.def("compute",
(Solver & (Solver::*)(const MatrixType &matrix)) & Solver::compute,
bp::args("self", "matrix"),
"Computes the sparse Cholesky decomposition of a given matrix.",
bp::return_self<>())
.def("determinant", &Solver::determinant, bp::arg("self"),
"Returns the determinant of the underlying matrix from the "
"current factorization.")
.def("factorize", &Solver::factorize, bp::args("self", "matrix"),
"Performs a numeric decomposition of a given matrix.\n"
"The given matrix must has the same sparcity than the matrix on "
"which the symbolic decomposition has been performed.\n"
"See also analyzePattern().")
.def("info", &Solver::info, bp::arg("self"),
"NumericalIssue if the input contains INF or NaN values or "
"overflow occured. Returns Success otherwise.")
.def("logDeterminant", &Solver::logDeterminant, bp::arg("self"),
"Returns the log determinant of the underlying matrix from the "
"current factorization.")
.def("setShift", &Solver::setShift, (bp::args("self", "offset")),
"Sets the shift parameters that will be used to adjust the "
"diagonal coefficients during the numerical factorization.\n"
"During the numerical factorization, the diagonal coefficients "
"are transformed by the following linear model: d_ii = offset + "
"d_ii.\n"
"The default is the identity transformation with offset=0.",
bp::return_self<>());
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_decomposition_sparse_cholmod_cholmod_base_hpp__
/*
* Copyright 2024 INRIA
*/
#ifndef __eigenpy_decomposition_sparse_cholmod_cholmod_decomposition_hpp__
#define __eigenpy_decomposition_sparse_cholmod_cholmod_decomposition_hpp__
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/decompositions/sparse/cholmod/CholmodBase.hpp"
namespace eigenpy {
template <typename CholdmodDerived>
struct CholmodDecompositionVisitor
: public boost::python::def_visitor<
CholmodDecompositionVisitor<CholdmodDerived> > {
typedef CholdmodDerived Solver;
template <class PyClass>
void visit(PyClass &cl) const {
cl
.def(CholmodBaseVisitor<Solver>())
.def("setMode", &Solver::setMode, bp::args("self", "mode"),
"Set the mode for the Cholesky decomposition.");
}
};
} // namespace eigenpy
#endif // ifndef
// __eigenpy_decomposition_sparse_cholmod_cholmod_decomposition_hpp__
/*
* Copyright 2024 INRIA
*/
#ifndef __eigenpy_decomposition_sparse_cholmod_cholmod_simplicial_ldlt_hpp__
#define __eigenpy_decomposition_sparse_cholmod_cholmod_simplicial_ldlt_hpp__
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/decompositions/sparse/cholmod/CholmodDecomposition.hpp"
#include "eigenpy/utils/scalar-name.hpp"
namespace eigenpy {
template <typename MatrixType_, int UpLo_ = Eigen::Lower>
struct CholmodSimplicialLDLTVisitor
: public boost::python::def_visitor<
CholmodSimplicialLDLTVisitor<MatrixType_, UpLo_> > {
typedef MatrixType_ MatrixType;
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::RealScalar RealScalar;
typedef Eigen::CholmodSimplicialLDLT<MatrixType_, UpLo_> Solver;
template <class PyClass>
void visit(PyClass &cl) const {
cl
.def(CholmodBaseVisitor<Solver>())
.def(bp::init<>(bp::arg("self"), "Default constructor"))
.def(bp::init<MatrixType>(bp::args("self", "matrix"),
"Constructs and performs the LDLT "
"factorization from a given matrix."))
;
}
static void expose() {
static const std::string classname =
"CholmodSimplicialLDLT_" + scalar_name<Scalar>::shortname();
expose(classname);
}
static void expose(const std::string &name) {
bp::class_<Solver, boost::noncopyable>(
name.c_str(),
"A simplicial direct Cholesky (LDLT) factorization and solver based on "
"Cholmod.\n\n"
"This class allows to solve for A.X = B sparse linear problems via a "
"simplicial LL^T Cholesky factorization using the Cholmod library."
"This simplicial variant is equivalent to Eigen's built-in "
"SimplicialLDLT class."
"Therefore, it has little practical interest. The sparse matrix A must "
"be selfadjoint and positive definite."
"The vectors or matrices X and B can be either dense or sparse.",
bp::no_init)
.def(CholmodSimplicialLDLTVisitor());
}
};
} // namespace eigenpy
#endif // ifndef
// __eigenpy_decomposition_sparse_cholmod_cholmod_simplicial_ldlt_hpp__
/*
* Copyright 2024 INRIA
*/
#ifndef __eigenpy_decomposition_sparse_cholmod_cholmod_simplicial_llt_hpp__
#define __eigenpy_decomposition_sparse_cholmod_cholmod_simplicial_llt_hpp__
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/decompositions/sparse/cholmod/CholmodDecomposition.hpp"
#include "eigenpy/utils/scalar-name.hpp"
namespace eigenpy {
template <typename MatrixType_, int UpLo_ = Eigen::Lower>
struct CholmodSimplicialLLTVisitor
: public boost::python::def_visitor<
CholmodSimplicialLLTVisitor<MatrixType_, UpLo_> > {
typedef MatrixType_ MatrixType;
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::RealScalar RealScalar;
typedef Eigen::CholmodSimplicialLLT<MatrixType_, UpLo_> Solver;
template <class PyClass>
void visit(PyClass &cl) const {
cl
.def(CholmodBaseVisitor<Solver>())
.def(bp::init<>(bp::arg("self"), "Default constructor"))
.def(bp::init<MatrixType>(bp::args("self", "matrix"),
"Constructs and performs the LLT "
"factorization from a given matrix."))
;
}
static void expose() {
static const std::string classname =
"CholmodSimplicialLLT_" + scalar_name<Scalar>::shortname();
expose(classname);
}
static void expose(const std::string &name) {
bp::class_<Solver, boost::noncopyable>(
name.c_str(),
"A simplicial direct Cholesky (LLT) factorization and solver based on "
"Cholmod.\n\n"
"This class allows to solve for A.X = B sparse linear problems via a "
"simplicial LL^T Cholesky factorization using the Cholmod library."
"This simplicial variant is equivalent to Eigen's built-in "
"SimplicialLLT class."
"Therefore, it has little practical interest. The sparse matrix A must "
"be selfadjoint and positive definite."
"The vectors or matrices X and B can be either dense or sparse.",
bp::no_init)
.def(CholmodSimplicialLLTVisitor());
}
};
} // namespace eigenpy
#endif // ifndef
// __eigenpy_decomposition_sparse_cholmod_cholmod_simplicial_llt_hpp__
/*
* Copyright 2024 INRIA
*/
#ifndef __eigenpy_decomposition_sparse_cholmod_cholmod_supernodal_llt_hpp__
#define __eigenpy_decomposition_sparse_cholmod_cholmod_supernodal_llt_hpp__
#include "eigenpy/eigenpy.hpp"
#include "eigenpy/decompositions/sparse/cholmod/CholmodDecomposition.hpp"
#include "eigenpy/utils/scalar-name.hpp"
namespace eigenpy {
template <typename MatrixType_, int UpLo_ = Eigen::Lower>
struct CholmodSupernodalLLTVisitor
: public boost::python::def_visitor<
CholmodSupernodalLLTVisitor<MatrixType_, UpLo_> > {
typedef MatrixType_ MatrixType;
typedef typename MatrixType::Scalar Scalar;
typedef typename MatrixType::RealScalar RealScalar;
typedef Eigen::CholmodSupernodalLLT<MatrixType_, UpLo_> Solver;
template <class PyClass>
void visit(PyClass &cl) const {
cl
.def(CholmodBaseVisitor<Solver>())
.def(bp::init<>(bp::arg("self"), "Default constructor"))
.def(bp::init<MatrixType>(bp::args("self", "matrix"),
"Constructs and performs the LLT "
"factorization from a given matrix."))
;
}
static void expose() {
static const std::string classname =
"CholmodSupernodalLLT_" + scalar_name<Scalar>::shortname();
expose(classname);
}
static void expose(const std::string &name) {
bp::class_<Solver, boost::noncopyable>(
name.c_str(),
"A supernodal direct Cholesky (LLT) factorization and solver based on "
"Cholmod.\n\n"
"This class allows to solve for A.X = B sparse linear problems via a "
"supernodal LL^T Cholesky factorization using the Cholmod library."
"This supernodal variant performs best on dense enough problems, e.g., "
"3D FEM, or very high order 2D FEM."
"The sparse matrix A must be selfadjoint and positive definite. The "
"vectors or matrices X and B can be either dense or sparse.",
bp::no_init)
.def(CholmodSupernodalLLTVisitor());
}
};
} // namespace eigenpy
#endif // ifndef
// __eigenpy_decomposition_sparse_cholmod_cholmod_supernodal_llt_hpp__
//
// Copyright (C) 2020 INRIA
// Copyright (C) 2024 LAAS-CNRS, INRIA
//
#ifndef __eigenpy_deprecation_hpp__
#define __eigenpy_deprecation_hpp__
#include "eigenpy/fwd.hpp"
namespace eigenpy {
enum class DeprecationType { DEPRECATION, FUTURE };
namespace detail {
inline PyObject *deprecationTypeToPyObj(DeprecationType dep) {
switch (dep) {
case DeprecationType::DEPRECATION:
return PyExc_DeprecationWarning;
case DeprecationType::FUTURE:
return PyExc_FutureWarning;
default: // The switch handles all cases explicitly, this should never be
// triggered.
throw std::invalid_argument(
"Undefined DeprecationType - this should never be triggered.");
}
}
} // namespace detail
/// @brief A Boost.Python call policy which triggers a Python warning on
/// precall.
template <DeprecationType deprecation_type = DeprecationType::DEPRECATION,
class BasePolicy = bp::default_call_policies>
struct deprecation_warning_policy : BasePolicy {
using result_converter = typename BasePolicy::result_converter;
using argument_package = typename BasePolicy::argument_package;
deprecation_warning_policy(const std::string &warning_msg)
: BasePolicy(), m_what(warning_msg) {}
std::string what() const { return m_what; }
const BasePolicy *derived() const {
return static_cast<const BasePolicy *>(this);
}
template <class ArgPackage>
bool precall(const ArgPackage &args) const {
PyErr_WarnEx(detail::deprecationTypeToPyObj(deprecation_type),
m_what.c_str(), 1);
return derived()->precall(args);
}
protected:
const std::string m_what;
};
template <DeprecationType deprecation_type = DeprecationType::DEPRECATION,
class BasePolicy = bp::default_call_policies>
struct deprecated_function
: deprecation_warning_policy<deprecation_type, BasePolicy> {
deprecated_function(const std::string &msg =
"This function has been marked as deprecated, and "
"will be removed in the future.")
: deprecation_warning_policy<deprecation_type, BasePolicy>(msg) {}
};
template <DeprecationType deprecation_type = DeprecationType::DEPRECATION,
class BasePolicy = bp::default_call_policies>
struct deprecated_member
: deprecation_warning_policy<deprecation_type, BasePolicy> {
deprecated_member(const std::string &msg =
"This attribute or method has been marked as "
"deprecated, and will be removed in the future.")
: deprecation_warning_policy<deprecation_type, BasePolicy>(msg) {}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_deprecation_hpp__
/*
* Copyright 2014-2019, CNRS
* Copyright 2018-2023, INRIA
* Copyright 2018-2024, INRIA
*/
#ifndef __eigenpy_details_hpp__
......@@ -19,11 +19,12 @@
namespace eigenpy {
template <typename EigenType,
typename BaseType = typename get_eigen_base_type<EigenType>::type>
typename BaseType = typename get_eigen_base_type<EigenType>::type,
typename Scalar = typename EigenType::Scalar>
struct expose_eigen_type_impl;
template <typename MatType>
struct expose_eigen_type_impl<MatType, Eigen::MatrixBase<MatType> > {
template <typename MatType, typename Scalar>
struct expose_eigen_type_impl<MatType, Eigen::MatrixBase<MatType>, Scalar> {
static void run() {
if (check_registration<MatType>()) return;
......@@ -39,9 +40,28 @@ struct expose_eigen_type_impl<MatType, Eigen::MatrixBase<MatType> > {
}
};
template <typename MatType, typename Scalar>
struct expose_eigen_type_impl<MatType, Eigen::SparseMatrixBase<MatType>,
Scalar> {
static void run() {
if (check_registration<MatType>()) return;
// to-python
EigenToPyConverter<MatType>::registration();
// #if EIGEN_VERSION_AT_LEAST(3, 2, 0)
// EigenToPyConverter<Eigen::Ref<MatType> >::registration();
// EigenToPyConverter<const Eigen::Ref<const MatType> >::registration();
// #endif
// from-python
EigenFromPyConverter<MatType>::registration();
}
};
#ifdef EIGENPY_WITH_TENSOR_SUPPORT
template <typename TensorType>
struct expose_eigen_type_impl<TensorType, Eigen::TensorBase<TensorType> > {
template <typename TensorType, typename Scalar>
struct expose_eigen_type_impl<TensorType, Eigen::TensorBase<TensorType>,
Scalar> {
static void run() {
if (check_registration<TensorType>()) return;
......
......@@ -91,23 +91,69 @@ struct init_tensor {
#endif
template <typename MatType>
bool check_swap(PyArrayObject *pyArray, const Eigen::MatrixBase<MatType> &mat) {
if (PyArray_NDIM(pyArray) == 0) return false;
if (mat.rows() == PyArray_DIMS(pyArray)[0])
return false;
else
return true;
struct check_swap_impl_matrix;
template <typename EigenType,
typename BaseType = typename get_eigen_base_type<EigenType>::type>
struct check_swap_impl;
template <typename MatType>
struct check_swap_impl<MatType, Eigen::MatrixBase<MatType> >
: check_swap_impl_matrix<MatType> {};
template <typename MatType>
struct check_swap_impl_matrix {
static bool run(PyArrayObject *pyArray,
const Eigen::MatrixBase<MatType> &mat) {
if (PyArray_NDIM(pyArray) == 0) return false;
if (mat.rows() == PyArray_DIMS(pyArray)[0])
return false;
else
return true;
}
};
template <typename EigenType>
bool check_swap(PyArrayObject *pyArray, const EigenType &mat) {
return check_swap_impl<EigenType>::run(pyArray, mat);
}
#ifdef EIGENPY_WITH_TENSOR_SUPPORT
template <typename TensorType>
bool check_swap(PyArrayObject * /*pyArray*/,
const Eigen::TensorBase<TensorType> & /*tensor*/) {
return false;
}
struct check_swap_impl_tensor {
static bool run(PyArrayObject * /*pyArray*/, const TensorType & /*tensor*/) {
return false;
}
};
template <typename TensorType>
struct check_swap_impl<TensorType, Eigen::TensorBase<TensorType> >
: check_swap_impl_tensor<TensorType> {};
#endif
// template <typename MatType>
// struct cast_impl_matrix;
//
// template <typename EigenType,
// typename BaseType = typename get_eigen_base_type<EigenType>::type>
// struct cast_impl;
//
// template <typename MatType>
// struct cast_impl<MatType, Eigen::MatrixBase<MatType> >
// : cast_impl_matrix<MatType> {};
//
// template <typename MatType>
// struct cast_impl_matrix
//{
// template <typename NewScalar, typename MatrixIn, typename MatrixOut>
// static void run(const Eigen::MatrixBase<MatrixIn> &input,
// const Eigen::MatrixBase<MatrixOut> &dest) {
// dest.const_cast_derived() = input.template cast<NewScalar>();
// }
// };
template <typename Scalar, typename NewScalar,
template <typename D> class EigenBase = Eigen::MatrixBase,
bool cast_is_valid = FromTypeToType<Scalar, NewScalar>::value>
struct cast {
template <typename MatrixIn, typename MatrixOut>
......@@ -115,34 +161,26 @@ struct cast {
const Eigen::MatrixBase<MatrixOut> &dest) {
dest.const_cast_derived() = input.template cast<NewScalar>();
}
};
#ifdef EIGENPY_WITH_TENSOR_SUPPORT
template <typename Scalar, typename NewScalar>
struct cast<Scalar, NewScalar, Eigen::TensorRef, true> {
template <typename TensorIn, typename TensorOut>
static void run(const Eigen::TensorBase<TensorIn> &input,
const Eigen::TensorBase<TensorOut> &dest) {
const_cast<TensorOut &>(static_cast<const TensorOut &>(dest)) =
input.template cast<NewScalar>();
static void run(const TensorIn &input, TensorOut &dest) {
dest = input.template cast<NewScalar>();
}
#endif
};
#endif
template <typename Scalar, typename NewScalar>
struct cast<Scalar, NewScalar, false> {
template <typename Scalar, typename NewScalar,
template <typename D> class EigenBase>
struct cast<Scalar, NewScalar, EigenBase, false> {
template <typename MatrixIn, typename MatrixOut>
static void run(const Eigen::MatrixBase<MatrixIn> & /*input*/,
const Eigen::MatrixBase<MatrixOut> & /*dest*/) {
static void run(const MatrixIn /*input*/, const MatrixOut /*dest*/) {
// do nothing
assert(false && "Must never happened");
}
#ifdef EIGENPY_WITH_TENSOR_SUPPORT
template <typename TensorIn, typename TensorOut>
static void run(const Eigen::TensorBase<TensorIn> & /*input*/,
const Eigen::TensorBase<TensorOut> & /*dest*/) {
// do nothing
assert(false && "Must never happened");
}
#endif
};
} // namespace details
......@@ -160,6 +198,91 @@ struct cast<Scalar, NewScalar, false> {
mat, NumpyMap<MatType, NewScalar>::map( \
pyArray, details::check_swap(pyArray, mat)))
// Define specific cast for Windows and Mac
#if defined _WIN32 || defined __CYGWIN__
// Manage NPY_INT on Windows (NPY_INT32 is NPY_LONG).
// See https://github.com/stack-of-tasks/eigenpy/pull/455
#define EIGENPY_CAST_FROM_NUMPY_TO_EIGEN_SWITCH_OS_SPECIFIC( \
MatType, Scalar, pyArray, mat, CAST_MACRO) \
case NPY_INT: \
CAST_MACRO(MatType, int32_t, Scalar, pyArray, mat); \
break; \
case NPY_UINT: \
CAST_MACRO(MatType, uint32_t, Scalar, pyArray, mat); \
break;
#elif defined __APPLE__
// Manage NPY_LONGLONG on Mac (NPY_INT64 is NPY_LONG).
// long long and long are both the same type
// but NPY_LONGLONG and NPY_LONG are different dtype.
// See https://github.com/stack-of-tasks/eigenpy/pull/455
#define EIGENPY_CAST_FROM_NUMPY_TO_EIGEN_SWITCH_OS_SPECIFIC( \
MatType, Scalar, pyArray, mat, CAST_MACRO) \
case NPY_LONGLONG: \
CAST_MACRO(MatType, int64_t, Scalar, pyArray, mat); \
break; \
case NPY_ULONGLONG: \
CAST_MACRO(MatType, uint64_t, Scalar, pyArray, mat); \
break;
#else
#define EIGENPY_CAST_FROM_NUMPY_TO_EIGEN_SWITCH_OS_SPECIFIC( \
MatType, Scalar, pyArray, mat, CAST_MACRO)
#endif
/// Define casting between Numpy matrix type to Eigen type.
#define EIGENPY_CAST_FROM_NUMPY_TO_EIGEN_SWITCH( \
pyArray_type_code, MatType, Scalar, pyArray, mat, CAST_MACRO) \
switch (pyArray_type_code) { \
case NPY_BOOL: \
CAST_MACRO(MatType, bool, Scalar, pyArray, mat); \
break; \
case NPY_INT8: \
CAST_MACRO(MatType, int8_t, Scalar, pyArray, mat); \
break; \
case NPY_INT16: \
CAST_MACRO(MatType, int16_t, Scalar, pyArray, mat); \
break; \
case NPY_INT32: \
CAST_MACRO(MatType, int32_t, Scalar, pyArray, mat); \
break; \
case NPY_INT64: \
CAST_MACRO(MatType, int64_t, Scalar, pyArray, mat); \
break; \
case NPY_UINT8: \
CAST_MACRO(MatType, uint8_t, Scalar, pyArray, mat); \
break; \
case NPY_UINT16: \
CAST_MACRO(MatType, uint16_t, Scalar, pyArray, mat); \
break; \
case NPY_UINT32: \
CAST_MACRO(MatType, uint32_t, Scalar, pyArray, mat); \
break; \
case NPY_UINT64: \
CAST_MACRO(MatType, uint64_t, Scalar, pyArray, mat); \
break; \
case NPY_FLOAT: \
CAST_MACRO(MatType, float, Scalar, pyArray, mat); \
break; \
case NPY_CFLOAT: \
CAST_MACRO(MatType, std::complex<float>, Scalar, pyArray, mat); \
break; \
case NPY_DOUBLE: \
CAST_MACRO(MatType, double, Scalar, pyArray, mat); \
break; \
case NPY_CDOUBLE: \
CAST_MACRO(MatType, std::complex<double>, Scalar, pyArray, mat); \
break; \
case NPY_LONGDOUBLE: \
CAST_MACRO(MatType, long double, Scalar, pyArray, mat); \
break; \
case NPY_CLONGDOUBLE: \
CAST_MACRO(MatType, std::complex<long double>, Scalar, pyArray, mat); \
break; \
EIGENPY_CAST_FROM_NUMPY_TO_EIGEN_SWITCH_OS_SPECIFIC( \
MatType, Scalar, pyArray, mat, CAST_MACRO) \
default: \
throw Exception("You asked for a conversion which is not implemented."); \
}
template <typename EigenType>
struct EigenAllocator;
......@@ -171,11 +294,11 @@ template <typename MatType>
struct eigen_allocator_impl_matrix;
template <typename MatType>
struct eigen_allocator_impl<MatType, Eigen::MatrixBase<MatType>>
struct eigen_allocator_impl<MatType, Eigen::MatrixBase<MatType> >
: eigen_allocator_impl_matrix<MatType> {};
template <typename MatType>
struct eigen_allocator_impl<const MatType, const Eigen::MatrixBase<MatType>>
struct eigen_allocator_impl<const MatType, const Eigen::MatrixBase<MatType> >
: eigen_allocator_impl_matrix<const MatType> {};
template <typename MatType>
......@@ -209,43 +332,9 @@ struct eigen_allocator_impl_matrix {
pyArray, details::check_swap(pyArray, mat)); // avoid useless cast
return;
}
switch (pyArray_type_code) {
case NPY_INT:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_MATRIX(MatType, int, Scalar, pyArray,
mat);
break;
case NPY_LONG:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_MATRIX(MatType, long, Scalar,
pyArray, mat);
break;
case NPY_FLOAT:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_MATRIX(MatType, float, Scalar,
pyArray, mat);
break;
case NPY_CFLOAT:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_MATRIX(MatType, std::complex<float>,
Scalar, pyArray, mat);
break;
case NPY_DOUBLE:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_MATRIX(MatType, double, Scalar,
pyArray, mat);
break;
case NPY_CDOUBLE:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_MATRIX(MatType, std::complex<double>,
Scalar, pyArray, mat);
break;
case NPY_LONGDOUBLE:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_MATRIX(MatType, long double, Scalar,
pyArray, mat);
break;
case NPY_CLONGDOUBLE:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_MATRIX(
MatType, std::complex<long double>, Scalar, pyArray, mat);
break;
default:
throw Exception("You asked for a conversion which is not implemented.");
}
EIGENPY_CAST_FROM_NUMPY_TO_EIGEN_SWITCH(
pyArray_type_code, MatType, Scalar, pyArray, mat,
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_MATRIX);
}
/// \brief Copy mat into the Python array using Eigen::Map
......@@ -263,43 +352,8 @@ struct eigen_allocator_impl_matrix {
details::check_swap(pyArray, mat)) = mat;
return;
}
switch (pyArray_type_code) {
case NPY_INT:
EIGENPY_CAST_FROM_EIGEN_MATRIX_TO_PYARRAY(MatType, Scalar, int, mat,
pyArray);
break;
case NPY_LONG:
EIGENPY_CAST_FROM_EIGEN_MATRIX_TO_PYARRAY(MatType, Scalar, long, mat,
pyArray);
break;
case NPY_FLOAT:
EIGENPY_CAST_FROM_EIGEN_MATRIX_TO_PYARRAY(MatType, Scalar, float, mat,
pyArray);
break;
case NPY_CFLOAT:
EIGENPY_CAST_FROM_EIGEN_MATRIX_TO_PYARRAY(
MatType, Scalar, std::complex<float>, mat, pyArray);
break;
case NPY_DOUBLE:
EIGENPY_CAST_FROM_EIGEN_MATRIX_TO_PYARRAY(MatType, Scalar, double, mat,
pyArray);
break;
case NPY_CDOUBLE:
EIGENPY_CAST_FROM_EIGEN_MATRIX_TO_PYARRAY(
MatType, Scalar, std::complex<double>, mat, pyArray);
break;
case NPY_LONGDOUBLE:
EIGENPY_CAST_FROM_EIGEN_MATRIX_TO_PYARRAY(MatType, Scalar, long double,
mat, pyArray);
break;
case NPY_CLONGDOUBLE:
EIGENPY_CAST_FROM_EIGEN_MATRIX_TO_PYARRAY(
MatType, Scalar, std::complex<long double>, mat, pyArray);
break;
default:
throw Exception("You asked for a conversion which is not implemented.");
}
throw Exception(
"Scalar conversion from Eigen to Numpy is not implemented.");
}
};
......@@ -308,12 +362,12 @@ template <typename TensorType>
struct eigen_allocator_impl_tensor;
template <typename TensorType>
struct eigen_allocator_impl<TensorType, Eigen::TensorBase<TensorType>>
struct eigen_allocator_impl<TensorType, Eigen::TensorBase<TensorType> >
: eigen_allocator_impl_tensor<TensorType> {};
template <typename TensorType>
struct eigen_allocator_impl<const TensorType,
const Eigen::TensorBase<TensorType>>
const Eigen::TensorBase<TensorType> >
: eigen_allocator_impl_tensor<const TensorType> {};
template <typename TensorType>
......@@ -334,19 +388,19 @@ struct eigen_allocator_impl_tensor {
copy(pyArray, tensor);
}
#define EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(TensorType, Scalar, \
NewScalar, pyArray, tensor) \
details::cast<Scalar, NewScalar>::run( \
NumpyMap<TensorType, Scalar>::map(pyArray, \
details::check_swap(pyArray, tensor)), \
tensor)
#define EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(TensorType, Scalar, \
NewScalar, pyArray, tensor) \
{ \
typename NumpyMap<TensorType, Scalar>::EigenMap pyArray_map = \
NumpyMap<TensorType, Scalar>::map( \
pyArray, details::check_swap(pyArray, tensor)); \
details::cast<Scalar, NewScalar, Eigen::TensorRef>::run(pyArray_map, \
tensor); \
}
/// \brief Copy Python array into the input matrix mat.
template <typename TensorDerived>
static void copy(PyArrayObject *pyArray,
const Eigen::TensorBase<TensorDerived> &tensor_) {
TensorDerived &tensor = const_cast<TensorDerived &>(
static_cast<const TensorDerived &>(tensor_));
static void copy(PyArrayObject *pyArray, TensorDerived &tensor) {
const int pyArray_type_code = EIGENPY_GET_PY_ARRAY_TYPE(pyArray);
const int Scalar_type_code = Register::getTypeCode<Scalar>();
......@@ -356,49 +410,20 @@ struct eigen_allocator_impl_tensor {
return;
}
switch (pyArray_type_code) {
case NPY_INT:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(TensorType, int, Scalar,
pyArray, tensor);
break;
case NPY_LONG:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(TensorType, long, Scalar,
pyArray, tensor);
break;
case NPY_FLOAT:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(TensorType, float, Scalar,
pyArray, tensor);
break;
case NPY_CFLOAT:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(
TensorType, std::complex<float>, Scalar, pyArray, tensor);
break;
case NPY_DOUBLE:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(TensorType, double, Scalar,
pyArray, tensor);
break;
case NPY_CDOUBLE:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(
TensorType, std::complex<double>, Scalar, pyArray, tensor);
break;
case NPY_LONGDOUBLE:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(TensorType, long double,
Scalar, pyArray, tensor);
break;
case NPY_CLONGDOUBLE:
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR(
TensorType, std::complex<long double>, Scalar, pyArray, tensor);
break;
default:
throw Exception("You asked for a conversion which is not implemented.");
}
EIGENPY_CAST_FROM_NUMPY_TO_EIGEN_SWITCH(
pyArray_type_code, TensorType, Scalar, pyArray, tensor,
EIGENPY_CAST_FROM_PYARRAY_TO_EIGEN_TENSOR);
}
#define EIGENPY_CAST_FROM_EIGEN_TENSOR_TO_PYARRAY(TensorType, Scalar, \
NewScalar, tensor, pyArray) \
details::cast<Scalar, NewScalar>::run( \
tensor, NumpyMap<TensorType, NewScalar>::map( \
pyArray, details::check_swap(pyArray, tensor)))
{ \
typename NumpyMap<TensorType, NewScalar>::EigenMap pyArray_map = \
NumpyMap<TensorType, NewScalar>::map( \
pyArray, details::check_swap(pyArray, tensor)); \
details::cast<Scalar, NewScalar, Eigen::TensorRef>::run(tensor, \
pyArray_map); \
}
/// \brief Copy mat into the Python array using Eigen::Map
static void copy(const TensorType &tensor, PyArrayObject *pyArray) {
......@@ -412,42 +437,8 @@ struct eigen_allocator_impl_tensor {
return;
}
switch (pyArray_type_code) {
case NPY_INT:
EIGENPY_CAST_FROM_EIGEN_TENSOR_TO_PYARRAY(TensorType, Scalar, int,
tensor, pyArray);
break;
case NPY_LONG:
EIGENPY_CAST_FROM_EIGEN_TENSOR_TO_PYARRAY(TensorType, Scalar, long,
tensor, pyArray);
break;
case NPY_FLOAT:
EIGENPY_CAST_FROM_EIGEN_TENSOR_TO_PYARRAY(TensorType, Scalar, float,
tensor, pyArray);
break;
case NPY_CFLOAT:
EIGENPY_CAST_FROM_EIGEN_TENSOR_TO_PYARRAY(
TensorType, Scalar, std::complex<float>, tensor, pyArray);
break;
case NPY_DOUBLE:
EIGENPY_CAST_FROM_EIGEN_TENSOR_TO_PYARRAY(TensorType, Scalar, double,
tensor, pyArray);
break;
case NPY_CDOUBLE:
EIGENPY_CAST_FROM_EIGEN_TENSOR_TO_PYARRAY(
TensorType, Scalar, std::complex<double>, tensor, pyArray);
break;
case NPY_LONGDOUBLE:
EIGENPY_CAST_FROM_EIGEN_TENSOR_TO_PYARRAY(TensorType, Scalar,
long double, tensor, pyArray);
break;
case NPY_CLONGDOUBLE:
EIGENPY_CAST_FROM_EIGEN_TENSOR_TO_PYARRAY(
TensorType, Scalar, std::complex<long double>, tensor, pyArray);
break;
default:
throw Exception("You asked for a conversion which is not implemented.");
}
throw Exception(
"Scalar conversion from Eigen to Numpy is not implemented.");
}
};
#endif
......@@ -471,7 +462,7 @@ inline bool is_arr_layout_compatible_with_mat_type(PyArrayObject *pyArray) {
}
template <typename MatType, int Options, typename Stride>
struct eigen_allocator_impl_matrix<Eigen::Ref<MatType, Options, Stride>> {
struct eigen_allocator_impl_matrix<Eigen::Ref<MatType, Options, Stride> > {
typedef Eigen::Ref<MatType, Options, Stride> RefType;
typedef typename MatType::Scalar Scalar;
......@@ -532,7 +523,7 @@ struct eigen_allocator_impl_matrix<Eigen::Ref<MatType, Options, Stride>> {
template <typename MatType, int Options, typename Stride>
struct eigen_allocator_impl_matrix<
const Eigen::Ref<const MatType, Options, Stride>> {
const Eigen::Ref<const MatType, Options, Stride> > {
typedef const Eigen::Ref<const MatType, Options, Stride> RefType;
typedef typename MatType::Scalar Scalar;
......@@ -599,14 +590,14 @@ template <typename TensorType, typename TensorRef>
struct eigen_allocator_impl_tensor_ref;
template <typename TensorType>
struct eigen_allocator_impl_tensor<Eigen::TensorRef<TensorType>>
struct eigen_allocator_impl_tensor<Eigen::TensorRef<TensorType> >
: eigen_allocator_impl_tensor_ref<TensorType,
Eigen::TensorRef<TensorType>> {};
Eigen::TensorRef<TensorType> > {};
template <typename TensorType>
struct eigen_allocator_impl_tensor<const Eigen::TensorRef<const TensorType>>
struct eigen_allocator_impl_tensor<const Eigen::TensorRef<const TensorType> >
: eigen_allocator_impl_tensor_ref<
const TensorType, const Eigen::TensorRef<const TensorType>> {};
const TensorType, const Eigen::TensorRef<const TensorType> > {};
template <typename TensorType, typename RefType>
struct eigen_allocator_impl_tensor_ref {
......@@ -648,14 +639,15 @@ struct eigen_allocator_impl_tensor_ref {
void *raw_ptr = storage->storage.bytes;
if (need_to_allocate) {
TensorType *tensor_ptr;
tensor_ptr = details::init_tensor<TensorType>::run(pyArray);
typedef typename boost::remove_const<TensorType>::type TensorTypeNonConst;
TensorTypeNonConst *tensor_ptr;
tensor_ptr = details::init_tensor<TensorTypeNonConst>::run(pyArray);
RefType tensor_ref(*tensor_ptr);
new (raw_ptr) StorageType(tensor_ref, pyArray, tensor_ptr);
RefType &tensor = *reinterpret_cast<RefType *>(raw_ptr);
EigenAllocator<TensorType>::copy(pyArray, tensor);
TensorTypeNonConst &tensor = *tensor_ptr;
EigenAllocator<TensorTypeNonConst>::copy(pyArray, tensor);
} else {
assert(pyArray_type_code == Scalar_type_code);
typename NumpyMap<TensorType, Scalar, Options>::EigenMap numpyMap =
......
......@@ -62,7 +62,7 @@ struct copy_if_non_const<const MatType, true> {
template <typename _RefType>
struct referent_storage_eigen_ref {
typedef _RefType RefType;
typedef typename get_eigen_ref_plain_type<RefType>::type PlainObjectType;
typedef typename get_eigen_plain_type<RefType>::type PlainObjectType;
typedef typename ::eigenpy::aligned_storage<
::boost::python::detail::referent_size<RefType &>::value>::type
AlignedStorage;
......@@ -290,7 +290,9 @@ struct eigen_from_py_impl<MatType, Eigen::MatrixBase<MatType> > {
static void registration();
};
template <typename EigenType, typename _Scalar>
template <typename EigenType,
typename Scalar =
typename boost::remove_reference<EigenType>::type::Scalar>
struct EigenFromPy : eigen_from_py_impl<EigenType> {};
template <typename MatType>
......@@ -557,4 +559,6 @@ struct EigenFromPy<const Eigen::Ref<const MatType, Options, Stride> > {
#include "eigenpy/tensor/eigen-from-python.hpp"
#endif
#include "eigenpy/sparse/eigen-from-python.hpp"
#endif // __eigenpy_eigen_from_python_hpp__
//
// Copyright (c) 2014-2023 CNRS INRIA
// Copyright (c) 2014-2024 CNRS INRIA
//
#ifndef __eigenpy_eigen_to_python_hpp__
......@@ -11,54 +11,11 @@
#include "eigenpy/eigen-allocator.hpp"
#include "eigenpy/numpy-allocator.hpp"
#include "eigenpy/scipy-allocator.hpp"
#include "eigenpy/numpy-type.hpp"
#include "eigenpy/scipy-type.hpp"
#include "eigenpy/registration.hpp"
namespace boost {
namespace python {
template <typename MatrixRef, class MakeHolder>
struct to_python_indirect_eigen {
template <class U>
inline PyObject* operator()(U const& mat) const {
return eigenpy::EigenToPy<MatrixRef>::convert(const_cast<U&>(mat));
}
#ifndef BOOST_PYTHON_NO_PY_SIGNATURES
inline PyTypeObject const* get_pytype() const {
return converter::registered_pytype<MatrixRef>::get_pytype();
}
#endif
};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime,
int Options, int MaxRowsAtCompileTime, int MaxColsAtCompileTime,
class MakeHolder>
struct to_python_indirect<
Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime, Options,
MaxRowsAtCompileTime, MaxColsAtCompileTime>&,
MakeHolder>
: to_python_indirect_eigen<
Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime, Options,
MaxRowsAtCompileTime, MaxColsAtCompileTime>&,
MakeHolder> {};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime,
int Options, int MaxRowsAtCompileTime, int MaxColsAtCompileTime,
class MakeHolder>
struct to_python_indirect<
const Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime, Options,
MaxRowsAtCompileTime, MaxColsAtCompileTime>&,
MakeHolder>
: to_python_indirect_eigen<
const Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime,
Options, MaxRowsAtCompileTime,
MaxColsAtCompileTime>&,
MakeHolder> {};
} // namespace python
} // namespace boost
namespace eigenpy {
EIGENPY_DOCUMENTATION_START_IGNORE
......@@ -101,9 +58,8 @@ struct eigen_to_py_impl_matrix {
PyArrayObject* pyArray;
// Allocate Python memory
if ((((!(C == 1) != !(R == 1)) && !MatrixDerived::IsVectorAtCompileTime) ||
MatrixDerived::IsVectorAtCompileTime) &&
NumpyType::getType() ==
ARRAY_TYPE) // Handle array with a single dimension
MatrixDerived::IsVectorAtCompileTime)) // Handle array with a single
// dimension
{
npy_intp shape[1] = {C == 1 ? R : C};
pyArray = NumpyAllocator<MatType>::allocate(
......@@ -117,6 +73,50 @@ struct eigen_to_py_impl_matrix {
// Create an instance (either np.array or np.matrix)
return NumpyType::make(pyArray).ptr();
}
static PyTypeObject const* get_pytype() { return getPyArrayType(); }
};
template <typename MatType>
struct eigen_to_py_impl_sparse_matrix;
template <typename MatType>
struct eigen_to_py_impl<MatType, Eigen::SparseMatrixBase<MatType> >
: eigen_to_py_impl_sparse_matrix<MatType> {};
template <typename MatType>
struct eigen_to_py_impl<MatType&, Eigen::SparseMatrixBase<MatType> >
: eigen_to_py_impl_sparse_matrix<MatType&> {};
template <typename MatType>
struct eigen_to_py_impl<const MatType, const Eigen::SparseMatrixBase<MatType> >
: eigen_to_py_impl_sparse_matrix<const MatType> {};
template <typename MatType>
struct eigen_to_py_impl<const MatType&, const Eigen::SparseMatrixBase<MatType> >
: eigen_to_py_impl_sparse_matrix<const MatType&> {};
template <typename MatType>
struct eigen_to_py_impl_sparse_matrix {
enum { IsRowMajor = MatType::IsRowMajor };
static PyObject* convert(
typename boost::add_reference<
typename boost::add_const<MatType>::type>::type mat) {
typedef typename boost::remove_const<
typename boost::remove_reference<MatType>::type>::type MatrixDerived;
// Allocate and perform the copy
PyObject* pyArray =
ScipyAllocator<MatType>::allocate(const_cast<MatrixDerived&>(mat));
return pyArray;
}
static PyTypeObject const* get_pytype() {
return IsRowMajor ? ScipyType::getScipyCSRMatrixType()
: ScipyType::getScipyCSCMatrixType();
}
};
#ifdef EIGENPY_WITH_TENSOR_SUPPORT
......@@ -150,15 +150,17 @@ struct eigen_to_py_impl_tensor {
// Create an instance (either np.array or np.matrix)
return NumpyType::make(pyArray).ptr();
}
static PyTypeObject const* get_pytype() { return getPyArrayType(); }
};
#endif
EIGENPY_DOCUMENTATION_END_IGNORE
template <typename EigenType, typename Scalar>
struct EigenToPy : eigen_to_py_impl<EigenType> {
static PyTypeObject const* get_pytype() { return getPyArrayType(); }
};
template <typename EigenType,
typename Scalar =
typename boost::remove_reference<EigenType>::type::Scalar>
struct EigenToPy : eigen_to_py_impl<EigenType> {};
template <typename MatType>
struct EigenToPyConverter {
......@@ -166,6 +168,52 @@ struct EigenToPyConverter {
bp::to_python_converter<MatType, EigenToPy<MatType>, true>();
}
};
} // namespace eigenpy
namespace boost {
namespace python {
template <typename MatrixRef, class MakeHolder>
struct to_python_indirect_eigen {
template <class U>
inline PyObject* operator()(U const& mat) const {
return eigenpy::EigenToPy<MatrixRef>::convert(const_cast<U&>(mat));
}
#ifndef BOOST_PYTHON_NO_PY_SIGNATURES
inline PyTypeObject const* get_pytype() const {
return converter::registered_pytype<MatrixRef>::get_pytype();
}
#endif
};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime,
int Options, int MaxRowsAtCompileTime, int MaxColsAtCompileTime,
class MakeHolder>
struct to_python_indirect<
Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime, Options,
MaxRowsAtCompileTime, MaxColsAtCompileTime>&,
MakeHolder>
: to_python_indirect_eigen<
Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime, Options,
MaxRowsAtCompileTime, MaxColsAtCompileTime>&,
MakeHolder> {};
template <typename Scalar, int RowsAtCompileTime, int ColsAtCompileTime,
int Options, int MaxRowsAtCompileTime, int MaxColsAtCompileTime,
class MakeHolder>
struct to_python_indirect<
const Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime, Options,
MaxRowsAtCompileTime, MaxColsAtCompileTime>&,
MakeHolder>
: to_python_indirect_eigen<
const Eigen::Matrix<Scalar, RowsAtCompileTime, ColsAtCompileTime,
Options, MaxRowsAtCompileTime,
MaxColsAtCompileTime>&,
MakeHolder> {};
} // namespace python
} // namespace boost
#endif // __eigenpy_eigen_to_python_hpp__
......@@ -32,6 +32,7 @@
EIGENPY_MAKE_FIXED_TYPEDEFS(Type, Options, TypeSuffix, 2) \
EIGENPY_MAKE_FIXED_TYPEDEFS(Type, Options, TypeSuffix, 3) \
EIGENPY_MAKE_FIXED_TYPEDEFS(Type, Options, TypeSuffix, 4) \
EIGENPY_MAKE_TYPEDEFS(Type, Options, TypeSuffix, 1, 1)
EIGENPY_MAKE_TYPEDEFS(Type, Options, TypeSuffix, 1, 1) \
typedef Eigen::SparseMatrix<Scalar, Options> SparseMatrixX##TypeSuffix
#endif // ifndef __eigenpy_eigen_typedef_hpp__
/*
* Copyright 2024 INRIA
*/
#ifndef __eigenpy_eigen_eigen_base_hpp__
#define __eigenpy_eigen_eigen_base_hpp__
#include "eigenpy/eigenpy.hpp"
namespace eigenpy {
template <typename Derived>
struct EigenBaseVisitor
: public boost::python::def_visitor<EigenBaseVisitor<Derived> > {
template <class PyClass>
void visit(PyClass &cl) const {
cl.def("cols", &Derived::cols, bp::arg("self"),
"Returns the number of columns.")
.def("rows", &Derived::rows, bp::arg("self"),
"Returns the number of rows.")
.def("size", &Derived::rows, bp::arg("self"),
"Returns the number of coefficients, which is rows()*cols().");
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_eigen_eigen_base_hpp__
/*
* Copyright 2014-2019, CNRS
* Copyright 2018-2023, INRIA
* Copyright 2018-2024, INRIA
*/
#ifndef __eigenpy_eigenpy_hpp__
......@@ -10,6 +10,9 @@
#include "eigenpy/eigen-typedef.hpp"
#include "eigenpy/expose.hpp"
/// Custom CallPolicies
#include "eigenpy/std-unique-ptr.hpp"
#define ENABLE_SPECIFIC_MATRIX_TYPE(TYPE) \
::eigenpy::enableEigenPySpecific<TYPE>();
......@@ -19,6 +22,8 @@ namespace eigenpy {
*/
void EIGENPY_DLLAPI enableEigenPy();
bool EIGENPY_DLLAPI withTensorSupport();
/* Enable the Eigen--Numpy serialization for the templated MatType class.*/
template <typename MatType>
void enableEigenPySpecific();
......@@ -52,15 +57,19 @@ EIGEN_DONT_INLINE void exposeType() {
ENABLE_SPECIFIC_MATRIX_TYPE(VectorXs);
ENABLE_SPECIFIC_MATRIX_TYPE(RowVectorXs);
ENABLE_SPECIFIC_MATRIX_TYPE(MatrixXs);
enableEigenPySpecific<SparseMatrixXs>();
}
template <typename Scalar>
EIGEN_DONT_INLINE void exposeType() {
exposeType<Scalar, 0>();
#ifdef EIGENPY_WITH_TENSOR_SUPPORT
enableEigenPySpecific<Eigen::Tensor<Scalar, 1> >();
enableEigenPySpecific<Eigen::Tensor<Scalar, 2> >();
enableEigenPySpecific<Eigen::Tensor<Scalar, 3> >();
#endif
}
} // namespace eigenpy
......
/*
* Copyright 2014-2023 CNRS INRIA
* Copyright 2014-2024 CNRS INRIA
*/
#ifndef __eigenpy_fwd_hpp__
......@@ -43,9 +43,8 @@
EIGENPY_PRAGMA_WARNING(Deprecated : the_message)
#define EIGENPY_PRAGMA_DEPRECATED_HEADER(old_header, new_header) \
EIGENPY_PRAGMA_WARNING( \
Deprecated header file \
: #old_header has been replaced \
by #new_header.\n Please use #new_header instead of #old_header.)
Deprecated header file : #old_header has been replaced \
by #new_header.\n Please use #new_header instead of #old_header.)
#elif defined(WIN32)
#define EIGENPY_PRAGMA(x) __pragma(#x)
#define EIGENPY_PRAGMA_MESSAGE(the_message) \
......@@ -65,6 +64,7 @@
#define EIGENPY_DOCUMENTATION_END_IGNORE /// \endcond
#include "eigenpy/config.hpp"
#include <boost/type_traits/is_base_of.hpp>
// Silence a warning about a deprecated use of boost bind by boost python
// at least fo boost 1.73 to 1.75
......@@ -73,6 +73,9 @@
#include <boost/python.hpp>
#include <boost/python/scope.hpp>
#include <type_traits>
#include <utility>
namespace eigenpy {
namespace bp = boost::python;
......@@ -86,6 +89,7 @@ namespace bp = boost::python;
#undef BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <Eigen/Core>
#include <Eigen/Sparse>
#include <Eigen/Geometry>
#ifdef EIGENPY_WITH_CXX11_SUPPORT
......@@ -104,7 +108,13 @@ namespace bp = boost::python;
#define EIGENPY_NO_ALIGNMENT_VALUE Eigen::Unaligned
#define EIGENPY_UNUSED_VARIABLE(var) (void)(var)
#define EIGENPY_UNUSED_TYPE(type) (type *)(NULL)
#define EIGENPY_UNUSED_TYPE(type) EIGENPY_UNUSED_VARIABLE((type *)(NULL))
#ifndef NDEBUG
#define EIGENPY_USED_VARIABLE_ONLY_IN_DEBUG_MODE(var)
#else
#define EIGENPY_USED_VARIABLE_ONLY_IN_DEBUG_MODE(var) \
EIGENPY_UNUSED_VARIABLE(var)
#endif
#ifdef EIGENPY_WITH_CXX11_SUPPORT
#include <memory>
......@@ -115,13 +125,13 @@ namespace bp = boost::python;
#endif
namespace eigenpy {
template <typename MatType,
typename Scalar =
typename boost::remove_reference<MatType>::type::Scalar>
// Default Scalar value can't be defined in the declaration
// because of a CL bug.
// See https://github.com/stack-of-tasks/eigenpy/pull/462
template <typename MatType, typename Scalar>
struct EigenToPy;
template <typename MatType,
typename Scalar =
typename boost::remove_reference<MatType>::type::Scalar>
template <typename MatType, typename Scalar>
struct EigenFromPy;
template <typename T>
......@@ -135,17 +145,20 @@ struct get_eigen_base_type {
typedef typename remove_const_reference<EigenType>::type EigenType_;
typedef typename boost::mpl::if_<
boost::is_base_of<Eigen::MatrixBase<EigenType_>, EigenType_>,
Eigen::MatrixBase<EigenType_>
#ifdef EIGENPY_WITH_TENSOR_SUPPORT
,
Eigen::MatrixBase<EigenType_>,
typename boost::mpl::if_<
boost::is_base_of<Eigen::TensorBase<EigenType_>, EigenType_>,
Eigen::TensorBase<EigenType_>, void>::type
boost::is_base_of<Eigen::SparseMatrixBase<EigenType_>, EigenType_>,
Eigen::SparseMatrixBase<EigenType_>
#ifdef EIGENPY_WITH_TENSOR_SUPPORT
,
typename boost::mpl::if_<
boost::is_base_of<Eigen::TensorBase<EigenType_>, EigenType_>,
Eigen::TensorBase<EigenType_>, void>::type
#else
,
void
,
void
#endif
>::type _type;
>::type>::type _type;
typedef typename boost::mpl::if_<
boost::is_const<typename boost::remove_reference<EigenType>::type>,
......@@ -153,22 +166,39 @@ struct get_eigen_base_type {
};
template <typename EigenType>
struct get_eigen_ref_plain_type;
struct get_eigen_plain_type;
template <typename MatType, int Options, typename Stride>
struct get_eigen_ref_plain_type<Eigen::Ref<MatType, Options, Stride> > {
struct get_eigen_plain_type<Eigen::Ref<MatType, Options, Stride> > {
typedef typename Eigen::internal::traits<
Eigen::Ref<MatType, Options, Stride> >::PlainObjectType type;
};
#ifdef EIGENPY_WITH_TENSOR_SUPPORT
template <typename TensorType>
struct get_eigen_ref_plain_type<Eigen::TensorRef<TensorType> > {
struct get_eigen_plain_type<Eigen::TensorRef<TensorType> > {
typedef TensorType type;
};
#endif
namespace internal {
template <class T1, class T2>
struct has_operator_equal_impl {
template <class U, class V>
static auto check(U *) -> decltype(std::declval<U>() == std::declval<V>());
template <typename, typename>
static auto check(...) -> std::false_type;
using type = typename std::is_same<bool, decltype(check<T1, T2>(0))>::type;
};
} // namespace internal
template <class T1, class T2 = T1>
struct has_operator_equal : internal::has_operator_equal_impl<T1, T2>::type {};
} // namespace eigenpy
#include "eigenpy/alignment.hpp"
#include "eigenpy/id.hpp"
#endif // ifndef __eigenpy_fwd_hpp__
//
// Copyright (c) 2024 INRIA
//
#ifndef __eigenpy_id_hpp__
#define __eigenpy_id_hpp__
#include <boost/python.hpp>
#include <boost/cstdint.hpp>
namespace eigenpy {
///
/// \brief Add the Python method id to retrieving a unique id for a given object
/// exposed with Boost.Python
///
template <class C>
struct IdVisitor : public bp::def_visitor<IdVisitor<C> > {
template <class PyClass>
void visit(PyClass& cl) const {
cl.def("id", &id, bp::arg("self"),
"Returns the unique identity of an object.\n"
"For object held in C++, it corresponds to its memory address.");
}
private:
static boost::int64_t id(const C& self) {
return boost::int64_t(reinterpret_cast<const void*>(&self));
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_id_hpp__
/// Copyright (c) 2016-2024 CNRS INRIA
/// This file was originally taken from Pinocchio (header
/// <pinocchio/bindings/python/utils/std-vector.hpp>)
///
#ifndef __eigenpy_map_hpp__
#define __eigenpy_map_hpp__
#include "eigenpy/pickle-vector.hpp"
#include "eigenpy/registration.hpp"
#include "eigenpy/utils/empty-visitor.hpp"
#include <boost/python/suite/indexing/map_indexing_suite.hpp>
#include <boost/python/stl_iterator.hpp>
#include <boost/python/to_python_converter.hpp>
namespace eigenpy {
/// \brief Change the behavior of indexing (method __getitem__ in Python).
/// This is suitable e.g. for container of Eigen matrix objects if you want to
/// mutate them.
/// \sa overload_base_get_item_for_std_vector
template <typename Container>
struct overload_base_get_item_for_map
: public boost::python::def_visitor<
overload_base_get_item_for_map<Container> > {
typedef typename Container::value_type value_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::key_type key_type;
typedef typename Container::key_type index_type;
template <class Class>
void visit(Class& cl) const {
cl.def("__getitem__", &base_get_item);
}
private:
static boost::python::object base_get_item(
boost::python::back_reference<Container&> container, PyObject* i_) {
index_type idx = convert_index(container.get(), i_);
typename Container::iterator i = container.get().find(idx);
if (i == container.get().end()) {
PyErr_SetString(PyExc_KeyError, "Invalid key");
boost::python::throw_error_already_set();
}
typename boost::python::to_python_indirect<
data_type&, boost::python::detail::make_reference_holder>
convert;
return boost::python::object(boost::python::handle<>(convert(i->second)));
}
static index_type convert_index(Container& /*container*/, PyObject* i_) {
boost::python::extract<key_type const&> i(i_);
if (i.check()) {
return i();
} else {
boost::python::extract<key_type> i(i_);
if (i.check()) return i();
}
PyErr_SetString(PyExc_TypeError, "Invalid index type");
boost::python::throw_error_already_set();
return index_type();
}
};
///////////////////////////////////////////////////////////////////////////////
// The following snippet of code has been taken from the header
// https://github.com/loco-3d/crocoddyl/blob/v2.1.0/bindings/python/crocoddyl/utils/map-converter.hpp
// The Crocoddyl library is written by Carlos Mastalli, Nicolas Mansard and
// Rohan Budhiraja.
///////////////////////////////////////////////////////////////////////////////
namespace bp = boost::python;
/**
* @brief Create a pickle interface for the map type
*
* @param[in] Container Map type to be pickled
* \sa Pickle
*/
template <typename Container>
struct PickleMap : public PickleVector<Container> {
static void setstate(bp::object op, bp::tuple tup) {
Container& o = bp::extract<Container&>(op)();
bp::stl_input_iterator<typename Container::value_type> begin(tup[0]), end;
o.insert(begin, end);
}
};
/// Conversion from dict to map solution proposed in
/// https://stackoverflow.com/questions/6116345/boostpython-possible-to-automatically-convert-from-dict-stdmap
/// This template encapsulates the conversion machinery.
template <typename Container>
struct dict_to_map {
static void register_converter() {
bp::converter::registry::push_back(&dict_to_map::convertible,
&dict_to_map::construct,
bp::type_id<Container>());
}
/// Check if conversion is possible
static void* convertible(PyObject* object) {
// Check if it is a list
if (!PyObject_GetIter(object)) return 0;
return object;
}
/// Perform the conversion
static void construct(PyObject* object,
bp::converter::rvalue_from_python_stage1_data* data) {
// convert the PyObject pointed to by `object` to a bp::dict
bp::handle<> handle(bp::borrowed(object)); // "smart ptr"
bp::dict dict(handle);
// get a pointer to memory into which we construct the map
// this is provided by the Python runtime
typedef bp::converter::rvalue_from_python_storage<Container> storage_type;
void* storage = reinterpret_cast<storage_type*>(data)->storage.bytes;
// placement-new allocate the result
new (storage) Container();
// iterate over the dictionary `dict`, fill up the map `map`
Container& map(*(static_cast<Container*>(storage)));
bp::list keys(dict.keys());
int keycount(static_cast<int>(bp::len(keys)));
for (int i = 0; i < keycount; ++i) {
// get the key
bp::object keyobj(keys[i]);
bp::extract<typename Container::key_type> keyproxy(keyobj);
if (!keyproxy.check()) {
PyErr_SetString(PyExc_KeyError, "Bad key type");
bp::throw_error_already_set();
}
typename Container::key_type key = keyproxy();
// get the corresponding value
bp::object valobj(dict[keyobj]);
bp::extract<typename Container::mapped_type> valproxy(valobj);
if (!valproxy.check()) {
PyErr_SetString(PyExc_ValueError, "Bad value type");
bp::throw_error_already_set();
}
typename Container::mapped_type val = valproxy();
map.emplace(key, val);
}
// remember the location for later
data->convertible = storage;
}
static bp::dict todict(Container& self) {
bp::dict dict;
typename Container::const_iterator it;
for (it = self.begin(); it != self.end(); ++it) {
dict.setdefault(it->first, it->second);
}
return dict;
}
};
/// Policies which handle the non-default constructible case
/// and set_item() using emplace().
template <class Container, bool NoProxy>
struct emplace_set_derived_policies
: bp::map_indexing_suite<
Container, NoProxy,
emplace_set_derived_policies<Container, NoProxy> > {
typedef typename Container::key_type index_type;
typedef typename Container::value_type::second_type data_type;
typedef typename Container::value_type value_type;
using DerivedPolicies =
bp::detail::final_map_derived_policies<Container, NoProxy>;
template <class Class>
static void extension_def(Class& cl) {
// Wrap the map's element (value_type)
std::string elem_name = "map_indexing_suite_";
bp::object class_name(cl.attr("__name__"));
bp::extract<std::string> class_name_extractor(class_name);
elem_name += class_name_extractor();
elem_name += "_entry";
namespace mpl = boost::mpl;
typedef typename mpl::if_<
mpl::and_<boost::is_class<data_type>, mpl::bool_<!NoProxy> >,
bp::return_internal_reference<>, bp::default_call_policies>::type
get_data_return_policy;
bp::class_<value_type>(elem_name.c_str(), bp::no_init)
.def("__repr__", &DerivedPolicies::print_elem)
.def("data", &DerivedPolicies::get_data, get_data_return_policy())
.def("key", &DerivedPolicies::get_key);
}
static void set_item(Container& container, index_type i, data_type const& v) {
container.emplace(i, v);
}
};
/**
* @brief Expose the map-like container, e.g. (std::map).
*
* @param[in] Container Container to expose.
* @param[in] NoProxy When set to false, the elements will be copied when
* returned to Python.
*/
template <class Container, bool NoProxy = false>
struct GenericMapVisitor
: public emplace_set_derived_policies<Container, NoProxy>,
public dict_to_map<Container> {
typedef dict_to_map<Container> FromPythonDictConverter;
template <typename DerivedVisitor>
static void expose(const std::string& class_name,
const std::string& doc_string,
const bp::def_visitor<DerivedVisitor>& visitor) {
namespace bp = bp;
if (!register_symbolic_link_to_registered_type<Container>()) {
bp::class_<Container>(class_name.c_str(), doc_string.c_str())
.def(GenericMapVisitor())
.def("todict", &FromPythonDictConverter::todict, bp::arg("self"),
"Returns the map type as a Python dictionary.")
.def_pickle(PickleMap<Container>())
.def(visitor);
// Register conversion
FromPythonDictConverter::register_converter();
}
}
static void expose(const std::string& class_name,
const std::string& doc_string = "") {
expose(class_name, doc_string, EmptyPythonVisitor());
}
template <typename DerivedVisitor>
static void expose(const std::string& class_name,
const bp::def_visitor<DerivedVisitor>& visitor) {
expose(class_name, "", visitor);
}
};
} // namespace eigenpy
#endif // ifndef __eigenpy_map_hpp__
......@@ -78,8 +78,8 @@ struct numpy_allocator_impl<const TensorType,
template <typename TensorType>
struct numpy_allocator_impl_tensor {
template <typename TensorDerived>
static PyArrayObject *allocate(const Eigen::TensorBase<TensorDerived> &tensor,
npy_intp nd, npy_intp *shape) {
static PyArrayObject *allocate(const TensorDerived &tensor, npy_intp nd,
npy_intp *shape) {
const int code = Register::getTypeCode<typename TensorDerived::Scalar>();
PyArrayObject *pyArray = (PyArrayObject *)call_PyArray_SimpleNew(
static_cast<int>(nd), shape, code);
......@@ -138,7 +138,12 @@ struct numpy_allocator_impl_matrix<Eigen::Ref<MatType, Options, Stride> > {
outer_stride = reverse_strides ? mat.innerStride()
: mat.outerStride();
#if NPY_ABI_VERSION < 0x02000000
const int elsize = call_PyArray_DescrFromType(Scalar_type_code)->elsize;
#else
const int elsize =
PyDataType_ELSIZE(call_PyArray_DescrFromType(Scalar_type_code));
#endif
npy_intp strides[2] = {elsize * inner_stride, elsize * outer_stride};
PyArrayObject *pyArray = (PyArrayObject *)call_PyArray_New(
......@@ -204,7 +209,12 @@ struct numpy_allocator_impl_matrix<
outer_stride = reverse_strides ? mat.innerStride()
: mat.outerStride();
#if NPY_ABI_VERSION < 0x02000000
const int elsize = call_PyArray_DescrFromType(Scalar_type_code)->elsize;
#else
const int elsize =
PyDataType_ELSIZE(call_PyArray_DescrFromType(Scalar_type_code));
#endif
npy_intp strides[2] = {elsize * inner_stride, elsize * outer_stride};
PyArrayObject *pyArray = (PyArrayObject *)call_PyArray_New(
......
......@@ -24,13 +24,13 @@ struct numpy_map_impl;
template <typename MatType, typename InputScalar, int AlignmentValue,
typename Stride>
struct numpy_map_impl<MatType, InputScalar, AlignmentValue, Stride,
Eigen::MatrixBase<MatType>>
Eigen::MatrixBase<MatType> >
: numpy_map_impl_matrix<MatType, InputScalar, AlignmentValue, Stride> {};
template <typename MatType, typename InputScalar, int AlignmentValue,
typename Stride>
struct numpy_map_impl<const MatType, InputScalar, AlignmentValue, Stride,
const Eigen::MatrixBase<MatType>>
const Eigen::MatrixBase<MatType> >
: numpy_map_impl_matrix<const MatType, InputScalar, AlignmentValue,
Stride> {};
......@@ -183,13 +183,13 @@ struct numpy_map_impl_tensor;
template <typename TensorType, typename InputScalar, int AlignmentValue,
typename Stride>
struct numpy_map_impl<TensorType, InputScalar, AlignmentValue, Stride,
Eigen::TensorBase<TensorType>>
Eigen::TensorBase<TensorType> >
: numpy_map_impl_tensor<TensorType, InputScalar, AlignmentValue, Stride> {};
template <typename TensorType, typename InputScalar, int AlignmentValue,
typename Stride>
struct numpy_map_impl<const TensorType, InputScalar, AlignmentValue, Stride,
const Eigen::TensorBase<TensorType>>
const Eigen::TensorBase<TensorType> >
: numpy_map_impl_tensor<const TensorType, InputScalar, AlignmentValue,
Stride> {};
......@@ -210,7 +210,7 @@ struct numpy_map_impl_tensor {
EIGENPY_UNUSED_VARIABLE(swap_dimensions);
assert(PyArray_NDIM(pyArray) == NumIndices || NumIndices == Eigen::Dynamic);
Eigen::DSizes<Index, NumIndices> dimensions(PyArray_NDIM(pyArray));
Eigen::DSizes<Index, NumIndices> dimensions;
for (int k = 0; k < PyArray_NDIM(pyArray); ++k)
dimensions[k] = PyArray_DIMS(pyArray)[k];
......