Skip to content

Index with boolean array #2651

Closed
Closed

Description

@mrocklin

For some applications, like downsampling, it would be convenient to be able to index with a dask.array of boolean dtype

In [1]: import dask.array as da

In [2]: X = da.ones((100, 5), chunks=(10, 5))

In [3]: y = da.ones((100,), chunks=(10,))

In [4]: index = da.random.random(size=y.shape, chunks=y.chunks) > 0.9

In [5]: X2 = X[index, :]
---------------------------------------------------------------------------
NotImplementedError                       Traceback (most recent call last)
<ipython-input-5-9e9ddb5053ea> in <module>()
----> 1 X2 = X[index, :]

/home/mrocklin/workspace/dask/dask/array/core.py in __getitem__(self, index)
   1205 
   1206         if any(isinstance(i, Array) for i in index):
-> 1207             raise NotImplementedError("Indexing with a dask Array")
   1208 
   1209         from .slicing import normalize_index

NotImplementedError: Indexing with a dask Array

Playing with this now

Activity

  1. TomAugspurger commented on Sep 5, 2017

    @TomAugspurger
    Member

    FYI @mrocklin I have this PR: #2430 that started on this.

    I rebased it over the weekend as I was playing with the original application that needed it (some distributed ML stuff). I'll push that rebase, and if you want I can polish it up or you can run with it.

  2. mrocklin commented on Sep 5, 2017

    @mrocklin
    MemberAuthor

    Ah, I had forgotten about that PR. I worked on this briefly over the weekend, but decided to put it back on the back burner and work on higher priority things once I realized that it was more effort than originally anticipated. I started briefly thinking about if it made sense to include constants in atop like the following:

    atop('out', 'ij', x, 'ij', condition, 'i', slice(None), '')` 
    

    which would make this quite a bit easier; I'm not sure that that's a good idea though (cc @jcrist).

    #2658

  3. TomAugspurger commented on Sep 5, 2017

    @TomAugspurger
    Member

    Ah, I see your use-case involves slicing axes other than the first. My initial attempt only solved x[condition], not any higher dimensions.

  4. jakirkham commented on Sep 5, 2017

    @jakirkham
    Member

    It might be possible to achieve this behavior by applying compress on a reshaped array. Where the dimensions where the mask would be applied are flattened.

    Here's a simplified example of what I mean.

    Details
    In [1]: import numpy as np
    
    In [2]: import dask.array as da
    
    In [3]: a = np.random.random((2, 3, 4))
    
    In [4]: am = a[..., 0] > 0.3
    
    In [5]: d = da.from_array(a, chunks=1)
    
    In [6]: dm = d[..., 0] > 0.3
    
    In [7]: a[am]  # same as a[am, ...]
    Out[7]: 
    array([[ 0.66280289,  0.13946264,  0.90614406,  0.86303196],
           [ 0.66187436,  0.66932569,  0.30641791,  0.14350136],
           [ 0.52088612,  0.75146569,  0.84352929,  0.21301708],
           [ 0.4764178 ,  0.9429292 ,  0.87033665,  0.54347886],
           [ 0.65136431,  0.80116764,  0.52482439,  0.57373349]])
    
    In [8]: da.compress(dm.flatten(), d.reshape((-1,) + d.shape[dm.ndim:]), axis=0).compute()
    Out[8]: 
    array([[ 0.66280289,  0.13946264,  0.90614406,  0.86303196],
           [ 0.66187436,  0.66932569,  0.30641791,  0.14350136],
           [ 0.52088612,  0.75146569,  0.84352929,  0.21301708],
           [ 0.4764178 ,  0.9429292 ,  0.87033665,  0.54347886],
           [ 0.65136431,  0.80116764,  0.52482439,  0.57373349]])
    

    Obviously there will be more work in normalizing the arguments to __getitem__ to figure out how to handle the different variants, but using compress (or pulling the code from it) should work very nicely here IMHO.

  5. jcrist commented on Sep 5, 2017

    @jcrist
    Member

    I started briefly thinking about if it made sense to include constants in atop

    I think this is probably fine, and might obviate the need for partial_by_order. Could go either way here.

  6. jakirkham commented on Sep 5, 2017

    @jakirkham
    Member

    For a very small step in this direction, have put together PR ( #2659 ), which simply allows the Boolean array to be smaller than the array it slices.

  7. timothydmorton commented on Sep 12, 2017

    @timothydmorton

    I just came across this thread looking for a way to get just the finite values from a dask series/dataframe. In other words, using pandas I would do something like vals = vals.replace([np.inf, -np.inf], np.nan).dropna(how='any') (I need to drop both infs and nans), but I have not yet figured out how to do this with dask. If there were a solution to the boolean indexing, I could do vals = vals[np.isfinite(vals)] but that currently doesn't work. Is there another way to do this?

  8. mrocklin commented on Sep 12, 2017

    @mrocklin
    MemberAuthor

    You shouldn't use numpy functions with dask series objects. You probably want the following:

    vals[~vals.isnull()]
    

    I recommend asking on Stack Overflow for usage questions in the future. The #dask tag is decently well tracked.

  9. jakirkham commented on Nov 18, 2017

    @jakirkham
    Member

    Running the example in the OP locally with dask 0.16.0 proceeds without issues. Are we ok to close this or is there more to do here?

  10. TAdeJong commented on Jan 16, 2018

    @TAdeJong
    Contributor

    With the risk that this is more SO material. I stumbled upon this issue and #2659 and #2658 while working on a 3D dataset, a stack of images where I want to calculate the mean of some area for each image. (Or in this example, exclude a center region. Inequalities are hard O:-) )

    >>> import dask.array as da
    >>> import numpy as np
    >>> import dask
    >>> dask.__version__
    '0.16.1'
    >>> X = da.ones((412,1580,1243),chunks=(1,1580,1243))
    >>> Z = np.ones(X.shape)
    >>> x,y = np.ogrid[:X.shape[1],:X.shape[2]]
    >>> mask = (((x - 500) / (200+.5))**2 + ((y - 300) / (100+.5))**2 > 1)
    >>> Z[mask]
    array([[ 1.,  1.,  1., ...,  1.,  1.,  1.],
           [ 1.,  1.,  1., ...,  1.,  1.,  1.],
           [ 1.,  1.,  1., ...,  1.,  1.,  1.],
           ...,
           [ 1.,  1.,  1., ...,  1.,  1.,  1.],
           [ 1.,  1.,  1., ...,  1.,  1.,  1.],
           [ 1.,  1.,  1., ...,  1.,  1.,  1.]])
    >>> Z[mask].shape
    (1900627, 412)
    >>> Z[mask,:]
    array([[ 1.,  1.,  1., ...,  1.,  1.,  1.],
           [ 1.,  1.,  1., ...,  1.,  1.,  1.],
           [ 1.,  1.,  1., ...,  1.,  1.,  1.],
           ...,
           [ 1.,  1.,  1., ...,  1.,  1.,  1.],
           [ 1.,  1.,  1., ...,  1.,  1.,  1.],
           [ 1.,  1.,  1., ...,  1.,  1.,  1.]])
    >>>X[mask]
    ValueError: object too deep for desired array
    >>>X[:,mask]
    ValueError: object too deep for desired array
    >>>X[da.from_array(mask)]
    NotImplementedError: Slicing with dask.array only permitted when the indexer has only one dimension or when it has the same dimension as the sliced array
    

    So it appears the masking as described does not work for higher dimensional masks, even when explicitly specifying broadcasting dimensions, while both work for numpy arrays, and a not-implemented error will only be raised if the mask is also a dask array.

    For my use case I can work around this by explicitly looping over the broadcasting dimension, but I'd just like to illustrate there are nice use cases for the numpy behaviour, which dask.array seems not to support at this point.

  11. jakirkham commented on Mar 19, 2021

    @jakirkham
    Member

    Interesting with that last example actually run into a different issue (should add I'm running from main)

    In [1]: import dask.array as da
    
    In [2]: import numpy as np
    
    In [3]: import dask
    
    In [4]: dask.__version__
    Out[4]: '2021.03.0+27.g82fcaab0'
    
    In [5]: X = da.ones((412,1580,1243),chunks=(1,1580,1243))
    
    In [6]: Z = np.ones(X.shape)
    
    In [7]: x,y = np.ogrid[:X.shape[1],:X.shape[2]]
    
    In [8]: mask = (((x - 500) / (200+.5))**2 + ((y - 300) / (100+.5))**2 > 1)
    
    In [9]: Z[mask]
    ---------------------------------------------------------------------------
    IndexError                                Traceback (most recent call last)
    <ipython-input-9-6c74f5b92130> in <module>
    ----> 1 Z[mask]
    
    IndexError: boolean index did not match indexed array along dimension 0; dimension is 412 but corresponding boolean dimension is 1580
    
  12. jakirkham commented on Mar 19, 2021

    @jakirkham
    Member

    In any event the issue in the OP, doesn't appear to produce an error any more. There has been a lot of work in this space over the years. While there are probably other cases that don't work, it would be easier to track these in new issues and tackle them separately. Going to go ahead and close this out (please do feel free to raise new issue though 🙂). Thanks! 😄

    In [1]: import dask.array as da
    
    In [2]: X = da.ones((100, 5), chunks=(10, 5))
    
    In [3]: y = da.ones((100,), chunks=(10,))
    
    In [4]: index = da.random.random(size=y.shape, chunks=y.chunks) > 0.9
    
    In [5]: X2 = X[index, :]
    
    In [6]: X2.compute()
    Out[6]: 
    array([[1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.],
           [1., 1., 1., 1., 1.]])
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions