xtensor icon indicating copy to clipboard operation
xtensor copied to clipboard

xt::sort unexpected behaviour when not providing axis parameter

Open vakokako opened this issue 2 years ago • 2 comments

When using xt::sort without passing the axis along which to sort, I was expecting it to sort the values in recpect to the whole container, however, it sorted the values in rows only:

xt::xarray<float> array = (xt::arange(25, 0, -1).reshape({5, 5}));
std::cout << "array : \n" << array << "\n";
std::cout << "sorted : \n" << xt::sort(array) << "\n";

output:

array : 
{{  25.,   24.,   23.,   22.,   21.},
 {  20.,   19.,   18.,   17.,   16.},
 {  15.,   14.,  100.,   12.,   11.},
 {  10.,    9.,    8.,    7.,    6.},
 {   5.,    4.,    3.,    2.,    1.}}
sorted :
{{  21.,   22.,   23.,   24.,   25.},
 {  16.,   17.,   18.,   19.,   20.},
 {  11.,   12.,   14.,   15.,  100.},
 {   6.,    7.,    8.,    9.,   10.},
 {   1.,    2.,    3.,    4.,    5.}}

expected result:

{{  1.,   2.,   3.,   4.,   5.},
 {  6.,   7.,   8.,   9.,  10.},
 { 11.,  12.,  13.,  14.,  15.},
 { 16.,  17.,  18.,  19.,  20.},
 { 21.,  22.,  23.,  24.,  24.}}

vakokako avatar Jul 15 '21 14:07 vakokako

I could use xt::sort(array, xt::placeholders::_), but it flattens the result and also this should be the default behaviour of xt::sort.

vakokako avatar Jul 15 '21 14:07 vakokako

Per NumPy's behaviour xt::sort always sorts along an axis and by default along the last axis (see also docs). To sort the full object you indeed should ravel, sort, and unravel. I also think that that is the way the NumPy does it.

What would be an alternative to sort the whole object in-place (untested):

xt::xarray<float> array = (xt::arange(25, 0, -1).reshape({5, 5}));
std::sort(array.begin(), array.end())l

tdegeus avatar Aug 01 '21 13:08 tdegeus