eigen.h revision 12037:d28054ac6ec9
1955SN/A/* 2955SN/A pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices 31762SN/A 4955SN/A Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch> 5955SN/A 6955SN/A All rights reserved. Use of this source code is governed by a 7955SN/A BSD-style license that can be found in the LICENSE file. 8955SN/A*/ 9955SN/A 10955SN/A#pragma once 11955SN/A 12955SN/A#include "numpy.h" 13955SN/A 14955SN/A#if defined(__INTEL_COMPILER) 15955SN/A# pragma warning(disable: 1682) // implicit conversion of a 64-bit integral type to a smaller integral type (potential portability problem) 16955SN/A#elif defined(__GNUG__) || defined(__clang__) 17955SN/A# pragma GCC diagnostic push 18955SN/A# pragma GCC diagnostic ignored "-Wconversion" 19955SN/A# pragma GCC diagnostic ignored "-Wdeprecated-declarations" 20955SN/A# if __GNUC__ >= 7 21955SN/A# pragma GCC diagnostic ignored "-Wint-in-bool-context" 22955SN/A# endif 23955SN/A#endif 24955SN/A 25955SN/A#include <Eigen/Core> 26955SN/A#include <Eigen/SparseCore> 27955SN/A 282665Ssaidi@eecs.umich.edu#if defined(_MSC_VER) 294762Snate@binkert.org# pragma warning(push) 30955SN/A# pragma warning(disable: 4127) // warning C4127: Conditional expression is constant 315522Snate@binkert.org#endif 326143Snate@binkert.org 334762Snate@binkert.org// Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit 345522Snate@binkert.org// move constructors that break things. We could detect this an explicitly copy, but an extra copy 35955SN/A// of matrices seems highly undesirable. 365522Snate@binkert.orgstatic_assert(EIGEN_VERSION_AT_LEAST(3,2,7), "Eigen support in pybind11 requires Eigen >= 3.2.7"); 37955SN/A 385522Snate@binkert.orgNAMESPACE_BEGIN(pybind11) 394202Sbinkertn@umich.edu 405742Snate@binkert.org// Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides: 41955SN/Ausing EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>; 424381Sbinkertn@umich.edutemplate <typename MatrixType> using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>; 434381Sbinkertn@umich.edutemplate <typename MatrixType> using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>; 448334Snate@binkert.org 45955SN/ANAMESPACE_BEGIN(detail) 46955SN/A 474202Sbinkertn@umich.edu#if EIGEN_VERSION_AT_LEAST(3,3,0) 48955SN/Ausing EigenIndex = Eigen::Index; 494382Sbinkertn@umich.edu#else 504382Sbinkertn@umich.eduusing EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE; 514382Sbinkertn@umich.edu#endif 526654Snate@binkert.org 535517Snate@binkert.org// Matches Eigen::Map, Eigen::Ref, blocks, etc: 548614Sgblack@eecs.umich.edutemplate <typename T> using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>, std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>; 557674Snate@binkert.orgtemplate <typename T> using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>; 566143Snate@binkert.orgtemplate <typename T> using is_eigen_dense_plain = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>; 576143Snate@binkert.orgtemplate <typename T> using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>; 586143Snate@binkert.org// Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This 598233Snate@binkert.org// basically covers anything that can be assigned to a dense matrix but that don't have a typical 608233Snate@binkert.org// matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and 618233Snate@binkert.org// SelfAdjointView fall into this category. 628233Snate@binkert.orgtemplate <typename T> using is_eigen_other = all_of< 638233Snate@binkert.org is_template_base_of<Eigen::EigenBase, T>, 648334Snate@binkert.org negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>> 658334Snate@binkert.org>; 6610453SAndrew.Bardsley@arm.com 6710453SAndrew.Bardsley@arm.com// Captures numpy/eigen conformability status (returned by EigenProps::conformable()): 688233Snate@binkert.orgtemplate <bool EigenRowMajor> struct EigenConformable { 698233Snate@binkert.org bool conformable = false; 708233Snate@binkert.org EigenIndex rows = 0, cols = 0; 718233Snate@binkert.org EigenDStride stride{0, 0}; 728233Snate@binkert.org 738233Snate@binkert.org EigenConformable(bool fits = false) : conformable{fits} {} 746143Snate@binkert.org // Matrix type: 758233Snate@binkert.org EigenConformable(EigenIndex r, EigenIndex c, 768233Snate@binkert.org EigenIndex rstride, EigenIndex cstride) : 778233Snate@binkert.org conformable{true}, rows{r}, cols{c}, 786143Snate@binkert.org stride(EigenRowMajor ? rstride : cstride /* outer stride */, 796143Snate@binkert.org EigenRowMajor ? cstride : rstride /* inner stride */) 806143Snate@binkert.org {} 816143Snate@binkert.org // Vector type: 828233Snate@binkert.org EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride) 838233Snate@binkert.org : EigenConformable(r, c, r == 1 ? c*stride : stride, c == 1 ? r : r*stride) {} 848233Snate@binkert.org 856143Snate@binkert.org template <typename props> bool stride_compatible() const { 868233Snate@binkert.org // To have compatible strides, we need (on both dimensions) one of fully dynamic strides, 878233Snate@binkert.org // matching strides, or a dimension size of 1 (in which case the stride value is irrelevant) 888233Snate@binkert.org return 898233Snate@binkert.org (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner() || 906143Snate@binkert.org (EigenRowMajor ? cols : rows) == 1) && 916143Snate@binkert.org (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer() || 926143Snate@binkert.org (EigenRowMajor ? rows : cols) == 1); 934762Snate@binkert.org } 946143Snate@binkert.org operator bool() const { return conformable; } 958233Snate@binkert.org}; 968233Snate@binkert.org 978233Snate@binkert.orgtemplate <typename Type> struct eigen_extract_stride { using type = Type; }; 988233Snate@binkert.orgtemplate <typename PlainObjectType, int MapOptions, typename StrideType> 998233Snate@binkert.orgstruct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> { using type = StrideType; }; 1006143Snate@binkert.orgtemplate <typename PlainObjectType, int Options, typename StrideType> 1018233Snate@binkert.orgstruct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> { using type = StrideType; }; 1028233Snate@binkert.org 1038233Snate@binkert.org// Helper struct for extracting information from an Eigen type 1048233Snate@binkert.orgtemplate <typename Type_> struct EigenProps { 1056143Snate@binkert.org using Type = Type_; 1066143Snate@binkert.org using Scalar = typename Type::Scalar; 1076143Snate@binkert.org using StrideType = typename eigen_extract_stride<Type>::type; 1086143Snate@binkert.org static constexpr EigenIndex 1096143Snate@binkert.org rows = Type::RowsAtCompileTime, 1106143Snate@binkert.org cols = Type::ColsAtCompileTime, 1116143Snate@binkert.org size = Type::SizeAtCompileTime; 1126143Snate@binkert.org static constexpr bool 1136143Snate@binkert.org row_major = Type::IsRowMajor, 1147065Snate@binkert.org vector = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1 1156143Snate@binkert.org fixed_rows = rows != Eigen::Dynamic, 1168233Snate@binkert.org fixed_cols = cols != Eigen::Dynamic, 1178233Snate@binkert.org fixed = size != Eigen::Dynamic, // Fully-fixed size 1188233Snate@binkert.org dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size 1198233Snate@binkert.org 1208233Snate@binkert.org template <EigenIndex i, EigenIndex ifzero> using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>; 1218233Snate@binkert.org static constexpr EigenIndex inner_stride = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value, 1228233Snate@binkert.org outer_stride = if_zero<StrideType::OuterStrideAtCompileTime, 1238233Snate@binkert.org vector ? size : row_major ? cols : rows>::value; 1248233Snate@binkert.org static constexpr bool dynamic_stride = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic; 1258233Snate@binkert.org static constexpr bool requires_row_major = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1; 1268233Snate@binkert.org static constexpr bool requires_col_major = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1; 1278233Snate@binkert.org 1288233Snate@binkert.org // Takes an input array and determines whether we can make it fit into the Eigen type. If 1298233Snate@binkert.org // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector 1308233Snate@binkert.org // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type). 1318233Snate@binkert.org static EigenConformable<row_major> conformable(const array &a) { 1328233Snate@binkert.org const auto dims = a.ndim(); 1338233Snate@binkert.org if (dims < 1 || dims > 2) 1348233Snate@binkert.org return false; 1358233Snate@binkert.org 1368233Snate@binkert.org if (dims == 2) { // Matrix type: require exact match (or dynamic) 1378233Snate@binkert.org 1388233Snate@binkert.org EigenIndex 1398233Snate@binkert.org np_rows = a.shape(0), 1408233Snate@binkert.org np_cols = a.shape(1), 1418233Snate@binkert.org np_rstride = a.strides(0) / sizeof(Scalar), 1428233Snate@binkert.org np_cstride = a.strides(1) / sizeof(Scalar); 1438233Snate@binkert.org if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols)) 1448233Snate@binkert.org return false; 1458233Snate@binkert.org 1468233Snate@binkert.org return {np_rows, np_cols, np_rstride, np_cstride}; 1476143Snate@binkert.org } 1486143Snate@binkert.org 1496143Snate@binkert.org // Otherwise we're storing an n-vector. Only one of the strides will be used, but whichever 1506143Snate@binkert.org // is used, we want the (single) numpy stride value. 1516143Snate@binkert.org const EigenIndex n = a.shape(0), 1526143Snate@binkert.org stride = a.strides(0) / sizeof(Scalar); 1539982Satgutier@umich.edu 15410196SCurtis.Dunham@arm.com if (vector) { // Eigen type is a compile-time vector 15510196SCurtis.Dunham@arm.com if (fixed && size != n) 15610196SCurtis.Dunham@arm.com return false; // Vector size mismatch 15710196SCurtis.Dunham@arm.com return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride}; 15810196SCurtis.Dunham@arm.com } 15910196SCurtis.Dunham@arm.com else if (fixed) { 16010196SCurtis.Dunham@arm.com // The type has a fixed size, but is not a vector: abort 16110196SCurtis.Dunham@arm.com return false; 1626143Snate@binkert.org } 1636143Snate@binkert.org else if (fixed_cols) { 1648945Ssteve.reinhardt@amd.com // Since this isn't a vector, cols must be != 1. We allow this only if it exactly 1658233Snate@binkert.org // equals the number of elements (rows is Dynamic, and so 1 row is allowed). 1668233Snate@binkert.org if (cols != n) return false; 1676143Snate@binkert.org return {1, n, stride}; 1688945Ssteve.reinhardt@amd.com } 1696143Snate@binkert.org else { 1706143Snate@binkert.org // Otherwise it's either fully dynamic, or column dynamic; both become a column vector 1716143Snate@binkert.org if (fixed_rows && rows != n) return false; 1726143Snate@binkert.org return {n, 1, stride}; 1735522Snate@binkert.org } 1746143Snate@binkert.org } 1756143Snate@binkert.org 1766143Snate@binkert.org static PYBIND11_DESCR descriptor() { 1779982Satgutier@umich.edu constexpr bool show_writeable = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value; 1788233Snate@binkert.org constexpr bool show_order = is_eigen_dense_map<Type>::value; 1798233Snate@binkert.org constexpr bool show_c_contiguous = show_order && requires_row_major; 1808233Snate@binkert.org constexpr bool show_f_contiguous = !show_c_contiguous && show_order && requires_col_major; 1816143Snate@binkert.org 1826143Snate@binkert.org return _("numpy.ndarray[") + npy_format_descriptor<Scalar>::name() + 1836143Snate@binkert.org _("[") + _<fixed_rows>(_<(size_t) rows>(), _("m")) + 1846143Snate@binkert.org _(", ") + _<fixed_cols>(_<(size_t) cols>(), _("n")) + 1855522Snate@binkert.org _("]") + 1865522Snate@binkert.org // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to be 1875522Snate@binkert.org // satisfied: writeable=True (for a mutable reference), and, depending on the map's stride 1885522Snate@binkert.org // options, possibly f_contiguous or c_contiguous. We include them in the descriptor output 1895604Snate@binkert.org // to provide some hint as to why a TypeError is occurring (otherwise it can be confusing to 1905604Snate@binkert.org // see that a function accepts a 'numpy.ndarray[float64[3,2]]' and an error message that you 1916143Snate@binkert.org // *gave* a numpy.ndarray of the right type and dimensions. 1926143Snate@binkert.org _<show_writeable>(", flags.writeable", "") + 1934762Snate@binkert.org _<show_c_contiguous>(", flags.c_contiguous", "") + 1944762Snate@binkert.org _<show_f_contiguous>(", flags.f_contiguous", "") + 1956143Snate@binkert.org _("]"); 1966727Ssteve.reinhardt@amd.com } 1976727Ssteve.reinhardt@amd.com}; 1986727Ssteve.reinhardt@amd.com 1994762Snate@binkert.org// Casts an Eigen type to numpy array. If given a base, the numpy array references the src data, 2006143Snate@binkert.org// otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array. 2016143Snate@binkert.orgtemplate <typename props> handle eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) { 2026143Snate@binkert.org constexpr size_t elem_size = sizeof(typename props::Scalar); 2036143Snate@binkert.org std::vector<size_t> shape, strides; 2046727Ssteve.reinhardt@amd.com if (props::vector) { 2056143Snate@binkert.org shape.push_back(src.size()); 2067674Snate@binkert.org strides.push_back(elem_size * src.innerStride()); 2077674Snate@binkert.org } 2085604Snate@binkert.org else { 2096143Snate@binkert.org shape.push_back(src.rows()); 2106143Snate@binkert.org shape.push_back(src.cols()); 2116143Snate@binkert.org strides.push_back(elem_size * src.rowStride()); 2124762Snate@binkert.org strides.push_back(elem_size * src.colStride()); 2136143Snate@binkert.org } 2144762Snate@binkert.org array a(std::move(shape), std::move(strides), src.data(), base); 2154762Snate@binkert.org if (!writeable) 2164762Snate@binkert.org array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_; 2176143Snate@binkert.org 2186143Snate@binkert.org return a.release(); 2194762Snate@binkert.org} 2208233Snate@binkert.org 2218233Snate@binkert.org// Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that 2228233Snate@binkert.org// reference the Eigen object's data with `base` as the python-registered base class (if omitted, 2238233Snate@binkert.org// the base will be set to None, and lifetime management is up to the caller). The numpy array is 2246143Snate@binkert.org// non-writeable if the given type is const. 2256143Snate@binkert.orgtemplate <typename props, typename Type> 2264762Snate@binkert.orghandle eigen_ref_array(Type &src, handle parent = none()) { 2276143Snate@binkert.org // none here is to get past array's should-we-copy detection, which currently always 2284762Snate@binkert.org // copies when there is no base. Setting the base to None should be harmless. 2296143Snate@binkert.org return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value); 2304762Snate@binkert.org} 2316143Snate@binkert.org 2328233Snate@binkert.org// Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a numpy 2338233Snate@binkert.org// array that references the encapsulated data with a python-side reference to the capsule to tie 23410453SAndrew.Bardsley@arm.com// its destruction to that of any dependent python objects. Const-ness is determined by whether or 2356143Snate@binkert.org// not the Type of the pointer given is const. 2366143Snate@binkert.orgtemplate <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>> 2376143Snate@binkert.orghandle eigen_encapsulate(Type *src) { 2386143Snate@binkert.org capsule base(src, [](void *o) { delete static_cast<Type *>(o); }); 2396143Snate@binkert.org return eigen_ref_array<props>(*src, base); 2406143Snate@binkert.org} 2416143Snate@binkert.org 2426143Snate@binkert.org// Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense 24310453SAndrew.Bardsley@arm.com// types. 24410453SAndrew.Bardsley@arm.comtemplate<typename Type> 245955SN/Astruct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> { 2469396Sandreas.hansson@arm.com using Scalar = typename Type::Scalar; 2479396Sandreas.hansson@arm.com using props = EigenProps<Type>; 2489396Sandreas.hansson@arm.com 2499396Sandreas.hansson@arm.com bool load(handle src, bool) { 2509396Sandreas.hansson@arm.com auto buf = array_t<Scalar>::ensure(src); 2519396Sandreas.hansson@arm.com if (!buf) 2529396Sandreas.hansson@arm.com return false; 2539396Sandreas.hansson@arm.com 2549396Sandreas.hansson@arm.com auto dims = buf.ndim(); 2559396Sandreas.hansson@arm.com if (dims < 1 || dims > 2) 2569396Sandreas.hansson@arm.com return false; 2579396Sandreas.hansson@arm.com 2589396Sandreas.hansson@arm.com auto fits = props::conformable(buf); 2599930Sandreas.hansson@arm.com if (!fits) 2609930Sandreas.hansson@arm.com return false; // Non-comformable vector/matrix types 2619396Sandreas.hansson@arm.com 2628235Snate@binkert.org value = Eigen::Map<const Type, 0, EigenDStride>(buf.data(), fits.rows, fits.cols, fits.stride); 2638235Snate@binkert.org 2646143Snate@binkert.org return true; 2658235Snate@binkert.org } 2669003SAli.Saidi@ARM.com 2678235Snate@binkert.orgprivate: 2688235Snate@binkert.org 2698235Snate@binkert.org // Cast implementation 2708235Snate@binkert.org template <typename CType> 2718235Snate@binkert.org static handle cast_impl(CType *src, return_value_policy policy, handle parent) { 2728235Snate@binkert.org switch (policy) { 2738235Snate@binkert.org case return_value_policy::take_ownership: 2748235Snate@binkert.org case return_value_policy::automatic: 2758235Snate@binkert.org return eigen_encapsulate<props>(src); 2768235Snate@binkert.org case return_value_policy::move: 2778235Snate@binkert.org return eigen_encapsulate<props>(new CType(std::move(*src))); 2788235Snate@binkert.org case return_value_policy::copy: 2798235Snate@binkert.org return eigen_array_cast<props>(*src); 2808235Snate@binkert.org case return_value_policy::reference: 2819003SAli.Saidi@ARM.com case return_value_policy::automatic_reference: 2828235Snate@binkert.org return eigen_ref_array<props>(*src); 2835584Snate@binkert.org case return_value_policy::reference_internal: 2844382Sbinkertn@umich.edu return eigen_ref_array<props>(*src, parent); 2854202Sbinkertn@umich.edu default: 2864382Sbinkertn@umich.edu throw cast_error("unhandled return_value_policy: should not happen!"); 2874382Sbinkertn@umich.edu }; 2884382Sbinkertn@umich.edu } 2899396Sandreas.hansson@arm.com 2905584Snate@binkert.orgpublic: 2914382Sbinkertn@umich.edu 2924382Sbinkertn@umich.edu // Normal returned non-reference, non-const value: 2934382Sbinkertn@umich.edu static handle cast(Type &&src, return_value_policy /* policy */, handle parent) { 2948232Snate@binkert.org return cast_impl(&src, return_value_policy::move, parent); 2955192Ssaidi@eecs.umich.edu } 2968232Snate@binkert.org // If you return a non-reference const, we mark the numpy array readonly: 2978232Snate@binkert.org static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) { 2988232Snate@binkert.org return cast_impl(&src, return_value_policy::move, parent); 2995192Ssaidi@eecs.umich.edu } 3008232Snate@binkert.org // lvalue reference return; default (automatic) becomes copy 3015192Ssaidi@eecs.umich.edu static handle cast(Type &src, return_value_policy policy, handle parent) { 3025799Snate@binkert.org if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) 3038232Snate@binkert.org policy = return_value_policy::copy; 3045192Ssaidi@eecs.umich.edu return cast_impl(&src, policy, parent); 3055192Ssaidi@eecs.umich.edu } 3065192Ssaidi@eecs.umich.edu // const lvalue reference return; default (automatic) becomes copy 3078232Snate@binkert.org static handle cast(const Type &src, return_value_policy policy, handle parent) { 3085192Ssaidi@eecs.umich.edu if (policy == return_value_policy::automatic || policy == return_value_policy::automatic_reference) 3098232Snate@binkert.org policy = return_value_policy::copy; 3105192Ssaidi@eecs.umich.edu return cast(&src, policy, parent); 3115192Ssaidi@eecs.umich.edu } 3125192Ssaidi@eecs.umich.edu // non-const pointer return 3135192Ssaidi@eecs.umich.edu static handle cast(Type *src, return_value_policy policy, handle parent) { 3144382Sbinkertn@umich.edu return cast_impl(src, policy, parent); 3154382Sbinkertn@umich.edu } 3164382Sbinkertn@umich.edu // const pointer return 3172667Sstever@eecs.umich.edu static handle cast(const Type *src, return_value_policy policy, handle parent) { 3182667Sstever@eecs.umich.edu return cast_impl(src, policy, parent); 3192667Sstever@eecs.umich.edu } 3202667Sstever@eecs.umich.edu 3212667Sstever@eecs.umich.edu static PYBIND11_DESCR name() { return type_descr(props::descriptor()); } 3222667Sstever@eecs.umich.edu 3235742Snate@binkert.org operator Type*() { return &value; } 3245742Snate@binkert.org operator Type&() { return value; } 3255742Snate@binkert.org template <typename T> using cast_op_type = cast_op_type<T>; 3265793Snate@binkert.org 3278334Snate@binkert.orgprivate: 3285793Snate@binkert.org Type value; 3295793Snate@binkert.org}; 3305793Snate@binkert.org 3314382Sbinkertn@umich.edu// Eigen Ref/Map classes have slightly different policy requirements, meaning we don't want to force 3324762Snate@binkert.org// `move` when a Ref/Map rvalue is returned; we treat Ref<> sort of like a pointer (we care about 3335344Sstever@gmail.com// the underlying data, not the outer shell). 3344382Sbinkertn@umich.edutemplate <typename Return> 3355341Sstever@gmail.comstruct return_value_policy_override<Return, enable_if_t<is_eigen_dense_map<Return>::value>> { 3365742Snate@binkert.org static return_value_policy policy(return_value_policy p) { return p; } 3375742Snate@binkert.org}; 3385742Snate@binkert.org 3395742Snate@binkert.org// Base class for casting reference/map/block/etc. objects back to python. 3405742Snate@binkert.orgtemplate <typename MapType> struct eigen_map_caster { 3414762Snate@binkert.orgprivate: 3425742Snate@binkert.org using props = EigenProps<MapType>; 3435742Snate@binkert.org 3447722Sgblack@eecs.umich.edupublic: 3455742Snate@binkert.org 3465742Snate@binkert.org // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has 3475742Snate@binkert.org // to stay around), but we'll allow it under the assumption that you know what you're doing (and 3489930Sandreas.hansson@arm.com // have an appropriate keep_alive in place). We return a numpy array pointing directly at the 3499930Sandreas.hansson@arm.com // ref's data (The numpy array ends up read-only if the ref was to a const matrix type.) Note 3509930Sandreas.hansson@arm.com // that this means you need to ensure you don't destroy the object in some other way (e.g. with 3519930Sandreas.hansson@arm.com // an appropriate keep_alive, or with a reference to a statically allocated matrix). 3529930Sandreas.hansson@arm.com static handle cast(const MapType &src, return_value_policy policy, handle parent) { 3535742Snate@binkert.org switch (policy) { 3548242Sbradley.danofsky@amd.com case return_value_policy::copy: 3558242Sbradley.danofsky@amd.com return eigen_array_cast<props>(src); 3568242Sbradley.danofsky@amd.com case return_value_policy::reference_internal: 3578242Sbradley.danofsky@amd.com return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value); 3585341Sstever@gmail.com case return_value_policy::reference: 3595742Snate@binkert.org case return_value_policy::automatic: 3607722Sgblack@eecs.umich.edu case return_value_policy::automatic_reference: 3614773Snate@binkert.org return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value); 3626108Snate@binkert.org default: 3631858SN/A // move, take_ownership don't make any sense for a ref/map: 3641085SN/A pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type"); 3656658Snate@binkert.org } 3666658Snate@binkert.org } 3677673Snate@binkert.org 3686658Snate@binkert.org static PYBIND11_DESCR name() { return props::descriptor(); } 3696658Snate@binkert.org 3706658Snate@binkert.org // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return 3716658Snate@binkert.org // types but not bound arguments). We still provide them (with an explicitly delete) so that 3726658Snate@binkert.org // you end up here if you try anyway. 3736658Snate@binkert.org bool load(handle, bool) = delete; 3746658Snate@binkert.org operator MapType() = delete; 3757673Snate@binkert.org template <typename> using cast_op_type = MapType; 3767673Snate@binkert.org}; 3777673Snate@binkert.org 3787673Snate@binkert.org// We can return any map-like object (but can only load Refs, specialized next): 3797673Snate@binkert.orgtemplate <typename Type> struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> 3807673Snate@binkert.org : eigen_map_caster<Type> {}; 3817673Snate@binkert.org 38210467Sandreas.hansson@arm.com// Loader for Ref<...> arguments. See the documentation for info on how to make this work without 3836658Snate@binkert.org// copying (it requires some extra effort in many cases). 3847673Snate@binkert.orgtemplate <typename PlainObjectType, typename StrideType> 38510467Sandreas.hansson@arm.comstruct type_caster< 38610467Sandreas.hansson@arm.com Eigen::Ref<PlainObjectType, 0, StrideType>, 38710467Sandreas.hansson@arm.com enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value> 38810467Sandreas.hansson@arm.com> : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> { 38910467Sandreas.hansson@arm.comprivate: 39010467Sandreas.hansson@arm.com using Type = Eigen::Ref<PlainObjectType, 0, StrideType>; 39110467Sandreas.hansson@arm.com using props = EigenProps<Type>; 39210467Sandreas.hansson@arm.com using Scalar = typename props::Scalar; 39310467Sandreas.hansson@arm.com using MapType = Eigen::Map<PlainObjectType, 0, StrideType>; 39410467Sandreas.hansson@arm.com using Array = array_t<Scalar, array::forcecast | 39510467Sandreas.hansson@arm.com ((props::row_major ? props::inner_stride : props::outer_stride) == 1 ? array::c_style : 3967673Snate@binkert.org (props::row_major ? props::outer_stride : props::inner_stride) == 1 ? array::f_style : 0)>; 3977673Snate@binkert.org static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value; 3987673Snate@binkert.org // Delay construction (these have no default constructor) 3997673Snate@binkert.org std::unique_ptr<MapType> map; 4007673Snate@binkert.org std::unique_ptr<Type> ref; 4019048SAli.Saidi@ARM.com // Our array. When possible, this is just a numpy array pointing to the source data, but 4027673Snate@binkert.org // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an incompatible 4037673Snate@binkert.org // layout, or is an array of a type that needs to be converted). Using a numpy temporary 4047673Snate@binkert.org // (rather than an Eigen temporary) saves an extra copy when we need both type conversion and 4057673Snate@binkert.org // storage order conversion. (Note that we refuse to use this temporary copy when loading an 4066658Snate@binkert.org // argument for a Ref<M> with M non-const, i.e. a read-write reference). 4077756SAli.Saidi@ARM.com Array copy_or_ref; 4087816Ssteve.reinhardt@amd.compublic: 4096658Snate@binkert.org bool load(handle src, bool convert) { 4104382Sbinkertn@umich.edu // First check whether what we have is already an array of the right type. If not, we can't 4114382Sbinkertn@umich.edu // avoid a copy (because the copy is also going to do type conversion). 4124762Snate@binkert.org bool need_copy = !isinstance<Array>(src); 4134762Snate@binkert.org 4144762Snate@binkert.org EigenConformable<props::row_major> fits; 4156654Snate@binkert.org if (!need_copy) { 4166654Snate@binkert.org // We don't need a converting copy, but we also need to check whether the strides are 4175517Snate@binkert.org // compatible with the Ref's stride requirements 4185517Snate@binkert.org Array aref = reinterpret_borrow<Array>(src); 4195517Snate@binkert.org 4205517Snate@binkert.org if (aref && (!need_writeable || aref.writeable())) { 4215517Snate@binkert.org fits = props::conformable(aref); 4225517Snate@binkert.org if (!fits) return false; // Incompatible dimensions 4235517Snate@binkert.org if (!fits.template stride_compatible<props>()) 4245517Snate@binkert.org need_copy = true; 4255517Snate@binkert.org else 4265517Snate@binkert.org copy_or_ref = std::move(aref); 4275517Snate@binkert.org } 4285517Snate@binkert.org else { 4295517Snate@binkert.org need_copy = true; 4305517Snate@binkert.org } 4315517Snate@binkert.org } 4325517Snate@binkert.org 4335517Snate@binkert.org if (need_copy) { 4346654Snate@binkert.org // We need to copy: If we need a mutable reference, or we're not supposed to convert 4355517Snate@binkert.org // (either because we're in the no-convert overload pass, or because we're explicitly 4365517Snate@binkert.org // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading. 4375517Snate@binkert.org if (!convert || need_writeable) return false; 4385517Snate@binkert.org 4395517Snate@binkert.org Array copy = Array::ensure(src); 4405517Snate@binkert.org if (!copy) return false; 4415517Snate@binkert.org fits = props::conformable(copy); 4425517Snate@binkert.org if (!fits || !fits.template stride_compatible<props>()) 4436143Snate@binkert.org return false; 4446654Snate@binkert.org copy_or_ref = std::move(copy); 4455517Snate@binkert.org } 4465517Snate@binkert.org 4475517Snate@binkert.org ref.reset(); 4485517Snate@binkert.org map.reset(new MapType(data(copy_or_ref), fits.rows, fits.cols, make_stride(fits.stride.outer(), fits.stride.inner()))); 4495517Snate@binkert.org ref.reset(new Type(*map)); 4505517Snate@binkert.org 4515517Snate@binkert.org return true; 4525517Snate@binkert.org } 4535517Snate@binkert.org 4545517Snate@binkert.org operator Type*() { return ref.get(); } 4555517Snate@binkert.org operator Type&() { return *ref; } 4565517Snate@binkert.org template <typename _T> using cast_op_type = pybind11::detail::cast_op_type<_T>; 4575517Snate@binkert.org 4585517Snate@binkert.orgprivate: 4596654Snate@binkert.org template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0> 4606654Snate@binkert.org Scalar *data(Array &a) { return a.mutable_data(); } 4615517Snate@binkert.org 4625517Snate@binkert.org template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0> 4636143Snate@binkert.org const Scalar *data(Array &a) { return a.data(); } 4646143Snate@binkert.org 4656143Snate@binkert.org // Attempt to figure out a constructor of `Stride` that will work. 4666727Ssteve.reinhardt@amd.com // If both strides are fixed, use a default constructor: 4675517Snate@binkert.org template <typename S> using stride_ctor_default = bool_constant< 4686727Ssteve.reinhardt@amd.com S::InnerStrideAtCompileTime != Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic && 4695517Snate@binkert.org std::is_default_constructible<S>::value>; 4705517Snate@binkert.org // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like 4715517Snate@binkert.org // Eigen::Stride, and use it: 4726654Snate@binkert.org template <typename S> using stride_ctor_dual = bool_constant< 4736654Snate@binkert.org !stride_ctor_default<S>::value && std::is_constructible<S, EigenIndex, EigenIndex>::value>; 4747673Snate@binkert.org // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use 4756654Snate@binkert.org // it (passing whichever stride is dynamic). 4766654Snate@binkert.org template <typename S> using stride_ctor_outer = bool_constant< 4776654Snate@binkert.org !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value && 4786654Snate@binkert.org S::OuterStrideAtCompileTime == Eigen::Dynamic && S::InnerStrideAtCompileTime != Eigen::Dynamic && 4795517Snate@binkert.org std::is_constructible<S, EigenIndex>::value>; 4805517Snate@binkert.org template <typename S> using stride_ctor_inner = bool_constant< 4815517Snate@binkert.org !any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value && 4826143Snate@binkert.org S::InnerStrideAtCompileTime == Eigen::Dynamic && S::OuterStrideAtCompileTime != Eigen::Dynamic && 4835517Snate@binkert.org std::is_constructible<S, EigenIndex>::value>; 4844762Snate@binkert.org 4855517Snate@binkert.org template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0> 4865517Snate@binkert.org static S make_stride(EigenIndex, EigenIndex) { return S(); } 4876143Snate@binkert.org template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0> 4886143Snate@binkert.org static S make_stride(EigenIndex outer, EigenIndex inner) { return S(outer, inner); } 4895517Snate@binkert.org template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0> 4905517Snate@binkert.org static S make_stride(EigenIndex outer, EigenIndex) { return S(outer); } 4915517Snate@binkert.org template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0> 4925517Snate@binkert.org static S make_stride(EigenIndex, EigenIndex inner) { return S(inner); } 4935517Snate@binkert.org 4945517Snate@binkert.org}; 4955517Snate@binkert.org 4965517Snate@binkert.org// type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not 4975517Snate@binkert.org// EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout). 4989338SAndreas.Sandberg@arm.com// load() is not supported, but we can cast them into the python domain by first copying to a 4999338SAndreas.Sandberg@arm.com// regular Eigen::Matrix, then casting that. 5009338SAndreas.Sandberg@arm.comtemplate <typename Type> 5019338SAndreas.Sandberg@arm.comstruct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> { 5029338SAndreas.Sandberg@arm.comprotected: 5039338SAndreas.Sandberg@arm.com using Matrix = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>; 5048596Ssteve.reinhardt@amd.com using props = EigenProps<Matrix>; 5058596Ssteve.reinhardt@amd.compublic: 5068596Ssteve.reinhardt@amd.com static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) { 5078596Ssteve.reinhardt@amd.com handle h = eigen_encapsulate<props>(new Matrix(src)); 5088596Ssteve.reinhardt@amd.com return h; 5098596Ssteve.reinhardt@amd.com } 5108596Ssteve.reinhardt@amd.com static handle cast(const Type *src, return_value_policy policy, handle parent) { return cast(*src, policy, parent); } 5116143Snate@binkert.org 5125517Snate@binkert.org static PYBIND11_DESCR name() { return props::descriptor(); } 5136654Snate@binkert.org 5146654Snate@binkert.org // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return 5156654Snate@binkert.org // types but not bound arguments). We still provide them (with an explicitly delete) so that 5166654Snate@binkert.org // you end up here if you try anyway. 5176654Snate@binkert.org bool load(handle, bool) = delete; 5186654Snate@binkert.org operator Type() = delete; 5195517Snate@binkert.org template <typename> using cast_op_type = Type; 5205517Snate@binkert.org}; 5215517Snate@binkert.org 5228596Ssteve.reinhardt@amd.comtemplate<typename Type> 5238596Ssteve.reinhardt@amd.comstruct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> { 5244762Snate@binkert.org typedef typename Type::Scalar Scalar; 5254762Snate@binkert.org typedef typename std::remove_reference<decltype(*std::declval<Type>().outerIndexPtr())>::type StorageIndex; 5264762Snate@binkert.org typedef typename Type::Index Index; 5274762Snate@binkert.org static constexpr bool rowMajor = Type::IsRowMajor; 5284762Snate@binkert.org 5294762Snate@binkert.org bool load(handle src, bool) { 5307675Snate@binkert.org if (!src) 53110584Sandreas.hansson@arm.com return false; 5324762Snate@binkert.org 5334762Snate@binkert.org auto obj = reinterpret_borrow<object>(src); 5344762Snate@binkert.org object sparse_module = module::import("scipy.sparse"); 5354762Snate@binkert.org object matrix_type = sparse_module.attr( 5364382Sbinkertn@umich.edu rowMajor ? "csr_matrix" : "csc_matrix"); 5374382Sbinkertn@umich.edu 5385517Snate@binkert.org if (obj.get_type() != matrix_type.ptr()) { 5396654Snate@binkert.org try { 5405517Snate@binkert.org obj = matrix_type(obj); 5418126Sgblack@eecs.umich.edu } catch (const error_already_set &) { 5426654Snate@binkert.org return false; 5437673Snate@binkert.org } 5446654Snate@binkert.org } 5456654Snate@binkert.org 5466654Snate@binkert.org auto values = array_t<Scalar>((object) obj.attr("data")); 5476654Snate@binkert.org auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices")); 5486654Snate@binkert.org auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr")); 5496654Snate@binkert.org auto shape = pybind11::tuple((pybind11::object) obj.attr("shape")); 5506654Snate@binkert.org auto nnz = obj.attr("nnz").cast<Index>(); 5516669Snate@binkert.org 5526669Snate@binkert.org if (!values || !innerIndices || !outerIndices) 5536669Snate@binkert.org return false; 5546669Snate@binkert.org 5556669Snate@binkert.org value = Eigen::MappedSparseMatrix<Scalar, Type::Flags, StorageIndex>( 5566669Snate@binkert.org shape[0].cast<Index>(), shape[1].cast<Index>(), nnz, 5576654Snate@binkert.org outerIndices.mutable_data(), innerIndices.mutable_data(), values.mutable_data()); 5587673Snate@binkert.org 5595517Snate@binkert.org return true; 5608126Sgblack@eecs.umich.edu } 5615798Snate@binkert.org 5627756SAli.Saidi@ARM.com static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) { 5637816Ssteve.reinhardt@amd.com const_cast<Type&>(src).makeCompressed(); 5645798Snate@binkert.org 5655798Snate@binkert.org object matrix_type = module::import("scipy.sparse").attr( 5665517Snate@binkert.org rowMajor ? "csr_matrix" : "csc_matrix"); 5675517Snate@binkert.org 5687673Snate@binkert.org array data((size_t) src.nonZeros(), src.valuePtr()); 5695517Snate@binkert.org array outerIndices((size_t) (rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr()); 5705517Snate@binkert.org array innerIndices((size_t) src.nonZeros(), src.innerIndexPtr()); 5717673Snate@binkert.org 5727673Snate@binkert.org return matrix_type( 5735517Snate@binkert.org std::make_tuple(data, innerIndices, outerIndices), 5745798Snate@binkert.org std::make_pair(src.rows(), src.cols()) 5755798Snate@binkert.org ).release(); 5768333Snate@binkert.org } 5777816Ssteve.reinhardt@amd.com 5785798Snate@binkert.org PYBIND11_TYPE_CASTER(Type, _<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[", "scipy.sparse.csc_matrix[") 5795798Snate@binkert.org + npy_format_descriptor<Scalar>::name() + _("]")); 5804762Snate@binkert.org}; 5814762Snate@binkert.org 5824762Snate@binkert.orgNAMESPACE_END(detail) 5834762Snate@binkert.orgNAMESPACE_END(pybind11) 5844762Snate@binkert.org 5858596Ssteve.reinhardt@amd.com#if defined(__GNUG__) || defined(__clang__) 5865517Snate@binkert.org# pragma GCC diagnostic pop 5875517Snate@binkert.org#elif defined(_MSC_VER) 5885517Snate@binkert.org# pragma warning(pop) 5895517Snate@binkert.org#endif 5905517Snate@binkert.org