xtensor icon indicating copy to clipboard operation
xtensor copied to clipboard

A generic type for all tensor (array) containers

Open benbovy opened this issue 7 years ago • 3 comments

I haven't found anywhere in xtensor such a generic type, i.e., something like xtensor_t<T, N> that we could use for xt::xtensor<T, N>, xt::pytensor<T, N>, xt::rtensor<T, N> or any other container adaptator using the tensor interface (there could be a similar type for the array interface). Am I missing something?

This would be handy for writing specific functions (e.g., that only deals with arrays of known dimensions) with clear signatures and just reuse them for bindings (python, r...).

benbovy avatar May 20 '18 15:05 benbovy

I like this idea for interface composition.

I think we can achieve a nice interface if we use the std::placeholders. Because we can't overload the template when using a size_t in the template unfortunately.

So something like

x<double>
x<T, _3>
x<int, xshape<3, 4, 2>

could work quite nicely... we could inherit from xexpression and add static asserts for the shape type or something like that to get nice error messages.

wolfv avatar May 21 '18 14:05 wolfv

I haven't thought about adding static asserts but it would be nice indeed!

I'd like to implement this kind of interface, but I have to admit that I'm a bit lost in C++ templates right now. @wolfv could you give me some hints on how to achieve this?

To give more context, here is an example of what I'd like to be able to write:

template<class T>
void func(xtensor_t<T, 2>& arr1,
          xtensor_t<int, 1>& arr2,
          xtensor_t<T, 1>& arr3)
{
   auto arr1_flat = xt::flatten(arr1);
   // do something with arr1_flat, arr2, arr3
}

and call func with either xt::xtensor or xt::pytensor or any object having the tensor interface...

The same example with a super explicit template would be something like:

template<class T, class N_Rows, class N_Cols, class N_Nodes = N_Rows * N_Cols>
void func(xtensor_t<T, xshape<N_Rows, N_Cols>>& arr1,
          xtensor_t<int, xshape<N_Nodes>>& arr2,
          xtensor_t<T, xshape<N_Nodes>>& arr3)
{
   auto arr1_flat = xt::flatten(arr1);
   // do something ...
}

but I don't know if it would work with numpy arrays and I don't even know if this is valid C++14. I'd be already very happy with the simpler version above.

benbovy avatar May 22 '18 10:05 benbovy

I'm going to look into that right now. I think we need to add another "xexpression-like" type to the inheritance chain to enable this stuff... i'll be doing some quick experiments right now.

wolfv avatar May 22 '18 11:05 wolfv