Repository navigation
Improve alignedmapping typing - #228
Conversation
All of the aligned mappings can hold dataframes. We test this anywhere that uses the As well as for
Does the fact that all of the aligned mappings can hold dataframes resolve this? I'm not sure if this is about something else.
They should only be indexed with |
Co-Authored-By: Isaac Virshup <[email protected]>
|
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 About layers being the only one aligned to both axes: I meant that it is the only |
Co-Authored-By: Isaac Virshup <[email protected]>
The main reason I allowed this is to test that we can handle arrays with labels (in this case,
|
|
Oh, but the only place I though the usage of |
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
See above: With
Yes, indexed with |
To me, the
My perspective with allowing dataframes in 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. |
|
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. |
|
@ivirshup what do you say now? |
|
@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.
Both of these let you accomplish things you wouldn't be able to with just numpy arrays. For 1, the pandas 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. |
|
Isn’t Another thing I want to enforce: No layer called |
|
I don't understand 90% of the discussion above but I have some practical questions/comments :)
|
|
Sorry for the big delay on feedback! I've been distracted with other work.
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.
I don't think I feel strongly about this. This was probably more "banned" before we stopped allowing
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.
👍 , I've found this useful for CITE seq data. |
Only the code says so. A guarantee exists the other way round though: If a df is homogeneous,
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.
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! |
|
So yeah, my vision:
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? |
We should definitely have data frames in I agree use cases for dataframes in
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
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). |
|
OK, decision time:
|
|
That sounds reasonable, I'll take another look at the code now. |
ivirshup
left a comment
There was a problem hiding this comment.
Just a few minor changes/ questions
See 62c4886
Let’s continue discussion here. I seem to misunderstand a few things about the new
AlignedMappings:obsmandvarm(AxisArrays) are the only ones where heterogenouspd.DataFrames can be put in?layers(Layers) is the onle one that is aligned to both axes instead of just one?strs? I mean technically there’s no need to, any hashable should work…