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
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.
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?
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.
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...
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.
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:
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.
@Koncopd, are you working on this? If you've got anything in progress, I'd be interested to see. I'm working around some of the code for this right now for #140, and don't want to cause too much in the way of merge conflicts.
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).
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.
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.
The invariant is already given if the storage mode is a sparse matrix
sometimes you don’t know if your dynamically computed index would retrieve 1 or more items.
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.
“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)).
Activity
falexwolf commentedon Apr 30, 2019
@Koncopd, any easy fix for this?
This whole thing relates back to the early issue of not flattening
.Xwhen effectively 1d (what Phil always wanted) and instead using another convenience accessor (@ivirshup's.get_obs_arrayor.get_obs_1dsliceor.get_obs_1dor.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'].Xgiving 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.fidelram commentedon Apr 30, 2019
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?
ivirshup commentedon Apr 30, 2019
I think
adata.[:, 'gene_name'].X(for denseX) being 1d is fine, since that's what numpy arrays do.adata.[:, 'gene_name'].Xshould 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.shapenot 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
reshapeif matplotlib still complains). If you'd like, I'm working on a function that does this for you over in scverse/scanpy#619.falexwolf commentedon Apr 30, 2019
Yes, this was the original idea, but there these considerations
.Xasnumpy.matrixand not asnumpy.ndarray, which will then have the same slicing properties assparse.matrix(not flattening an effectively 1d array).._Xis always 2d and.Xmerely 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...falexwolf commentedon Apr 30, 2019
This is definitely a mistake in the implemenation and shouldn't be like that...
ivirshup commentedon Apr 30, 2019
I don't think we should do
np.matrixas it's been deprecated within numpy.I'd also say the shape of
adata.Xis not necessarily shape ofadata.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.
fidelram commentedon Apr 30, 2019
Thanks for the clarification I would suggest to first set the output of the slicing of .
Xand.layersthe 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.ndarraybecause is not 1d. I don't know why the tests didn't catch this but I think I only tested for a value in.obswhich does not trigger the problem.ivirshup commentedon Apr 30, 2019
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:
falexwolf commentedon Apr 30, 2019
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.
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.Xsuddenly 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 than0). 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'].Xis not great, either...Also, one would need to catch the layers case in a custom way, for which there is no elegant implementation.
Koncopd commentedon Apr 30, 2019
@falexwolf
So, should we have flattened layers in 1d case?
ivirshup commentedon May 1, 2019
@falexwolf Doesn't this count as keeping the dimensions?
I guess we could just insist that
_normalize_indicesreturns 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?adata[index].X.shape == X[index].shapeandadata[index].shape != X[index].shapeadata[index].X.shape != X[index].shape]andadata[index].shape == X[index].shapefalexwolf commentedon May 6, 2019
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_indicesand removing the forced flattening (letting the shape of the passed index determine whether things get flattened) will make people generally happyhttps://github.com/theislab/anndata/blob/fc7f3cb06c191aff4fcad6af88f0c3012d7d1a65/anndata/base.py#L967-L970
ivirshup commentedon May 8, 2019
@Koncopd, are you working on this? If you've got anything in progress, I'd be interested to see. I'm working around some of the code for this right now for #140, and don't want to cause too much in the way of merge conflicts.
Relevant lines:
https://github.com/theislab/anndata/blob/fc7f3cb06c191aff4fcad6af88f0c3012d7d1a65/anndata/base.py#L511
https://github.com/theislab/anndata/blob/fc7f3cb06c191aff4fcad6af88f0c3012d7d1a65/anndata/base.py#L241-L250
https://github.com/theislab/anndata/blob/fc7f3cb06c191aff4fcad6af88f0c3012d7d1a65/anndata/base.py#L698-L699
Koncopd commentedon May 8, 2019
@ivirshup , hi, no, i'm not.
ivirshup commentedon Jun 25, 2019
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.sparseand 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:
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).falexwolf commentedon Jun 26, 2019
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.0directly, which I think should be an option. A lot of code will break in people's notebooks, and also within Scanpy, accessing.Xis 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 withscanpy 1.5, I guess.Last question: I still think one needs convenient access to vectors along the data matrix. And as we have
.obs_vectoralready, it should be that. Maybe, in some distant future, we'd also have.X[:, gene][which would conform withadata[:, gene].Xand probably be most efficient], but that might be more tricky than the family ofArrayView,DataFrameViewetc. (if it still exists). However, if it's easy enough to subclassnp.ndarray,sp.spmatrixandh5py.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.
flying-sheep commentedon Jun 26, 2019
For completeness’ sake I’d like to enumerate the options:
.Xand flatten layers as well.ad[:, 1].Xorad[:, 'GeneA'].Xreturn a(n_obs,)array (1D),ad[:, [1]].Xorad[:, :1].Xreturn a(n_obs, 1)array (2D).len(ad[i, j].X.shape) == 2for all validis andjs.ad[int_or_str, int_or_str].Xis a special case that returns a single floatI also think “predictability”/“always-2d” is the best option.
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)).