You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ENH, API: provide a canonical implementation of array getitem argument handling as an API #13768
A number of libraries try to replicate numpy's handling of array slices to one extent or another, but it's long and fidgety (and not quick) when you take into account slices, integers, ellipses, new axes, and tuples thereof. I would love to see a function like this:
Replace Nones in slice objects with 0, array_shape[axis] and 1 respectively
Replace negative integers, including those in slice objects, with their positive equivalent
Ensure there is only one Ellipsis, and replace it with the correct number of non-Noneslice objects
There might be better output types than a tuple of slices, as that doesn't capture new axes and you need another step to figure out if there are any 0-length dimensions.
We have a C-side list of prepared indexes, which does things like determining how many numbers of slices an ellipsis is. Or whether or not the result is going to be a copy or a view. It will not fill in some the slice information though. That is prepare_index in mapping.c.
If anyone has such a thing already written in python, it would probably be @shoyer. However, I guess you are looking for something slightly different. I am not quite sure what you need, for example I am not sure what filling in the slice information is good for. Slices already implement that if you give them the dimension size and that information should be readily available?
Concrete use case: we have a rust library for reading and writing array data to disk in a particular blocked storage format. We are writing a python wrapper around that library. The rust end gives us a function which takes an offset from (0, 0, ...) and a shape (or a stop index, it doesn't matter which), and returns a numpy array (or something which can be coerced into it): this seems like a pretty common pattern among low-level libraries implementing array storage.
Numpy, and derivatives reimplementing its indexing API, handle a variety of extras, like newaxis, ellipsis (inferred and concrete), and slice objects. I suspect that a lot of those derivatives have their own implementation of turning whatever is passed to __getitem__ into an offset and shape tuple of lengths which match the dimensionality of the underlying array. It's duplicative, and reduces interoperability.
Numpy is in the business of supporting array-oriented workflows, and is the canonical API for interfacing with arrays with python; nobody understands all the corner cases like numpy's contributors, so it seemed like numpy was a good place to make this utility available.
Slices already implement that if you give them the dimension size
Huh, you're right. I dug through the docs plenty to no avail, slices are very poorly documented given how common they are. That definitely cuts out one point of awkwardness!
However, there are other points - like ellipsis and newaxis handling, picking which axes to squeeze, handling indices and slices outside the array extends, and so on. None of it is particularly hard on its own, there are just a lot of corner cases to account for.
changed the title [-]Feature request: canonical implementation of slice argument handling[/-][+]Feature request: canonical implementation of getitem argument handling[/+]on Jun 13, 2019
changed the title [-]Feature request: canonical implementation of getitem argument handling[/-][+]Feature request: canonical implementation of array getitem argument handling[/+]on Jun 13, 2019
We don't have anything exactly like this in xarray, but I agree that it sounds like a nice utility to package with NumPy. Certainly I've encountered many cases where this would have been handy.
Maybe we could put something like this in np.lib.index_tricks? I wouldn't expose it in the top-level numpy namespace, though.
You will also need to return axes_to_expand as well. Actually, you might consider just returning the result shape instead, so it can be reshaped with np.reshape, e.g.,
So perhaps the interface should return another tuple that can be used with NumPy style indexing to create an array with the desired shape/order. Something like:
Maybe we could put something like this in np.lib.index_tricks?
Yes, my heart leapt when I saw that package, so it would seem to be the right place for it.
Another trick we found helpful is ensuring that the backend only needs to deal with positive step sizes.
That's been my strategy too. As a first pass, the backend reads unstrided data (because striding support isn't all that common in the low-level libraries I've seen) and then numpy does the striding (positive or negative) and squeezing.
Yes, with oindex/vindex, we would probably pass around a "prepared index" object, and this could make much of this available fairly easily. In fact, I think, such an object already exists in my oindex branch, although right now it does not expose anything to the outside.
A prepared index object sounds like just the thing!
I updated my gist and it seems to pass a (small) test suite. The out_shape member of the Roi namedtuple should handle both squeezes and newaxes, although I suspect there are some edge cases with C/F ordering to deal with.
The Roi is designed to return the unstrided offset and shape, starting from the smaller index (even for negative strides), so that the stride can simply be applied to the returned array and the backend doesn't need to worry about directionality etc. I can see there's going to be more awkwardness around the order of reshaping and striding, though.
Maybe two small comments, not very important, but just in case you want to be as close to numpy as possible. If you want I can take a closer look, but I don't have a real feeling for what the code is used for.
To coerce indices, numpy basically uses operator.index (__index__) with the exception of rejecting python (and numpy) booleans, because those have advanced indexing meaning like arrays (and frankly, it is strange in any case). We basically use try/except here. (EDIT: we first check for arrays though, since they are advanced indexing)
I don't have a real feeling for what the code is used for.
There are a few different libraries wrapping self-describing hierarchically-arranged array datasets like HDF5, some of which use HDF5's terminology as an analogy for their organisation. I've been involved in a couple and found myself duplicating a lot of code, so I wrote h5py_like, which contains a bunch of ABCs which expose an h5py-like interface. Subclasses define a few simple things like getting and creating direct children of a Group, and everything else (navigating the tree, access control, require_dataset and so on) is handled by the superclass. The package also contains a set of ABCs with a test suite for downstream packages, so that people don't have to write the same tests over and over.
It assumes that you'd be wrapping a much simpler array access library (possibly in a lower-level language) which doesn't implement its own striding, ellipsis, newaxis etc. handling, and so contains a utility for converting a complicated index into a start tuple and a positive shape tuple to read from the low-level array, then a stride tuple and reshape tuple to go the rest of the way in numpy.
Ideally the array indexing stuff, which is required by but not dependent on the hierarchical organisation stuff, would be split out; maybe it could go into a package at the very center of python's array workflow ecosystem.
Interesting - what's the reasoning behind this, when we're already doing a type check to make sure it's not an array? Is there a preferred way of doing something like ceil(bls.len / abs(bls.stride))?
Sorry, nvm. about that comment, I thought you have float logic, so (bls.len-1) // abs(bls.stride) + 1 seemed safer, but floats are exact here up to absurdly large values, so it does not matter...
Generally, yes. However, the thing is that this feels like something that should hook directly into the C-API. I.e. we create an Indexer object, which describes indexing more completely than the typical tuple. Once we do that, we can expose helpers to "normalize", and give information like Expanding the ellipsis or whether or not a scalar would be returned.
In other words: The problem is not really if we want to expose this, the question is how we would like the API/implementation to look like within NumPy. We can help look at some implementations you have in either case.
After a few more iterations, I got to this, which forms part of a library of ABCs to help people writing libraries with an API consistent with h5py's. We are using it in pyn5 and it seems to work fairly well.
For the use case I envisioned, it would be nicer for this utility to stay out of the C-API so that it could be generic over array storage backends (I was more interested in a utility for other people to make libraries which behave like numpy, rather than change the way numpy achieves its existing behaviour). Numpy's API is a (de facto) python standard and my intention in this discussion was to establish an easier way for other libraries to comply with that API.
@clbarnes moving/reusing parts of the numpy C-API does not necessarily mean you need arrays around. The first part of index preparation only uses the dimension (and maybe the shape of the array).
changed the title [-]Feature request: canonical implementation of array getitem argument handling[/-][+]ENH, API: provide a canonical implementation of array getitem argument handling as an API[/+]on Dec 8, 2019
Activity
seberg commentedon Jun 13, 2019
We have a C-side list of prepared indexes, which does things like determining how many numbers of slices an ellipsis is. Or whether or not the result is going to be a copy or a view. It will not fill in some the slice information though. That is
prepare_indexinmapping.c.If anyone has such a thing already written in python, it would probably be @shoyer. However, I guess you are looking for something slightly different. I am not quite sure what you need, for example I am not sure what filling in the slice information is good for. Slices already implement that if you give them the dimension size and that information should be readily available?
clbarnes commentedon Jun 13, 2019
Concrete use case: we have a rust library for reading and writing array data to disk in a particular blocked storage format. We are writing a python wrapper around that library. The rust end gives us a function which takes an offset from (0, 0, ...) and a shape (or a stop index, it doesn't matter which), and returns a numpy array (or something which can be coerced into it): this seems like a pretty common pattern among low-level libraries implementing array storage.
Numpy, and derivatives reimplementing its indexing API, handle a variety of extras, like newaxis, ellipsis (inferred and concrete), and slice objects. I suspect that a lot of those derivatives have their own implementation of turning whatever is passed to
__getitem__into an offset and shape tuple of lengths which match the dimensionality of the underlying array. It's duplicative, and reduces interoperability.Some examples:
Numpy is in the business of supporting array-oriented workflows, and is the canonical API for interfacing with arrays with python; nobody understands all the corner cases like numpy's contributors, so it seemed like numpy was a good place to make this utility available.
Huh, you're right. I dug through the docs plenty to no avail, slices are very poorly documented given how common they are. That definitely cuts out one point of awkwardness!
However, there are other points - like ellipsis and newaxis handling, picking which axes to squeeze, handling indices and slices outside the array extends, and so on. None of it is particularly hard on its own, there are just a lot of corner cases to account for.
[-]Feature request: canonical implementation of slice argument handling[/-][+]Feature request: canonical implementation of getitem argument handling[/+][-]Feature request: canonical implementation of getitem argument handling[/-][+]Feature request: canonical implementation of array getitem argument handling[/+]shoyer commentedon Jun 13, 2019
We don't have anything exactly like this in xarray, but I agree that it sounds like a nice utility to package with NumPy. Certainly I've encountered many cases where this would have been handy.
Maybe we could put something like this in
np.lib.index_tricks? I wouldn't expose it in the top-levelnumpynamespace, though.You will also need to return
axes_to_expandas well. Actually, you might consider just returning the result shape instead, so it can be reshaped withnp.reshape, e.g.,shoyer commentedon Jun 13, 2019
Another trick we found helpful is ensuring that the backend only needs to deal with positive step sizes. This requires doing another "slice" operation afterwards in NumPy:
https://github.com/pydata/xarray/blob/7e4bf8623891c4e564bbaede706e1d69c614b74b/xarray/core/indexing.py#L793
So perhaps the interface should return another tuple that can be used with NumPy style indexing to create an array with the desired shape/order. Something like:
seberg commentedon Jun 13, 2019
I have just created this gist: https://gist.github.com/seberg/b0b213523a83e42fa8ffede9cb61fea9
which does the first pass of helping here, basically the path that numpy also does internall first (it probably should get some testing).
clbarnes commentedon Jun 13, 2019
Yes, my heart leapt when I saw that package, so it would seem to be the right place for it.
That's been my strategy too. As a first pass, the backend reads unstrided data (because striding support isn't all that common in the low-level libraries I've seen) and then numpy does the striding (positive or negative) and squeezing.
eric-wieser commentedon Jun 13, 2019
Ideally this would become part of the
oindex/vindexstuff, and the proposedLegacyIndexwould provide APIs for this kind of parsing.seberg commentedon Jun 13, 2019
Yes, with oindex/vindex, we would probably pass around a "prepared index" object, and this could make much of this available fairly easily. In fact, I think, such an object already exists in my oindex branch, although right now it does not expose anything to the outside.
clbarnes commentedon Jun 13, 2019
A prepared index object sounds like just the thing!
I updated my gist and it seems to pass a (small) test suite. The
out_shapemember of theRoinamedtuple should handle both squeezes and newaxes, although I suspect there are some edge cases with C/F ordering to deal with.The Roi is designed to return the unstrided offset and shape, starting from the smaller index (even for negative strides), so that the stride can simply be applied to the returned array and the backend doesn't need to worry about directionality etc. I can see there's going to be more awkwardness around the order of reshaping and striding, though.
clbarnes commentedon Jun 18, 2019
A slightly more rounded implementation is here:
https://github.com/clbarnes/h5py_like/blob/master/h5py_like/shape_utils.py#L91
It passes some direct sanity checks https://github.com/clbarnes/h5py_like/blob/master/tests/test_shape_utils.py , but more importantly, a package which uses it to re-implement much of h5py's API passes tests which check it against numpy: https://github.com/clbarnes/h5py_like/blob/master/h5py_like/test_utils/dataset.py#L36
seberg commentedon Jun 18, 2019
Maybe two small comments, not very important, but just in case you want to be as close to numpy as possible. If you want I can take a closer look, but I don't have a real feeling for what the code is used for.
operator.index(__index__) with the exception of rejecting python (and numpy) booleans, because those have advanced indexing meaning like arrays (and frankly, it is strange in any case). We basically usetry/excepthere. (EDIT: we first check for arrays though, since they are advanced indexing)/operator?clbarnes commentedon Jun 18, 2019
Thanks for taking a look!
There are a few different libraries wrapping self-describing hierarchically-arranged array datasets like HDF5, some of which use HDF5's terminology as an analogy for their organisation. I've been involved in a couple and found myself duplicating a lot of code, so I wrote
h5py_like, which contains a bunch of ABCs which expose anh5py-like interface. Subclasses define a few simple things like getting and creating direct children of a Group, and everything else (navigating the tree, access control,require_datasetand so on) is handled by the superclass. The package also contains a set of ABCs with a test suite for downstream packages, so that people don't have to write the same tests over and over.It assumes that you'd be wrapping a much simpler array access library (possibly in a lower-level language) which doesn't implement its own striding, ellipsis, newaxis etc. handling, and so contains a utility for converting a complicated index into a start tuple and a positive shape tuple to read from the low-level array, then a stride tuple and reshape tuple to go the rest of the way in numpy.
Ideally the array indexing stuff, which is required by but not dependent on the hierarchical organisation stuff, would be split out; maybe it could go into a package at the very center of python's array workflow ecosystem.
A concrete use case is my branch of the python bindings to a rust implementation of the N5 filesystem format. Python bindings to the C++ implementation of N5 and zarr filesystem formats do not use it, but potentially could.
Interesting - what's the reasoning behind this, when we're already doing a type check to make sure it's not an array? Is there a preferred way of doing something like
ceil(bls.len / abs(bls.stride))?seberg commentedon Jun 18, 2019
Sorry, nvm. about that comment, I thought you have float logic, so
(bls.len-1) // abs(bls.stride) + 1seemed safer, but floats are exact here up to absurdly large values, so it does not matter...jbrockmendel commentedon Oct 10, 2019
Would a PR implementing this be accepted? Parts of it were implemented (with tests) here.
seberg commentedon Oct 10, 2019
Generally, yes. However, the thing is that this feels like something that should hook directly into the C-API. I.e. we create an
Indexerobject, which describes indexing more completely than the typical tuple. Once we do that, we can expose helpers to "normalize", and give information like Expanding the ellipsis or whether or not a scalar would be returned.In other words: The problem is not really if we want to expose this, the question is how we would like the API/implementation to look like within NumPy. We can help look at some implementations you have in either case.
clbarnes commentedon Oct 10, 2019
After a few more iterations, I got to this, which forms part of a library of ABCs to help people writing libraries with an API consistent with h5py's. We are using it in pyn5 and it seems to work fairly well.
For the use case I envisioned, it would be nicer for this utility to stay out of the C-API so that it could be generic over array storage backends (I was more interested in a utility for other people to make libraries which behave like numpy, rather than change the way numpy achieves its existing behaviour). Numpy's API is a (de facto) python standard and my intention in this discussion was to establish an easier way for other libraries to comply with that API.
seberg commentedon Oct 10, 2019
@clbarnes moving/reusing parts of the numpy C-API does not necessarily mean you need arrays around. The first part of index preparation only uses the dimension (and maybe the shape of the array).
[-]Feature request: canonical implementation of array getitem argument handling[/-][+]ENH, API: provide a canonical implementation of array getitem argument handling as an API[/+]