Skip to content

Instantly share code, notes, and snippets.

@sglyon
Last active October 24, 2023 15:11
Show Gist options
  • Save sglyon/822f4ccb78c9dbd54fa62b968339d42b to your computer and use it in GitHub Desktop.
Save sglyon/822f4ccb78c9dbd54fa62b968339d42b to your computer and use it in GitHub Desktop.
xtensor buffer adaptor for eigen VectorXd and MatrixXd
#include <stdexcept>
#include "xtensor/xarray.hpp"
#include "xtensor/xio.hpp"
#include "xtensor/xbuffer_adaptor.hpp"
#include "Eigen/Dense"
auto to_xarray(Eigen::VectorXd& in) {
using buf = xt::xbuffer_adaptor<double>;
using xbuf_arr = xt::xarray_container<buf, xt::layout_type::column_major, std::vector<std::size_t>>;
std::size_t len = in.size();
std::vector<std::size_t> shape = {len};
std::vector<std::size_t> strides(1);
// strides[0] = 1;
xt::compute_strides(shape, xt::layout_type::column_major, strides);
std::cout << "strides[0] = " << strides[0] << std::endl;
auto arr = xbuf_arr(buf(in.data(), len), std::move(shape), std::move(strides));
return arr;
}
auto to_xarray(Eigen::MatrixXd& in) {
using buf = xt::xbuffer_adaptor<double>;
using xbuf_arr = xt::xarray_container<buf, xt::layout_type::column_major, std::vector<std::size_t>>;
std::size_t nrow = in.rows();
std::size_t ncol = in.cols();
std::vector<std::size_t> shape = {nrow, ncol};
std::vector<std::size_t> strides(2);
// strides[0] = 1;
xt::compute_strides(shape, xt::layout_type::column_major, strides);
std::cout << "strides[0] = " << strides[0] << std::endl;
std::cout << "strides[1] = " << strides[1] << std::endl;
auto arr = xbuf_arr(buf(in.data(), nrow*ncol), std::move(shape), std::move(strides));
return arr;
}
int main() {
Eigen::VectorXd myvec = Eigen::VectorXd::LinSpaced(10, 0.0, 0.9);
auto arr = to_xarray(myvec);
std::cout << arr << std::endl;
std::cout << "\n\n" << myvec << "\n\n" << std::endl;
auto my_data = myvec.data();
std::cout << "my_data = " << my_data << std::endl;
for (size_t i = 0; i < myvec.size(); i++) {
std::cout << "my_data[" << i << "] = " << my_data[i] << std::endl;
}
std::cout << "\n\nMatrix example\n\n" << std::endl;
Eigen::MatrixXd mymat = Eigen::MatrixXd::Random(3, 4);
auto arr_mat = to_xarray(mymat);
std::cout << arr_mat << std::endl;
std::cout << "\n\n" << mymat << "\n\n" << std::endl;
}
strides[0] = 1
{ 0. , 0.1 , 0.2 , 0.3 , 0.4 , 0.5 ,
0.6 , 0.7 , 0.8 , 0.9 }
0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9
my_data = 0x7fecbed00000
my_data[0] = 0
my_data[1] = 0.1
my_data[2] = 0.2
my_data[3] = 0.3
my_data[4] = 0.4
my_data[5] = 0.5
my_data[6] = 0.6
my_data[7] = 0.7
my_data[8] = 0.8
my_data[9] = 0.9
Matrix example
strides[0] = 1
strides[1] = 3
{{-0.999984, -0.0827 , -0.905911, 0.869386},
{-0.736924, 0.065534, 0.357729, -0.232996},
{ 0.511211, -0.562082, 0.358593, 0.038833}}
-0.999984 -0.0826997 -0.905911 0.869386
-0.736924 0.0655345 0.357729 -0.232996
0.511211 -0.562082 0.358593 0.0388327
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment