Skip to content

inconsistent slicing of .X vs .layer #145

Closed

Description

@fidelram

This is related to #74 for for slices and is behind the problem reported in scverse/scanpy#555

from  scipy.sparse import csr_matrix

adata = sc.AnnData(np.ones((3,3)))
adata.layers['test'] = adata.X.copy()
adata.layers['sparse'] = csr_matrix(adata.X)

print(adata[:, ['0']].X.shape, 
      adata[:, ['0']].layers['test'].shape,
      adata[:, ['0']].layers['sparse'].shape)
print(adata[:, '0'].X.shape, 
     adata[:, '0'].layers['test'].shape, 
     adata[:, '0'].layers['sparse'].shape)

print(type(adata[:, ['0']].X), 
      type(adata[:, ['0']].layers['test']), 
      type(adata[:, ['0']].layers['sparse']))

print(type(adata[:, '0'].X), 
      type(adata[:, '0'].layers['test']), 
      type(adata[:, '0'].layers['sparse']))

The output is:

(3,) (3, 1) (3, 1)
(3,) (3,) (3, 1)
<class 'anndata.base.ArrayView'> <class 'numpy.ndarray'> <class 'scipy.sparse.csr.csr_matrix'>
<class 'anndata.base.ArrayView'> <class 'numpy.ndarray'> <class 'scipy.sparse.csr.csr_matrix'>

Ideally, while slicing .layers, the output should be the same as for .X

Activity

  1. falexwolf commented on Apr 30, 2019

    @falexwolf
    Member

    @Koncopd, any easy fix for this?

    This whole thing relates back to the early issue of not flattening .X when effectively 1d (what Phil always wanted) and instead using another convenience accessor (@ivirshup's .get_obs_array or .get_obs_1dslice or .get_obs_1d or .get_1d_obs (I like the last best) or a similar name #144).

    The problem is that this is a backwards breaking change and many people got used to adata.[, 'gene_name'].X giving something 1d. But I do think we should move there and make this change and point people to .get_1d_obs. We could make it anndata 2.0 and put a big warning in the docs. Replacing all occurances in Scanpy is no problem at all.

  2. fidelram commented on Apr 30, 2019

    @fidelram
    Author

    If I remember correctly, in some past discussions it was proposed that the slicing should to mimic the behavior of numpy, pandas etc. which return a 1d array in the case of a single slice. Why don't we stick with this behaviour?

  3. ivirshup commented on Apr 30, 2019

    @ivirshup
    Member

    I think adata.[:, 'gene_name'].X (for dense X) being 1d is fine, since that's what numpy arrays do. adata.[:, 'gene_name'].X should be 2d for a sparse matrix, since that's what sparse matrices do. We shouldn't expect sparse matrices to behave like arrays until there's a more systemic solution, like CSD or CSF finally being added to sparse. That would be a good time for anndata 2.0, since there's a ton of code in scanpy having to deal with sparse matrices not having array like semantics.

    The only wrong thing I see in those examples is adata[:, ['0']].X.shape not being (3, 1).

    @fidelram, I think a more direct solution to that issue is checking if the layer is a sparse matrix, then converting it to an array after you've sliced it (possibly followed by a reshape if matplotlib still complains). If you'd like, I'm working on a function that does this for you over in scverse/scanpy#619.

  4. falexwolf commented on Apr 30, 2019

    @falexwolf
    Member

    Yes, this was the original idea, but there these considerations

    • we want to be consistent between sparse and dense representations. And then we should treat .X as numpy.matrix and not as numpy.ndarray, which will then have the same slicing properties as sparse.matrix (not flattening an effectively 1d array).
    • we want AnnData always to be in a valid state with meaningful row and column slicing and meaningful on-disk representations. As ._X is always 2d and .X merely provides views, we achieved this in a way. The layers example you're giving though indicates that we'll potentially always tap into new traps with this custom model...
  5. falexwolf commented on Apr 30, 2019

    @falexwolf
    Member

    The only wrong thing I see in those examples is adata[:, ['0']].X.shape not being (3, 1)

    This is definitely a mistake in the implemenation and shouldn't be like that...

  6. ivirshup commented on Apr 30, 2019

    @ivirshup
    Member

    I don't think we should do np.matrix as it's been deprecated within numpy.

    I'd also say the shape of adata.X is not necessarily shape of adata.

    If the issue here is the bug in scverse/scanpy#555, I think the more direct solution is not to pass matplotlib a sparse matrix.

  7. fidelram commented on Apr 30, 2019

    @fidelram
    Author

    Thanks for the clarification I would suggest to first set the output of the slicing of .X and .layers the way you want it, and then I address the scatterplots issue (and potentially other problems).

    @ivirshup in scverse/scanpy#555 the problem happens with the layer being a sparse matrix and also with a np.ndarray because is not 1d. I don't know why the tests didn't catch this but I think I only tested for a value in .obs which does not trigger the problem.

  8. ivirshup commented on Apr 30, 2019

    @ivirshup
    Member

    That makes sense. I'd be surprised if matplotlib would accept anything besides an explicitly 1d array for that. This has become a pretty common idiom for me:

    if issparse(a):
        a = a.toarray()
    a = np.ravel(a)
  9. falexwolf commented on Apr 30, 2019

    @falexwolf
    Member

    I don't think we should do np.matrix as it's been deprecated within numpy.

    Oh, I see, you're right! This has to be relatively recent. That's a bit unfortunate because then there is no easy way to have an array keep its dimensions throughout slicing, I fear.

    I'd also say the shape of adata.X is not necessarily shape of adata.

    Several people approached me (also 2 developers of CZI buillding cellxgene and other toolkits) saying that "an always-2d .X" object is helpful. Even in my own coding, I produced bugs because .X suddenly turned out 1d when I expected it to be 2d. For the cases that I experienced, it should be fixed by restoring numpy's behavior (treating indexing with [0] differently than 0). I don't really see a disadvantage of having X be always-2d when there is a convenient 1d accessor method. After all, adata[:, 'gene'].X is not great, either...

    Also, one would need to catch the layers case in a custom way, for which there is no elegant implementation.

  10. Koncopd commented on Apr 30, 2019

    @Koncopd
    Member

    @falexwolf
    So, should we have flattened layers in 1d case?

  11. ivirshup commented on May 1, 2019

    @ivirshup
    Member

    @falexwolf Doesn't this count as keeping the dimensions?

    import numpy as np
    a = np.ones((10, 10))
    print(a[:, [0]].shape)
    # (10, 1)
    print(a[[0], :].shape)
    # (1, 10)

    I guess we could just insist that _normalize_indices returns slices and collections? Indexing into an array with those should preserve dimensionality.

    There is the principle of least surprise here. When you do adata[index].X, which of these outcomes is more surprising?

    1. adata[index].X.shape == X[index].shape and adata[index].shape != X[index].shape
    2. adata[index].X.shape != X[index].shape] and adata[index].shape == X[index].shape
  12. falexwolf commented on May 6, 2019

    @falexwolf
    Member

    No discussion necessary at all: we should definitely do what you suggest. If at some later stage, we go nuts and make something "always 2d", is another and much less important question. And probably we won't as maintaining collections through _normalize_indices and removing the forced flattening (letting the shape of the passed index determine whether things get flattened) will make people generally happy
    https://github.com/theislab/anndata/blob/fc7f3cb06c191aff4fcad6af88f0c3012d7d1a65/anndata/base.py#L967-L970

  13. Koncopd commented on May 8, 2019

    @Koncopd
    Member

    @ivirshup , hi, no, i'm not.

  14. ivirshup commented on Jun 25, 2019

    @ivirshup
    Member

    After writing up the view code, I've come around on this. I think for now it makes sense to have the shape of the AnnData object match up with the shape of the constituent arrays (the "always 2d" option). This allows for a more consistent API when dealing with sparse vs dense arrays, which should be as interchangeable as possible. While I'd prefer that we be consistent with other array-likes, I don't think that option works well with scipy.sparse and the inherent two dimensional shape of the AnnData object. In particular, it becomes difficult to tell which dimensions of which constituents are aligned with the parent object.

    Do people think there would be any significant issues created by changing this behavior? I think the most commonly effected expressions would be ones like:

    adata[0, 0].X # Returns array of shape (1, 1)
    adata[0, :].X # Returns array of shape (1, adata.shape[1])

    I'd like to make this part of #164, if this is the way we go. This will involve changing the expected outputs for some tests, mostly the ones which have .to_list() in their assertions.

    I've got implementations for "always 2d" and "directly pass index" options sitting on my fork – though each still needs to have tests corrected. I think directly passing indices ends up taking more code since there's an additional case for subsetting (the scalar) and more types to deal with (pd.Series, scalars).

  15. falexwolf commented on Jun 26, 2019

    @falexwolf
    Member

    OK! Cool! This is exactly what @flying-sheep said from the very beginning about "always-2d". :)

    My argument at the time (2 years ago) was that we need a convenient access to vectors. When anndata was "always-2d", I had a lot of adata[0, :].X.flatten() all over the place in the scanpy code, scripts and notebooks.

    Then I went ahead and moved the .flatten() into the accessor. Which was a bad idea (now, I know, @flying-sheep 🙂).

    Anyway, I'm happy if we make this change if we make anndata 1.0 directly, which I think should be an option. A lot of code will break in people's notebooks, and also within Scanpy, accessing .X is assumed to be vector like in several instances. But I think, it's probably worth it and it's not crazy to fix it. It should go along with scanpy 1.5, I guess.

    Last question: I still think one needs convenient access to vectors along the data matrix. And as we have .obs_vector already, it should be that. Maybe, in some distant future, we'd also have .X[:, gene] [which would conform with adata[:, gene].X and probably be most efficient], but that might be more tricky than the family of ArrayView, DataFrameView etc. (if it still exists). However, if it's easy enough to subclass np.ndarray, sp.spmatrix and h5py.Dataset, to plugin the global AnnData indexer, this would be a great solution.

    Last but not least, communicating these changes properly will be key. Both in the release notes, docs, tutorials and github/twitter.

  16. flying-sheep commented on Jun 26, 2019

    @flying-sheep
    Member

    For completeness’ sake I’d like to enumerate the options:

    • “convenience”: Fix the current idea, i.e. leave the behavior for .X and flatten layers as well.
    • “precision”: Slice depending on the index type. ad[:, 1].X or ad[:, 'GeneA'].X return a (n_obs,) array (1D), ad[:, [1]].X or ad[:, :1].X return a (n_obs, 1) array (2D).
    • “predictability”/“always-2d”: len(ad[i, j].X.shape) == 2 for all valid is and js.
    • Some hybrid, e.g. that ad[int_or_str, int_or_str].X is a special case that returns a single float

    I also think “predictability”/“always-2d” is the best option.

    1. The invariant is already given if the storage mode is a sparse matrix
    2. sometimes you don’t know if your dynamically computed index would retrieve 1 or more items.
    3. Back then my concerns about it being more bug prone were purely hypothetical (if well-reasoned), but now we saw (as alex said) that the bugs actually happen.
    4. “precision” or the described hybrid would result in X having an 1D or 0D shape. That’s OK if X is directly accessed afterwards (ad[0, 'GeneA'].X), but suffers from the same problems as the “convenience” approach if not (ad = ad[0, 'GeneA']; <do stuff>; good_riddance(ad)).
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

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions