pynid 11とnumpyを交互にする方法

3085 ワード

buffer protocolに従うオブジェクトを使うとnumpyと対話できます。
このブザープロトコールはどんなものがありますか?次のインターフェースが必要です

struct buffer_info {
  void *ptr;
  ssize_t itemsize;
  std::string format;
  ssize_t ndim;
  std::vector<ssize_t> shape;
  std::vector<ssize_t> strides;
};
つまり、配列を指すポインタと各次元の情報だけでいいです。そして、私達はポインタ+オフセットで数字の中の任意の位置の数字にアクセスできます。
以下は走ることができる例です。

#include <pybind11/pybind11.h>
 #include <pybind11/numpy.h>
 namespace py = pybind11;
 py::array_t<double> add_arrays(py::array_t<double> input1, py::array_t<double> input2) {
   py::buffer_info buf1 = input1.request(), buf2 = input2.request();
   if (buf1.ndim != 1 || buf2.ndim != 1)
     throw std::runtime_error("Number of dimensions must be one");
   if (buf1.size != buf2.size)
     throw std::runtime_error("Input shapes must match");
   /* No pointer is passed, so NumPy will allocate the buffer */
   auto result = py::array_t<double>(buf1.size);
   py::buffer_info buf3 = result.request();
   double *ptr1 = (double *) buf1.ptr,
      *ptr2 = (double *) buf2.ptr,
      *ptr3 = (double *) buf3.ptr;
   for (size_t idx = 0; idx < buf1.shape[0]; idx++)
     ptr3[idx] = ptr1[idx] + ptr2[idx];
   return result;
 }
 
 PYBIND11_MODULE(test, m) {
   m.def("add_arrays", &add_arrays, "Add two NumPy arrays");
 }
アラリtの中のbufは1つの互換性のインターフェースです。
bufでは、ポインタと対応する数字の次元情報が得られます。
便利さのために、私達はEigenをnumpy対応のインターフェースとしても使えます。

#include <pybind11/pybind11.h>
 #include <pybind11/eigen.h> 
 #include <Eigen/LU> 
 // N.B. this would equally work with Eigen-types that are not predefined. For example replacing
 // all occurrences of "Eigen::MatrixXd" with "MatD", with the following definition:
 //
 // typedef Eigen::Matrix<double, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> MatD;
 
 Eigen::MatrixXd inv(const Eigen::MatrixXd &xs)
 {
  return xs.inverse();
 }
 
 double det(const Eigen::MatrixXd &xs)
 {
  return xs.determinant();
 }
 
 namespace py = pybind11;
 
 PYBIND11_MODULE(example,m)
 {
  m.doc() = "pybind11 example plugin";
 
  m.def("inv", &inv);
 
  m.def("det", &det);
 }
詳細な参照:
https://pybind11.readthedocs.io/en/stable/advanced/pycpp/numpy.html
https://github.com/tdegeus/pybind11_examples
締め括りをつける
以上は小编が皆さんに绍介したpyninumpyとのインタラクティブな方法です。皆さんのために何かお聞きしたいことがあれば、メッセージをください。小编はすぐにご返事します。ここでも私たちのサイトを応援してくれてありがとうございます。
本文があなたのためになると思ったら、転載を歓迎します。出所を明記してください。ありがとうございます。