xtensor icon indicating copy to clipboard operation
xtensor copied to clipboard

Why doesn't the at() element access function throw an exception if the size of a violated dimension == 1?

Open mokenyi opened this issue 4 years ago • 7 comments

If the upper bound of an axis of size 1 is exceeded in at(), I expected an exception to be thrown. However this is not the case. For example, I expected the following example to throw an exception:

#include "xtensor/xtensor.hpp"

int main(int argc, char** argv)
{
  std::array<size_t,2> sh2({2,1});
  xt::xtensor<int,2> x(sh2);
  x.at(0,1);
}

Could somebody please explain the reasoning behind this behaviour? Sorry if it is already explained elsewhere.

mokenyi avatar Nov 04 '21 22:11 mokenyi

Hi,

This is the broadcasting feature. Assume we have two tensors a and b, with shapes (2, 4, 1) and (2, 4, 5). The expression (a+b).at(0, 0, 4) is valid, therefore a.at(0, 0, 4) must be valid.

JohanMabille avatar Nov 08 '21 10:11 JohanMabille

Thanks for your explanation. Is there a way to use at() which does not allow axes of size 1 to be exceeded?

mokenyi avatar Nov 08 '21 12:11 mokenyi

Not for now. But we could easily add anoother check enabled with a build variable for that.

JohanMabille avatar Nov 15 '21 22:11 JohanMabille

xtensor also provides the in_bounds method, which checks if the arguments do not exceed the size of their axe. Maybe it's a better option to call it before accessing the elements; or we could implement a at_in_bounds method if you prefer. But both of them are better than a new build option.

JohanMabille avatar Nov 22 '21 19:11 JohanMabille

Thanks for the info. Would it be possible and acceptable to somehow override at() for xtensors and xarrays so that broadcasting is disabled? Or are there cases with these containers where the broadcasting behaviour is desirable?

mokenyi avatar Nov 24 '21 22:11 mokenyi

Broadcasting is possible in the context of lazy evaluation only if all expressions support broadcasting. Therefore we cannot disable it for xarrays or xtensors only. What is the issue in using a new method such as at_in_bounds ?

JohanMabille avatar Nov 26 '21 08:11 JohanMabille

I understand. There's nothing wrong with using a new method. I was only wondering if there was a solution without having to add a new method. Thanks!

mokenyi avatar Nov 26 '21 09:11 mokenyi