4#include <pybind11/numpy.h>
7namespace py = pybind11;
10using pyarray = py::array_t<T, py::array::f_style | py::array::forcecast>;
23template <
typename T> py::array_t<T>
ColToNpy(
const arma::Col<T> &data) {
25 const us Tsize =
sizeof(T);
27 const auto nrows =
static_cast<ssize_t
>(data.n_rows);
29 const us size = nrows;
31 py::array_t<T> result({nrows}, {Tsize});
35 memcpy(result.mutable_data(0), data.memptr(),
sizeof(T) * nrows);
49template <
typename T> py::array_t<T>
MatToNpy(
const arma::Mat<T> &data) {
51 const us Tsize =
sizeof(T);
53 const auto nrows =
static_cast<ssize_t
>(data.n_rows);
54 const auto ncols =
static_cast<ssize_t
>(data.n_cols);
56 const us size = nrows;
58 py::array_t<T> result({nrows, ncols}, {Tsize, nrows * Tsize});
62 memcpy(result.mutable_data(0, 0), data.memptr(),
sizeof(T) * nrows * ncols);
76template <
typename T> py::array_t<T>
CubeToNpy(
const arma::Cube<T> &data) {
78 const us Tsize =
sizeof(T);
80 const auto nrows =
static_cast<ssize_t
>(data.n_rows);
81 const auto ncols =
static_cast<ssize_t
>(data.n_cols);
82 const auto nslices =
static_cast<ssize_t
>(data.n_slices);
84 const us size = nrows * ncols * nslices;
86 py::array_t<T> result({nrows, ncols, nslices},
87 {Tsize, nrows * Tsize, nrows * ncols * Tsize});
91 memcpy(result.mutable_data(0, 0, 0), data.memptr(),
92 sizeof(T) * nrows * ncols * nslices);
109template <
typename T,
bool copy = true>
111 if (data.ndim() != 2) {
112 throw std::runtime_error(
"Expects a 2D array");
114 return arma::Mat<T>(data.mutable_data(0,0), data.shape(0), data.shape(1), copy);
126template <
typename T,
bool copy = true>
128 if (data.ndim() != 1) {
129 throw std::runtime_error(
"Expects a 1D array");
131 return arma::Col<T>(data.mutable_data(0), data.size(), copy);
py::array_t< T > ColToNpy(const arma::Col< T > &data)
Convert Armadillo column vector to Numpy 1D array.
py::array_t< T > CubeToNpy(const arma::Cube< T > &data)
Convert Armadillo Cube to Numpy 3D array.
py::array_t< T > MatToNpy(const arma::Mat< T > &data)
Convert Armadillo 2D array Numpy 2D array.
arma::Mat< T > NpyToCol(pyarray< T > data)
Wrap Numpy array to 1D Armadillo column vector.
arma::Mat< T > NpyToMat(pyarray< T > data)
BACK converters.
py::array_t< T, py::array::f_style|py::array::forcecast > pyarray
size_t us
We often use boolean values.