Skip to content

ENH, API: provide a canonical implementation of array getitem argument handling as an API #13768

Open

Description

@clbarnes

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:

from typing import Union, Tuple, TypeVar

SliceLike = Union[ellipsis, slice, int, None]
SliceArgs = TypeVar("SliceArgs", SliceLike, Tuple[SliceLike])

def rationalise_indices(
    getitem_arg: SliceArgs, array_shape: Tuple[int]
) -> Tuple[Tuple[slice], List[int]]:
    # insert magic here
    return slices, axes_to_squeeze

This function would:

  • Realise implied ellipses
  • 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-None slice 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.

I have an implementation of something like this but it's ugly, doesn't handle new axes or negative strides, and almost certainly is not correct in other ways: https://gist.github.com/clbarnes/b6a3d15b20bdff1f11a2043138a564f9

Activity

  1. seberg commented on Jun 13, 2019

    @seberg
    Member

    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?

  2. clbarnes commented on Jun 13, 2019

    @clbarnes
    ContributorAuthor

    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.

    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.

  3. changed the title [-]Feature request: canonical implementation of slice argument handling[/-] [+]Feature request: canonical implementation of getitem argument handling[/+] on Jun 13, 2019
  4. changed the title [-]Feature request: canonical implementation of getitem argument handling[/-] [+]Feature request: canonical implementation of array getitem argument handling[/+] on Jun 13, 2019
  5. shoyer commented on Jun 13, 2019

    @shoyer
    Member

    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.,

    index, shape = rationalise_indices(index, my_array.shape)
    result = np.reshape(do_indexing(my_array, index), shape)
  6. shoyer commented on Jun 13, 2019

    @shoyer
    Member

    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:

    index, post_index = rationalise_indices(index, my_array.shape)
    result = np.asarray(do_indexing(my_array, index))[post_index]
  7. seberg commented on Jun 13, 2019

    @seberg
    Member

    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).

  8. clbarnes commented on Jun 13, 2019

    @clbarnes
    ContributorAuthor

    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.

  9. eric-wieser commented on Jun 13, 2019

    @eric-wieser
    Member

    Ideally this would become part of the oindex / vindex stuff, and the proposed LegacyIndex would provide APIs for this kind of parsing.

  10. seberg commented on Jun 13, 2019

    @seberg
    Member

    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.

  11. clbarnes commented on Jun 13, 2019

    @clbarnes
    ContributorAuthor

    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.

  12. seberg commented on Jun 18, 2019

    @seberg
    Member

    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.

    1. 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)
    2. Out of principle might avoid / operator?
  13. clbarnes commented on Jun 18, 2019

    @clbarnes
    ContributorAuthor

    Thanks for taking a look!

    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.

    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.

    Out of principle might avoid / operator?

    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))?

  14. seberg commented on Jun 18, 2019

    @seberg
    Member

    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...

  15. jbrockmendel commented on Oct 10, 2019

    @jbrockmendel
    Contributor

    Would a PR implementing this be accepted? Parts of it were implemented (with tests) here.

  16. seberg commented on Oct 10, 2019

    @seberg
    Member

    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.

  17. clbarnes commented on Oct 10, 2019

    @clbarnes
    ContributorAuthor

    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.

  18. seberg commented on Oct 10, 2019

    @seberg
    Member

    @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).

  19. 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions