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 1182 additions and 307 deletions
/*
* 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__
......@@ -40,6 +40,24 @@ struct expose_eigen_type_impl<MatType, Eigen::MatrixBase<MatType>, Scalar> {
}
};
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, typename Scalar>
struct expose_eigen_type_impl<TensorType, Eigen::TensorBase<TensorType>,
......
......@@ -198,6 +198,91 @@ struct cast<Scalar, NewScalar, EigenBase, 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;
......@@ -247,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
......@@ -301,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.");
}
};
......@@ -394,42 +410,9 @@ 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, \
......@@ -454,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
......
......@@ -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,16 +290,10 @@ struct eigen_from_py_impl<MatType, Eigen::MatrixBase<MatType> > {
static void registration();
};
#ifdef EIGENPY_MSVC_COMPILER
template <typename EigenType>
struct EigenFromPy<EigenType,
typename boost::remove_reference<EigenType>::type::Scalar>
#else
template <typename EigenType, typename _Scalar>
struct EigenFromPy
#endif
: eigen_from_py_impl<EigenType> {
};
template <typename EigenType,
typename Scalar =
typename boost::remove_reference<EigenType>::type::Scalar>
struct EigenFromPy : eigen_from_py_impl<EigenType> {};
template <typename MatType>
void *eigen_from_py_impl<MatType, Eigen::MatrixBase<MatType> >::convertible(
......@@ -565,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,22 +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
#ifdef EIGENPY_MSVC_COMPILER
template <typename EigenType>
struct EigenToPy<EigenType,
typename boost::remove_reference<EigenType>::type::Scalar>
#else
template <typename EigenType, typename _Scalar>
struct EigenToPy
#endif
: 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 {
......@@ -173,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,6 +57,8 @@ 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>
......
/*
* 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
......@@ -105,6 +109,12 @@ namespace bp = boost::python;
#define EIGENPY_UNUSED_VARIABLE(var) (void)(var)
#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__
......@@ -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(
......
/*
* Copyright 2018-2020 INRIA
* Copyright 2018-2023 INRIA
*/
#ifndef __eigenpy_numpy_type_hpp__
......@@ -17,17 +17,54 @@ namespace eigenpy {
template <typename Scalar>
bool np_type_is_convertible_into_scalar(const int np_type) {
if (static_cast<NPY_TYPES>(NumpyEquivalentType<Scalar>::type_code) >=
NPY_USERDEF)
const auto scalar_np_code =
static_cast<NPY_TYPES>(NumpyEquivalentType<Scalar>::type_code);
if (scalar_np_code >= NPY_USERDEF)
return np_type == Register::getTypeCode<Scalar>();
if (NumpyEquivalentType<Scalar>::type_code == np_type) return true;
if (scalar_np_code == np_type) return true;
// Manage type promotion
switch (np_type) {
case NPY_BOOL:
return FromTypeToType<bool, Scalar>::value;
case NPY_INT8:
return FromTypeToType<int8_t, Scalar>::value;
case NPY_INT16:
return FromTypeToType<int16_t, Scalar>::value;
case NPY_INT32:
return FromTypeToType<int32_t, Scalar>::value;
case NPY_INT64:
return FromTypeToType<int64_t, Scalar>::value;
case NPY_UINT8:
return FromTypeToType<uint8_t, Scalar>::value;
case NPY_UINT16:
return FromTypeToType<uint16_t, Scalar>::value;
case NPY_UINT32:
return FromTypeToType<uint32_t, Scalar>::value;
case NPY_UINT64:
return FromTypeToType<uint64_t, Scalar>::value;
#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
case NPY_INT:
return FromTypeToType<int, Scalar>::value;
case NPY_LONG:
return FromTypeToType<long, Scalar>::value;
return FromTypeToType<int32_t, Scalar>::value;
case NPY_UINT:
return FromTypeToType<uint32_t, Scalar>::value;
#endif // WIN32
#if 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
case NPY_LONGLONG:
return FromTypeToType<int64_t, Scalar>::value;
case NPY_ULONGLONG:
return FromTypeToType<uint64_t, Scalar>::value;
#endif // MAC
case NPY_FLOAT:
return FromTypeToType<float, Scalar>::value;
case NPY_CFLOAT:
......@@ -45,54 +82,28 @@ bool np_type_is_convertible_into_scalar(const int np_type) {
}
}
enum NP_TYPE { MATRIX_TYPE, ARRAY_TYPE };
struct EIGENPY_DLLAPI NumpyType {
static NumpyType& getInstance();
operator bp::object() { return getInstance().CurrentNumpyType; }
static bp::object make(PyArrayObject* pyArray, bool copy = false);
static bp::object make(PyObject* pyObj, bool copy = false);
static void setNumpyType(bp::object& obj);
static void sharedMemory(const bool value);
static bool sharedMemory();
static void switchToNumpyArray();
static void switchToNumpyMatrix();
static NP_TYPE& getType();
static bp::object getNumpyType();
static const PyTypeObject* getNumpyMatrixType();
static const PyTypeObject* getNumpyArrayType();
static bool isMatrix();
static bool isArray();
protected:
NumpyType();
bp::object CurrentNumpyType;
bp::object pyModule;
// Numpy types
bp::object NumpyMatrixObject;
PyTypeObject* NumpyMatrixType;
// bp::object NumpyAsMatrixObject; PyTypeObject * NumpyAsMatrixType;
bp::object NumpyArrayObject;
PyTypeObject* NumpyArrayType;
NP_TYPE np_type;
bool shared_memory;
};
} // namespace eigenpy
......
/*
* Copyright 2020-2022 INRIA
* Copyright 2020-2024 INRIA
*/
#ifndef __eigenpy_numpy_hpp__
#define __eigenpy_numpy_hpp__
#include "eigenpy/fwd.hpp"
#include "eigenpy/config.hpp"
#ifndef PY_ARRAY_UNIQUE_SYMBOL
#define PY_ARRAY_UNIQUE_SYMBOL EIGENPY_ARRAY_API
#endif
// For compatibility with Numpy 2.x. See:
// https://numpy.org/devdocs/reference/c-api/array.html#c.NPY_API_SYMBOL_ATTRIBUTE
#define NPY_API_SYMBOL_ATTRIBUTE EIGENPY_DLLAPI
// When building with MSVC, Python headers use some pragma operator to link
// against the Python DLL.
// Unfortunately, it can link against the wrong build type of the library
// leading to some linking issue.
// Boost::Python provides a helper specifically dedicated to selecting the right
// Python library depending on build type, so let's make use of it.
// Numpy headers drags Python with them. As a result, it
// is necessary to include this helper before including Numpy.
// See: https://github.com/stack-of-tasks/eigenpy/pull/514
#include <boost/python/detail/wrap_python.hpp>
#include <numpy/numpyconfig.h>
#ifdef NPY_1_8_API_VERSION
#define NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION
#endif
// Allow compiling against NumPy 1.x and 2.x. See:
// https://github.com/numpy/numpy/blob/afea8fd66f6bdbde855f5aff0b4e73eb0213c646/doc/source/reference/c-api/array.rst#L1224
#if NPY_ABI_VERSION < 0x02000000
#define PyArray_DescrProto PyArray_Descr
#endif
#include <numpy/ndarrayobject.h>
#include <numpy/ufuncobject.h>
#if NPY_ABI_VERSION < 0x02000000
static inline PyArray_ArrFuncs* PyDataType_GetArrFuncs(PyArray_Descr* descr) {
return descr->f;
}
#endif
/* PEP 674 disallow using macros as l-values
see : https://peps.python.org/pep-0674/
*/
#if PY_VERSION_HEX < 0x030900A4 && !defined(Py_SET_TYPE)
static inline void _Py_SET_TYPE(PyObject* o, PyTypeObject* type) {
Py_TYPE(o) = type;
}
#define Py_SET_TYPE(o, type) _Py_SET_TYPE((PyObject*)(o), type)
#endif
#if defined _WIN32 || defined __CYGWIN__
#define EIGENPY_GET_PY_ARRAY_TYPE(array) \
call_PyArray_MinScalarType(array)->type_num
......@@ -26,68 +63,140 @@
#define EIGENPY_GET_PY_ARRAY_TYPE(array) PyArray_MinScalarType(array)->type_num
#endif
#include <complex>
namespace eigenpy {
void EIGENPY_DLLAPI import_numpy();
int EIGENPY_DLLAPI PyArray_TypeNum(PyTypeObject* type);
// By default, the Scalar is considered as a Python object
template <typename Scalar>
template <typename Scalar, typename Enable = void>
struct NumpyEquivalentType {
enum { type_code = NPY_USERDEF };
};
template <>
struct NumpyEquivalentType<float> {
enum { type_code = NPY_FLOAT };
struct NumpyEquivalentType<bool> {
enum { type_code = NPY_BOOL };
};
template <>
struct NumpyEquivalentType<std::complex<float> > {
enum { type_code = NPY_CFLOAT };
struct NumpyEquivalentType<char> {
enum { type_code = NPY_INT8 };
};
template <>
struct NumpyEquivalentType<double> {
enum { type_code = NPY_DOUBLE };
struct NumpyEquivalentType<unsigned char> {
enum { type_code = NPY_UINT8 };
};
template <>
struct NumpyEquivalentType<std::complex<double> > {
enum { type_code = NPY_CDOUBLE };
struct NumpyEquivalentType<int8_t> {
enum { type_code = NPY_INT8 };
};
template <>
struct NumpyEquivalentType<long double> {
enum { type_code = NPY_LONGDOUBLE };
struct NumpyEquivalentType<int16_t> {
enum { type_code = NPY_INT16 };
};
template <>
struct NumpyEquivalentType<std::complex<long double> > {
enum { type_code = NPY_CLONGDOUBLE };
struct NumpyEquivalentType<uint16_t> {
enum { type_code = NPY_UINT16 };
};
template <>
struct NumpyEquivalentType<bool> {
enum { type_code = NPY_BOOL };
struct NumpyEquivalentType<int32_t> {
enum { type_code = NPY_INT32 };
};
template <>
struct NumpyEquivalentType<uint32_t> {
enum { type_code = NPY_UINT32 };
};
// On Windows, long is a 32 bytes type but it's a different type than int
// See https://github.com/stack-of-tasks/eigenpy/pull/455
#if defined _WIN32 || defined __CYGWIN__
template <>
struct NumpyEquivalentType<long> {
enum { type_code = NPY_INT32 };
};
template <>
struct NumpyEquivalentType<unsigned long> {
enum { type_code = NPY_UINT32 };
};
#endif // WIN32
template <>
struct NumpyEquivalentType<int> {
enum { type_code = NPY_INT };
struct NumpyEquivalentType<int64_t> {
enum { type_code = NPY_INT64 };
};
template <>
struct NumpyEquivalentType<unsigned int> {
enum { type_code = NPY_UINT };
struct NumpyEquivalentType<uint64_t> {
enum { type_code = NPY_UINT64 };
};
// On Mac, long is a 64 bytes type but it's a different type than int64_t
// See https://github.com/stack-of-tasks/eigenpy/pull/455
#if defined __APPLE__
template <>
struct NumpyEquivalentType<long> {
enum { type_code = NPY_LONG };
enum { type_code = NPY_INT64 };
};
// #if defined _WIN32 || defined __CYGWIN__
template <>
struct NumpyEquivalentType<long long> {
struct NumpyEquivalentType<unsigned long> {
enum { type_code = NPY_UINT64 };
};
#endif // MAC
// On Linux, long long is a 64 bytes type but it's a different type than int64_t
// See https://github.com/stack-of-tasks/eigenpy/pull/455
#if defined __linux__
#include <type_traits>
template <typename Scalar>
struct NumpyEquivalentType<
Scalar,
typename std::enable_if<!std::is_same<int64_t, long long>::value &&
std::is_same<Scalar, long long>::value>::type> {
enum { type_code = NPY_LONGLONG };
};
// #else
// template <> struct NumpyEquivalentType<long long> { enum { type_code =
// NPY_LONGLONG };};
// #endif
template <typename Scalar>
struct NumpyEquivalentType<
Scalar, typename std::enable_if<
!std::is_same<uint64_t, unsigned long long>::value &&
std::is_same<Scalar, unsigned long long>::value>::type> {
enum { type_code = NPY_ULONGLONG };
};
#endif // Linux
template <>
struct NumpyEquivalentType<unsigned long> {
enum { type_code = NPY_ULONG };
struct NumpyEquivalentType<float> {
enum { type_code = NPY_FLOAT };
};
template <>
struct NumpyEquivalentType<double> {
enum { type_code = NPY_DOUBLE };
};
template <>
struct NumpyEquivalentType<long double> {
enum { type_code = NPY_LONGDOUBLE };
};
template <>
struct NumpyEquivalentType<std::complex<float> > {
enum { type_code = NPY_CFLOAT };
};
template <>
struct NumpyEquivalentType<std::complex<double> > {
enum { type_code = NPY_CDOUBLE };
};
template <>
struct NumpyEquivalentType<std::complex<long double> > {
enum { type_code = NPY_CLONGDOUBLE };
};
template <typename Scalar>
......@@ -122,7 +231,7 @@ EIGENPY_DLLAPI PyArray_Descr* call_PyArray_DescrFromType(int typenum);
EIGENPY_DLLAPI void call_PyArray_InitArrFuncs(PyArray_ArrFuncs* funcs);
EIGENPY_DLLAPI int call_PyArray_RegisterDataType(PyArray_Descr* dtype);
EIGENPY_DLLAPI int call_PyArray_RegisterDataType(PyArray_DescrProto* dtype);
EIGENPY_DLLAPI int call_PyArray_RegisterCanCast(PyArray_Descr* descr,
int totype,
......@@ -170,7 +279,7 @@ inline void call_PyArray_InitArrFuncs(PyArray_ArrFuncs* funcs) {
PyArray_InitArrFuncs(funcs);
}
inline int call_PyArray_RegisterDataType(PyArray_Descr* dtype) {
inline int call_PyArray_RegisterDataType(PyArray_DescrProto* dtype) {
return PyArray_RegisterDataType(dtype);
}
......
///
/// Copyright (c) 2023 CNRS INRIA
///
/// Definitions for exposing boost::optional<T> types.
/// Also works with std::optional.
......@@ -7,6 +9,8 @@
#include "eigenpy/fwd.hpp"
#include "eigenpy/eigen-from-python.hpp"
#include "eigenpy/registration.hpp"
#include <boost/optional.hpp>
#ifdef EIGENPY_WITH_CXX17_SUPPORT
#include <optional>
......@@ -35,6 +39,7 @@ struct expected_pytype_for_arg<std::optional<T> > : expected_pytype_for_arg<T> {
} // namespace boost
namespace eigenpy {
namespace detail {
/// Helper struct to decide which type is the "none" type for a specific
......@@ -56,6 +61,17 @@ struct nullopt_helper<std::optional> {
};
#endif
template <typename NoneType>
struct NoneToPython {
static PyObject *convert(const NoneType &) { Py_RETURN_NONE; }
static void registration() {
if (!check_registration<NoneType>()) {
bp::to_python_converter<NoneType, NoneToPython, false>();
}
}
};
template <typename T,
template <typename> class OptionalTpl = EIGENPY_DEFAULT_OPTIONAL>
struct OptionalToPython {
......@@ -72,7 +88,9 @@ struct OptionalToPython {
}
static void registration() {
bp::to_python_converter<OptionalTpl<T>, OptionalToPython, true>();
if (!check_registration<OptionalTpl<T> >()) {
bp::to_python_converter<OptionalTpl<T>, OptionalToPython, true>();
}
}
};
......