Skip to content

Improve alignedmapping typing - #228

Merged
flying-sheep merged 11 commits into
masterfrom
aligned-typing
Oct 24, 2019
Merged

flying-sheep merged 11 commits into
masterfrom
aligned-typing

Conversation

@flying-sheep

Copy link
Copy Markdown
Member

See 62c4886

Let’s continue discussion here. I seem to misunderstand a few things about the new AlignedMappings:

  • I thought obsm and varm (AxisArrays) are the only ones where heterogenous pd.DataFrames can be put in?
  • I thought layers (Layers) is the onle one that is aligned to both axes instead of just one?
  • I thought all of those are indexed only with strs? I mean technically there’s no need to, any hashable should work…

@ivirshup

Copy link
Copy Markdown
Member

I thought obsm and varm (AxisArrays) are the only ones where heterogenous pd.DataFrames can be put in?

All of the aligned mappings can hold dataframes. We test this anywhere that uses the gen_adata helper (which is a lot of the view and io tests)

https://github.com/theislab/anndata/blob/914d7375a93ca617bd6dee1565097656e6e1d359/anndata/tests/helpers.py#L130-L134

As well as for obsp and varp:

https://github.com/theislab/anndata/blob/914d7375a93ca617bd6dee1565097656e6e1d359/anndata/tests/test_obspvarp.py#L25-L45

I thought layers (Layers) is the onle one that is aligned to both axes instead of just one?

Does the fact that all of the aligned mappings can hold dataframes resolve this? I'm not sure if this is about something else.

I thought all of those are indexed only with strs? I mean technically there’s no need to, any hashable should work…

They should only be indexed with str if the user wants to write them to hdf5 or zarr, but I don't think that's enforced by these types. In general, I lean towards keeping the typing as broad as possible.

Comment thread anndata/core/alignedmapping.py Resolved
Comment thread anndata/core/alignedmapping.py Resolved
Co-Authored-By: Isaac Virshup <[email protected]>
@flying-sheep

Copy link
Copy Markdown
Member Author

I think it’s weird to allow dataframes with heterogeneous columns in a pairwise matrix (those should hold symmetric or asymmetric transitions right? Homogeneous data), and slightly less weird when aligned to genes (Why should gene A have a str column and gene B a float column?)

About layers being the only one aligned to both axes: I meant that it is the only AlignedMapping whose members gets sliced when either AnnData axis is sliced, i.e. the only one needing to remember a 2D index.

Co-Authored-By: Isaac Virshup <[email protected]>
@ivirshup

Copy link
Copy Markdown
Member

I think it’s weird to allow dataframes with heterogeneous columns in a pairwise matrix

The main reason I allowed this is to test that we can handle arrays with labels (in this case, index and column) in these fields. I would like to also include sparse dataframes here, as well as xarray data arrays. Plus dataframes don't have to have heterogenous element types.

About layers being the only one aligned to both axes

obsp and varp will also get indexed on two axes.

@ivirshup

Copy link
Copy Markdown
Member

Oh, but the only place I though the usage of OneDIdx should change was _subset_df

@flying-sheep

Copy link
Copy Markdown
Member Author

Plus dataframes don't have to have heterogenous element types.

They’re designed to have a heterogeneous axis and a homogeneous one. AnnData is designed to have homogeneous 2D layers and 2× heterogeneous 2D annotations per axis.

I don’t like varp/obsp and layers to be able to contain something heterogeneous. Users will be confused and it doesn’t fit AnnData’s design. We could runtime check if a DataFrame is homogeneous, in Layer.__setitem__, but it’s probably easier to not support DataFrames there and test with another class.

Oh, but the only place I though the usage of OneDIdx should change was _subset_df

See above: With DataFrame layers that would make sense, but I don’t think DataFrame layers should exist.

obsp and varp will also get indexed on two axes.

Yes, indexed with (subset_idx, subset_idx). Both axes of an obsp matrix are aligned to one AnnData axis.

@ivirshup

Copy link
Copy Markdown
Member

the only place I though the usage of OneDIdx should change was _subset_df

To me, the _subset is meant to be an interface for array-like objects that subsets them consistently with respect to the index provided. I think it should be considered separately from the alignedmapping module, and probably moved to a utils file or maybe views.

We could runtime check if a DataFrame is homogeneous, in Layer.setitem, but it’s probably easier to not support DataFrames there and test with another class.

My perspective with allowing dataframes in layers was that it's pretty common for people have data (especially expression matrices) in dataframes already. I also like the simplicity of non-defensive code, and not having to special case too much as long as we can provide consistent behavior. It seems like more effort to define behavior specific to dataframes, rather than to say "we accept them, it's up to you whether that's useful".

I guess it would be fine to define some behavior for dataframes, we'd just have to decide what that is. If we're going to require they're homogenous, then I'd probably say we should just convert them to a ndarray.

@flying-sheep

flying-sheep commented Sep 24, 2019 •

Copy link
Copy Markdown
Member Author

I hear you. Less code is better.

However, non-defensive code has the disadvantage that not allowing stuff at first and gradually opening up useful cases will result in less messy code and less backwards-compat hacks.

How about this?

def df_to_homogeneous_arr(df)
    arr = df.to_numpy()
    if df.dtypes.nunique() != 1:
        warn(f'Layer {key!r} converted to numpy array with dtype {arr.dtype}')
    return arr

class Layer(...):
    ...
    def __setitem__(self, key, layer):
        if isinstance(layer, pd.DataFrame):
            layer = df_to_homogeneous_arr(layer)
        ...

The pandas docs say that if there’s a homogeneous dataframe, there’s no copy being made when converting to numpy, which makes the operation pretty efficient.

@flying-sheep

Copy link
Copy Markdown
Member Author

@ivirshup what do you say now?

@ivirshup

Copy link
Copy Markdown
Member

@flying-sheep I've been thinking about it, and want to go back on my previous statement (that homogenous dataframes should be converted to ndarrays) for a couple reasons.

  1. Dataframes have very useful methods.
  2. Dataframes have an extension dtype mechanism.

Both of these let you accomplish things you wouldn't be able to with just numpy arrays. For 1, the pandas .rank method is much more powerful than numpys. For 2, you could have categories of cell interactions in obsp.

I'm still dubious about the proposition objects in layers, obsp, and varp need have homogenous dtypes, but even if they do – I think there's value in allowing the containers to be dataframes.

@flying-sheep

flying-sheep commented Oct 2, 2019 •

Copy link
Copy Markdown
Member Author

Isn’t pd.DataFrame(adata.layers['foo']).do_stuff() easy enough? I’m pretty sure it creates a slim view over the array, so it should be pretty much for free to do this on the fly.

Another thing I want to enforce: No layer called X, '' or None, as I want to unify layers and X down the road.

@gokceneraslan

Copy link
Copy Markdown
Contributor

I don't understand 90% of the discussion above but I have some practical questions/comments :)

  • What happens if a DataFrame layer has an index different than adata.obs.index?
  • What happens if a DataFrame layer has column names different than adata.var_names? Isn't it too much flexibility given that the initial idea for layers was to support coupled features like unspliced/spliced counts of genes.
  • Same questions for obsp/varp.
  • One advantage of having a DF in obsm/varm (even for homogeneous data) is the ability to store column names (seem trivial but can be useful) That'd be great for storing HTO barcodes as I wrote in Additional modes (surface proteins, methylation, …) #237. This is also a case where just doing pd.DataFrame(adata.obsm[bla]) doesn't solve the issue. Image a sc.pp.read_hashtags() method that reads a csv file and stores such barcodes in obsm (see Interest in HTO/ADT demultiplexing and analysis? scanpy#351). Then a sc.tl. method can simply read adata.obsm[hashtag] field that's created by sc.pp.read_hashtags() and use both the values and column names to produce things.

@ivirshup

Copy link
Copy Markdown
Member

Sorry for the big delay on feedback! I've been distracted with other work.

@flying-sheep

Isn’t pd.DataFrame(adata.layers['foo']).do_stuff() easy enough? I’m pretty sure it creates a slim view over the array, so it should be pretty much for free to do this on the fly.

Does pandas promise that it will always be slim view? I'd expect other dataframe libraries (especially cudf) wouldn't be. I'd also note that pandas extension dtypes won't convert to numpy arrays, and there's going to be performance changes around C vs Fortran array ordering.

Another thing I want to enforce: No layer called X, '' or None, as I want to unify layers and X down the road.

I don't think I feel strongly about this. This was probably more "banned" before we stopped allowing use_rep="X".

@gokceneraslan

What happens if a DataFrame layer has an index different than adata.obs.index
What happens if a DataFrame layer has column names different than adata.var_names? Isn't it too much flexibility given that the initial idea for layers was to support coupled features like unspliced/spliced counts of genes.

We probably shouldn't allow either of these. I'd thought they wouldn't be, but it looks like they are at the moment. Any axis aligned to the one of the main axes should have the same labels. This is similar to netCDF and xarray.

One advantage of having a DF in obsm/varm (even for homogeneous data) is the ability to store column names

👍 , I've found this useful for CITE seq data.

@flying-sheep

Copy link
Copy Markdown
Member Author

Does pandas promise that it will always be slim view?

Only the code says so. A guarantee exists the other way round though: If a df is homogeneous, to_numpy will return a view.

We probably shouldn't allow either of these

That’s exactly my problem: data frames are so complex that supporting them in more places means opening a can of worms, and either having to introduce checks everywhere or risk inconsistency.

👍, I've found this useful for CITE seq data.

As above: Allowing dataframes in more places has more implications than just “neat, we get colnames”.

The multimodal usecase will be covered more thoroughly by #237. Let’s get that going!

@flying-sheep

flying-sheep commented Oct 23, 2019 •

Copy link
Copy Markdown
Member Author

So yeah, my vision:

  • modes allow having different sets of layers with different variables and the same observations as described in Additional modes (surface proteins, methylation, …) #237
  • layers becomes unified with X.
  • layers/obsm/varm/obsp/varp entries are each homogeneous in type, and are realized as dense or sparse arrays (possibly disk-backed).

Do you think any of this is unrealistic/impractical for daily use? What operations on DataFrames did you guys find useful that aren’t available for arrays? When would someone ever need a pandas extension dtype anywhere but in obs/var? What array or dataframe classes/packages exist and which ones should be able to go where in your opinion?

@ivirshup

ivirshup commented Oct 24, 2019 •

Copy link
Copy Markdown
Member

layers/obsm/varm/obsp/varp entries are each homogeneous in type, and are realized as dense or sparse arrays (possibly disk-backed).

We should definitely have data frames in obsm and varm. varm is probably where differential expression results (as dataframes) should go, but would also make it easier to organize data than just putting it all in .obs, .var. This might be pretty similar to your thinking about X just being an elements of layers. Here, obs/var would just be elements of obsm/varm.

I agree use cases for dataframes in .layers and .obsp, .varp aren't as obvious. That's mainly me not seeing any huge drawbacks. (Potential compromise: warn that it's experimental and see if issues crop up?).

That’s exactly my problem: data frames are so complex that supporting them in more places means opening a can of worms, and either having to introduce checks everywhere or risk inconsistency.

I was making more of a general statement on labelled arrays. We already do throw an error for the case I thought we shouldn't allow:

import scanpy as sc
import pandas as pd
import numpy as np

adata = sc.AnnData(
    X=np.ones((10, 10)),
    obs=pd.DataFrame([], index=[f"cell{i}" for i in range(10)]),
    var=pd.DataFrame([], index=[f"gene{i}" for i in range(10)])
)
newdf = pd.DataFrame([np.arange(10)], index=[f"obs{i}" for i in range(10)])

adata.obsm["new"] = newdf
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-6-5bd9adc00a4f> in <module>
----> 1 adata.obsm["new"] = newdf

~/github/anndata/anndata/core/alignedmapping.py in __setitem__(self, key, value)
    176 
    177     def __setitem__(self, key: str, value: V):
--> 178         self._validate_value(value, key)
    179         self._data[key] = value
    180 

~/github/anndata/anndata/core/alignedmapping.py in _validate_value(self, val, key)
     79             # Could probably also re-order index if it's contained
     80             if not (val.index == self.dim_names).all():
---> 81                 raise IndexError()  # Maybe not index error
     82         except AttributeError:
     83             pass

Do you think any of this is unrealistic/impractical for daily use? What operations on DataFrames did you guys find useful that aren’t available for arrays?

  • Labelled columns in obsm, varm are really useful. For homogenous data it's possible that Xarray would be a better option, though its sparse support is limited at the moment, and uses the pydata/sparse api.
  • Not having to put all "annotation"-like info in .obs, .var is very useful for keeping my objects organized. For example, I might have multiple versions of qc metrics based on different pipelines. SingleCellExperiment achieves something similar with nested dataframes.

When would someone ever need a pandas extension dtype anywhere but in obs/var?

Besides the cases where it's useful to just store a dataframe, I think arrays of user defined datatypes are a very powerful tool. Numpy doesn't make defining methods on these particularly easy, but I think pandas has (i.e. categoricals, geo-pandas). That said, this did get me thinking about how similar things could be done by using numba (numba/numba#4740).

@flying-sheep

flying-sheep commented Oct 24, 2019 •

Copy link
Copy Markdown
Member Author

OK, decision time:

  • This PR’s code for {obs,var}p and layers will stay: DataFrames will be converted to arrays there, and there’ll be a warning if the conversion changed the dtype.
  • {obs,var}m will continue to allow DataFrames

@ivirshup

Copy link
Copy Markdown
Member

That sounds reasonable, I'll take another look at the code now.

@ivirshup ivirshup left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just a few minor changes/ questions

Comment thread anndata/core/alignedmapping.py Resolved
Comment thread anndata/core/alignedmapping.py Resolved
Comment thread anndata/core/anndata.py Resolved
Comment thread anndata/core/anndata.py Resolved
Comment thread anndata/tests/test_layers.py Resolved
@flying-sheep
flying-sheep merged commit 6310e3e into master Oct 24, 2019
@flying-sheep
flying-sheep deleted the aligned-typing branch October 24, 2019 12:49
Comment thread anndata/core/alignedmapping.py Resolved
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants