使用pybind11将NumPy数组转换为自定义C++ Matrix类

Tom*_*eus 8 c++ python arrays numpy pybind11

我正在尝试使用包装我的C++代码pybind11.在C++中,我有一个Matrix3D充当三维数组(即形状[n,m,p])的类.它具有以下基本签名:

template <class T> class Matrix3D
{

  public:

    std::vector<T> data;
    std::vector<size_t> shape;
    std::vector<size_t> strides;

    Matrix3D<T>();
    Matrix3D<T>(std::vector<size_t>);
    Matrix3D<T>(const Matrix3D<T>&);

    T& operator() (int,int,int);

};
Run Code Online (Sandbox Code Playgroud)

为了最小化包装器代码,我想将此类直接转换为NumPy数组(副本没有问题).例如,我想直接包装以下签名的函数:

Matrix3D<double> func ( const Matrix3D<double>& );
Run Code Online (Sandbox Code Playgroud)

使用包装器代码

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>

namespace py = pybind11;

PYBIND11_PLUGIN(example) {
  py::module m("example", "Module description");
  m.def("func", &func, "Function description" );
  return m.ptr();
}
Run Code Online (Sandbox Code Playgroud)

目前我还有另一个接受和返回的功能py::array_t<double>.但我想避免为每个函数编写一个包装函数,方法是用一些模板替换它.

这已经为Eigen-library(对于数组和(2-D)矩阵)完成.但是代码对我来说太过牵扯,无法从中派生自己的代码.另外,我真的只需要包装一个简单的类.

kaz*_*ase 5

我对 pybind11 不熟悉,但在阅读这个问题后开始感兴趣。从文档看来,您将不得不编写自己的类型 caster。这显然是一个相当高级的话题,但似乎可以通过一些努力来实现。

从文档中剥离,这是用于转换 C++ 类型的此类转换器的外壳inty

namespace pybind11 { namespace detail {
    template <> struct type_caster<inty> {
    public:
        PYBIND11_TYPE_CASTER(inty, _("inty"));    

        // Conversion part 1 (Python->C++)
        bool load(handle src, bool);

        //Conversion part 2 (C++ -> Python)
        static handle cast(inty src, return_value_policy, handle);
    };
}} // namespace pybind11::detail
Run Code Online (Sandbox Code Playgroud)

似乎所有你需要做的是,以取代intyMatrix3D<double>贯彻load()cast()

让我们看看他们是如何为 Eigen 做的(eigen.h,第 236 行):

bool load(handle src, bool) {
    auto buf = array_t<Scalar>::ensure(src);
    if (!buf)
        return false;

    auto dims = buf.ndim();
    if (dims < 1 || dims > 2)
        return false;

    auto fits = props::conformable(buf);
    if (!fits)
        return false; // Non-comformable vector/matrix types

    value = Eigen::Map<const Type, 0, EigenDStride>(buf.data(), fits.rows, fits.cols, fits.stride);

    return true;
}
Run Code Online (Sandbox Code Playgroud)

这看起来并不太难。首先,他们确保输入的类型array_t<Scalar>(可能array_t<double>在您的情况下)。然后他们检查尺寸和一些一致性(你可以跳过后者)。最后创建特征矩阵。由于复制不是问题,此时只需创建一个新Martix3D<double>实例并用 numpy 数组中的数据填充它。

cast()对于 l 值和常量的不同情况,该函数有不同的实现。我想如果可以的话,只执行一个在新的 numpy 数组中创建数据副本的实现就足够了。请参阅函数eigen_array_cast()如何将数组作为handle返回类型返回。

我没有测试过任何这些,这个过程可能比看起来的要多。希望这将作为一个起点。


Tom*_*eus 5

随着@kazemakase和@jagerman(通过后者的帮助下pybind11论坛)我已经想通了。类本身应该具有可以从某些输入复制的构造函数,这里使用迭代器:

#include <vector>
#include <assert.h>
#include <iterator>


template <class T> class Matrix3D
{
public:

  std::vector<T>      data;
  std::vector<size_t> shape;
  std::vector<size_t> strides;

  Matrix3D<T>() = default;

  template<class Iterator>
  Matrix3D<T>(const std::vector<size_t> &shape, Iterator first, Iterator last);
};


template <class T>
template<class Iterator>
Matrix3D<T>::Matrix3D(const std::vector<size_t> &shape_, Iterator first, Iterator last)
{
  shape = shape_;

  assert( shape.size() == 3 );

  strides.resize(3);

  strides[0] = shape[2]*shape[1];
  strides[1] = shape[2];
  strides[2] = 1;

  int size = shape[0] * shape[1] * shape[2];

  assert( last-first == size );

  data.resize(size);

  std::copy(first, last, data.begin());
}
Run Code Online (Sandbox Code Playgroud)

直接包装以下签名的功能:

Matrix3D<double> func ( const Matrix3D<double>& );
Run Code Online (Sandbox Code Playgroud)

需要以下包装器代码

#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <pybind11/numpy.h>

namespace py = pybind11;

namespace pybind11 { namespace detail {
  template <typename T> struct type_caster<Matrix3D<T>>
  {
    public:

      PYBIND11_TYPE_CASTER(Matrix3D<T>, _("Matrix3D<T>"));

      // Conversion part 1 (Python -> C++)
      bool load(py::handle src, bool convert) 
      {
        if ( !convert and !py::array_t<T>::check_(src) )
          return false;

        auto buf = py::array_t<T, py::array::c_style | py::array::forcecast>::ensure(src);
        if ( !buf )
          return false;

        auto dims = buf.ndim();
        if ( dims != 3  )
          return false;

        std::vector<size_t> shape(3);

        for ( int i = 0 ; i < 3 ; ++i )
          shape[i] = buf.shape()[i];

        value = Matrix3D<T>(shape, buf.data(), buf.data()+buf.size());

        return true;
      }

      //Conversion part 2 (C++ -> Python)
      static py::handle cast(const Matrix3D<T>& src, py::return_value_policy policy, py::handle parent) 
      {

        std::vector<size_t> shape  (3);
        std::vector<size_t> strides(3);

        for ( int i = 0 ; i < 3 ; ++i ) {
          shape  [i] = src.shape  [i];
          strides[i] = src.strides[i]*sizeof(T);
        }

        py::array a(std::move(shape), std::move(strides), src.data.data() );

        return a.release();

      }
  };
}} // namespace pybind11::detail

PYBIND11_PLUGIN(example) {
    py::module m("example", "Module description");
    m.def("func", &func, "Function description" );
    return m.ptr();
}
Run Code Online (Sandbox Code Playgroud)

注意,现在也可以进行函数重载。例如,如果存在带有以下签名的重载函数:

Matrix3D<int   > func ( const Matrix3D<int   >& );
Matrix3D<double> func ( const Matrix3D<double>& );
Run Code Online (Sandbox Code Playgroud)

需要以下包装器函数定义:

m.def("func", py::overload_cast<Matrix3D<int   >&>(&func), "Function description" );
m.def("func", py::overload_cast<Matrix3D<double>&>(&func), "Function description" );
Run Code Online (Sandbox Code Playgroud)

  • 我在这个 [GitHub 存储库](https://github.com/tdegeus/pybind11_examples) 中包含了完整的代码以及一些 pybind11 示例,如示例 9。 (2认同)