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
In cell hashing or CITE-seq datasets, an additional count matrix is produced and it stores how many ADT/HTO barcodes (see this for details https://genomebiology.biomedcentral.com/track/pdf/10.1186/s13059-018-1603-1) a cell has. Then depending on the experiment type we use these barcodes to either demultiplex cells into their original "sources" (HTO case) or to quantify protein expression (ADT case). Here is the PBMC HTO file from Seurat tutorial (rows are sample names i.e. HTO barcode IDs, columns are cells):
Right now, we can store these counts in adata.obsm as @wflynny suggested, however there is no place to store barcode strings (or protein names or sample names depending on what barcodes represent) in adata.obsm. One hack would be to store them in adata.uns but that'd be very ugly. Alternatively one can store everything in adata.obs but that'd also pollute the obs and ignore the multivariate nature of the barcodes.
What would be a good solution here? Would it make sense to add "column names" to an adata.obsm? Since they're currently stored as numpy arrays this seems infeasible but how much effort is it to store them as dataframes (like obs) instead of matrices? Alternatively, sc.get might allow us to access a group of columns in adata.obs for convenience.
Let me know what you think. (Btw, related discussion: scverse/scanpy#351)
Maybe it's important to separate ADT (cite-seq) and HTO (hashing) cases because ADT is more in line with multimodal analysis which also includes protein+rna or atac+rna (e.g. https://www.nature.com/articles/s41587-019-0290-0). Scanpy's behaviour for multimodality is undefined since computational pipelines are not established. But the hashing case is very relevant for Scanpy because it enables the analysis of multiplexed samples.
In git master, pandas DataFrames are allowed as obsm entries. Check out #228 for a discussion.
I’m inclined to allow DataFrames there as long as they’re homogeneous, (inhomogeneous ones can be represented as hierarchical column index in obs, right?)
@gokceneraslan I like your idea of storing HTO/ADT into .obsm as this seems to almost ready to be used. However, as you point out, there are different use cases that we may want to consider to see if .obsm can accommodate all the functionality required.
In the case of CITE-seq (or Feature Barcodes as 10x calls them) the antibody capture counts are simply added at the end of the genes matrix. This is very convenient to, for example, plot gene expression and antibody abundance directly. What is problematic is to do clustering only using this data because it requires the isolation of these information. Putting the CITE-seq data into .obsm will not be useful for this as the current methods need the data in adata.X.
For cell hashing, once the samples had been demultiplexed, there should be no modifications or need to use these data. If demultiplexing is to be done inside scanpy a place to put matrix could be .obsm, and the methods to do the demultiplexing can be directed to find the data there.
For future cases in which ATAC-seq, or methylation are available together with RNA-seq for the same cell barcode, a place to store sparse matrices will be needed.
In general, what seems to be missing in scanpy is a placeholder for matrices that contain the same number of cells but different number of variables. Currently, the layers address the case of same cells, same genes. The missing relationship should be similar the the one between adata and adata.raw but extended to multiple cases, for example adata.citeseq, adata.atac etc. In Seurat, I think this is implemented as assays.
Under the above scenario, I could envision that something like this should be possible (extrapolating from current adata.raw functionality in which adata.obs is shared):
This should use the matrix and neighbors information contained in adata.citeseq, which itself is an AnnData object (as is already the case for adata.raw), and update adata.obs by adding the citeseq_clusterin column.
Implementing something like this does not look like a low hanging fruit but given the code already available for adata.raw maybe the possibility of such extension can be investigated.
Reacted by Bill Flynn, Gregor Sturm and Pau Badia i Mompel
changed the title [-]Using named obsm matrices for storing ADT/HTO barcode counts[/-][+]Additional modes (surface proteins, methylation, …)[/+]on Oct 23, 2019
I like the ideas in this discussion! While I've definitely got some thoughts on this, I wanted to point to how other people were dealing with this problem – so we can think about the pros and cons of their approaches:
Should we account for relationships across modalities? E.g. connect the transcript expression to the protein?
What can we steal from existing work? Is an Xarray or netCDF dataset a good model for this?
As is done with layers in parts, all functions gain a parameter to specify which layer to operate on.
Why do you think this would be too painful? I've played around with this a bit, and think it's promising. In particular I think it reduces a lot of complexity by establishing some shared code for argument handling.
About naming: Seurat calls its different modes “assays” SCE calls its layers “assays”. Confusing! I don’t want us to contribute to confusion, but why does nobody call this the way to store multimodal data “modes” outside of this issue? altExperiment is cumbersome, sidecar is cute.
Should we account for relationships across modalities? E.g. connect the transcript expression to the protein?
Good question. I’d assume the relationship here may even be a many-to-many graph for each pair of modes, right?
Why do you think this would be too painful?
We’d have to modify every single function, which is reason enough. If we do it my way, 3rd party code will just work instead of us having to bug them to change it. Also it’s easier to miss a mode='CITE' deep in the param list than using the wrong object as first parameter.
@flying-sheep I support your arguments against something like layers.
I don't understand exactly what you mean with making AnnData stateful. I guess that by setting adata.mode = 'prot' your suggestion is that this will set adata.X to contain 'prot' data (thus changing the shape) and move whatever was in adata.X, adata.var, adata.varm etc. to for example a RNA container? If that is the case, I also don't like it, especially because the mode is hidden away.
With respect to your preferred suggestion, why do you call it a 'wrapper'? I think you have something quite clear in mind already on how to implement this. I like the idea of using the word mode. That would be my preferred naming.
With respect to your question about what is global and what is mode specific I would say that anything related to obs and obsm is global because that's the axis shared by all modes. Otherwise, each mode should have its own .uns, .var, .var_names
Under your proposal, the following statements should be equivalent?
sc.tl.leiden(adata.mode['prot'], key_added='prot_clustering')
# now adata.obs has 'prot_clustering'
adata_prot=adata.mode('prot')
sc.tl.leiden(adata_prot, key_added='prot_clustering')
# now adata.obs has 'prot_clustering'
With respect to your preferred suggestion, why do you call it a 'wrapper'?
The idea is that it isn’t an AnnData object, it just behaves like one. All operations regarding obs go directly to a parent AnnData object, with the difference that shape, X, layers, var{,m,p}, are for a different mode.
Our API is already pretty big so I don’t think we should make different modes’ .var, … available directly via something like adata.mode_var['prot] or so. I think adata.mode['prot'].var is clean enough.
Under your proposal, the following statements should be equivalent?
Hmm, That’s the same code, except that one uses __getitem__ and the other __call__. I’m open on which one to use, but it shouldn’t be both. I was also thinking about only allowing the following, but I think it might be cumbersome? Maybe it’s clearer 🤔
That would force the use of alternative modes to be temporary, which would be clean for operations, but cumbersome to retrieve data, as aforementioned adata.mode['prot'].var wouldn’t work anymore.
It probably won’t take that long with a plan: We just need to
create a list of public APIs for AnnData
create a class (called, say ModeView) that implements them by deferring to self._parent (or self._modeless since _parent is already taken)
Create a new AlignedMapping aligned to the obs axis (almost like obsm’s class, only using another _view_class)
Write tests that make sure the right properties are shared and the other ones aren’t
Write tests about subsetting the original and the ModeView.
The only question left: Currently, AnnData objects can be “actualized” and “slice views”. This is because slice views can be actualized without creating a new object. I’m not sure how to cleanly solve this with a second kind of view (mode views).
@flying-sheep With respect to the open question. If we start by the principle that modes are anndata objects that share .obs, those actualizations and slices that involved .obs should propagate to all other modes while anything to do with .var only affects the current mode.
Sorry to have missed this discussion! I managed to injure myself and was out of action for most of the last couple weeks 🤕
Would it be fair to say what @flying-sheep is proposing is pretty similar to SingleCellExperimentsAltExp? My understanding: This would define a new object which has one master obs axis, but allow multiple options for var axes. You can then pick an axis and get a ModeView which would behave a lot like a AnnData object, but would allow updating the original.
I have a few api questions.
I want to create one of our paneled UMAP plots where I color the points by expression of transcripts and proteins. What does this call look like?
I have a graph associating two modalities, lets say SNPs and transcripts. Where is this stored, and how do I access it?
I've calculated a connectivity graph for both transcripts and surface markers. I now want to perform a joint clustering on the two graphs. a) did I have to choose specific keys to differentiate between these? b) What does this call look like? Can I still specify the modes in the call to leiden or are these networks just objects in obsp now?
It would be interesting, and powerful, if this could be extended to allow multiple obs "modes" (i.e. multiple datasets) along with multiple modalities. Similar to performing a joint clustering on cells across modalities, can we find a consistent regulatory networks across experiments? Any thoughts on this?
This looks interesting, are there any updates on implementing this? With totalVI we opted to put the protein expression in adata.obsm["protein_expression"] and names in .uns. It's not a very elegant solution.
Hi, AnnData is a great format to work with! We would like to use AnnData as our default data format. However this multi-modal feature is quite an important feature that we would require.
I was wondering whether there is any ETA for having this feature implemented AnnData ?
interesting discussion! I like the adata.mode["prot"].{X,var,...} API and also its context-manager variant.
As far as I understood, you are assuming that obs is shared between all modes. However, when working with immune receptor (IR) data, it would be very "clean" to have the IR-related obs columns in a separate "mode" than the transcriptome-related columns. Both modes would have the same n_obs, though.
In scirpy, we currently store all IR-related information (such as VDJ-genes) in obs for
easy plotting with scanpy. However, this clutters obs with many automatically generated columns (see example below). Therefore, for this usecase it would be nice to have separate adata.obs and adata.mode["ir"].obs.
In this context, parsing strings for explicit access to the different modes while plotting also sounds like a great idea:
Hi, +1 from me to the modes API as well and I can see how I can fit dandelion's slots to that system. Being a complete novice, I went about the long way to create a different class object to handle the bits I wanted to acheive with dandelion and then just transfer to the .obs slot afterwards. I have the same issue as with @grst with the whole chunk of data that comes from immune receptors, and the format i'm adhering to is the one imposed by the Adaptive Immune Receptor Repertoire community standards for interoperability and consistency, but it may some times contain 100s of columns and not every column is going to be useful for every step. So a second data frame within the mode would be great i think.
Hi all, adding modes would be great, I stand for it as well!
What to do if multiple modes pass quality filtering differently? E.g. we lose cells x, y, z in the proteome but cells z, a, b in the transcriptome – x, y are however fine for transcriptome analysis and a, b for proteome analysis.
I wouldn't enforce cells to be shared across modalities. The set of cell IDs can be equal, intersect but in principle they can be completely disjoint (say a scRNA-seq experiment + scATAC-seq experiment on two splits of the same sample). Each modality will have their own filters. Of course, one may add a function to retain only shared cells. Moreover, as there will be more than 2 modalities, there will be no guarantee that a cell will survive in all of them
We need some way to allow keeping them. How? all-NA rows? a obs-mask per mode that is only respected by some algorithms? I don’t think .raw is the answer.
People want mode-specific .obsm. (E.g. a PCA for each mode). We could handle that by automatically appending f'_{mode_name}' to each basis (e.g. 'X_pca_prot') or by giving every mode its own .obs{,m,p}.
Wouldn't be better to think to AnnData as a hierarchical container in which each mode is a AnnData in the way you intend it today? I believe hdf5 supports that, also in that case you don't need to fill with NA or to name things differently. You only need some high-level function that is able to retrieve data from a specific mode (pretty much like you do with layers today)
An example for a multi-modal algorithm would be Stegle Labs’ MOFA. Another example is e.g. plotting stuff, e.g. transcript against protein: sc.pl.scatter(adata, x='CD8A', y='prot:CD8')
Nice! If modes will be available, MOFA+ could enter in the sc.external tools:
frommofapy2.run.entry_pointimportentry_pointimportscanpyasscshared_cells=sc.tl.get_shared_cells(adata, modes=['rna', 'meth'])
ent=entry_point()
D= [adata.mode['rna'], adata.mode['meth']]
M=2K=20N= [len(shared_cells)]
G=1data_mat= [[Noneforginrange(G)] forminrange(M)]
data_mat[0][0] =adata.mode['rna'].raw.X.toarray()
data_mat[1][0] =adata_mode['meth']raw.X.toarray()
ent.set_data_options(…)
ent.set_data_matrix(data_mat,
likelihoods= …,
views_names=adata.mode_keys(),
samples_names=[shared_cells],
features_names=[adata.mode['rna'].var_names, adata.mode['meth'].var_names]
)
ent.set_model_options(…)
ent.set_train_options(…)
ent.build()
ent.run()
#assuming if mode is not specified, is referred to object shared across modalitiesadata.obsm['X_mofa'] =ent['expectations']['Z']['group0'].value
Since this issue is coming up in relevant discussions, I'd mention — to the benefit of the reader — a recently introduced multimodal datatype, MuData, that builds on AnnData for individual modalities and has an AnnData-like interface itself (e.g. .obs, .var, .obsm attributes, etc.). It does store modalities in its .mod attribute (e.g. adata = mdata.mod["rna"]) and should address quite a few points from this discussion.
With respect to the anndata development, this raises a question if we might want to rather encourage the use of MuData for multimodal datasets rather than rewriting AnnData to handle multimodal designs.
This issue has been automatically marked as stale because it has not had recent activity.
Please add a comment if you want to keep the issue open. Thank you for your contributions!
Activity
gokceneraslan commentedon Oct 16, 2019
Maybe it's important to separate ADT (cite-seq) and HTO (hashing) cases because ADT is more in line with multimodal analysis which also includes protein+rna or atac+rna (e.g. https://www.nature.com/articles/s41587-019-0290-0). Scanpy's behaviour for multimodality is undefined since computational pipelines are not established. But the hashing case is very relevant for Scanpy because it enables the analysis of multiplexed samples.
flying-sheep commentedon Oct 18, 2019
In git master, pandas DataFrames are allowed as obsm entries. Check out #228 for a discussion.
I’m inclined to allow DataFrames there as long as they’re homogeneous, (inhomogeneous ones can be represented as hierarchical column index in
obs, right?)gokceneraslan commentedon Oct 18, 2019
Oh ok, I didn't know about the discussion at all :) That's super cool, I wrote a comment there.
fidelram commentedon Oct 21, 2019
@gokceneraslan I like your idea of storing HTO/ADT into
.obsmas this seems to almost ready to be used. However, as you point out, there are different use cases that we may want to consider to see if.obsmcan accommodate all the functionality required..obsmwill not be useful for this as the current methods need the data inadata.X..obsm, and the methods to do the demultiplexing can be directed to find the data there.In general, what seems to be missing in scanpy is a placeholder for matrices that contain the same number of cells but different number of variables. Currently, the
layersaddress the case of same cells, same genes. The missing relationship should be similar the the one betweenadataandadata.rawbut extended to multiple cases, for exampleadata.citeseq,adata.atacetc. In Seurat, I think this is implemented asassays.Under the above scenario, I could envision that something like this should be possible (extrapolating from current
adata.rawfunctionality in whichadata.obsis shared):This should use the matrix and neighbors information contained in
adata.citeseq, which itself is an AnnData object (as is already the case foradata.raw), and updateadata.obsby adding theciteseq_clusterincolumn.Implementing something like this does not look like a low hanging fruit but given the code already available for
adata.rawmaybe the possibility of such extension can be investigated.[-]Using named obsm matrices for storing ADT/HTO barcode counts[/-][+]Additional modes (surface proteins, methylation, …)[/+]flying-sheep commentedon Oct 23, 2019
I’m currently thinking about multimodal data. I think adding them to the count matrix is a bad idea. Instead I’m thinking about this:
Xwill becomeproperty(lambda self: self.layers[None])adata_prot = adata.mode('prot')Questions
.uns[mode][...]?Alternatives:
As is done with layers in parts, all functions gain a parameter to specify which layer to operate on.
Cumbersome and needs a lot of changes. No.
Make AnnData stateful:
adata.mode = 'prot'Flaky, hard to debug. An assignment that changes the shape? Weird! The wrapper/view idea seems like a straight upgrade!
ivirshup commentedon Oct 24, 2019
I like the ideas in this discussion! While I've definitely got some thoughts on this, I wanted to point to how other people were dealing with this problem – so we can think about the pros and cons of their approaches:
scater: Handle alternative experiments alanocallaghan/scater#93Brief, general questions:
Why do you think this would be too painful? I've played around with this a bit, and think it's promising. In particular I think it reduces a lot of complexity by establishing some shared code for argument handling.
flying-sheep commentedon Oct 24, 2019
About naming: Seurat calls its different modes “assays” SCE calls its layers “assays”. Confusing! I don’t want us to contribute to confusion, but why does nobody call this the way to store multimodal data “modes” outside of this issue?
altExperimentis cumbersome,sidecaris cute.Good question. I’d assume the relationship here may even be a many-to-many graph for each pair of modes, right?
We’d have to modify every single function, which is reason enough. If we do it my way, 3rd party code will just work instead of us having to bug them to change it. Also it’s easier to miss a
mode='CITE'deep in the param list than using the wrong object as first parameter.fidelram commentedon Oct 29, 2019
@flying-sheep I support your arguments against something like layers.
I don't understand exactly what you mean with making AnnData stateful. I guess that by setting
adata.mode = 'prot'your suggestion is that this will setadata.Xto contain 'prot' data (thus changing the shape) and move whatever was inadata.X,adata.var,adata.varmetc. to for example aRNAcontainer? If that is the case, I also don't like it, especially because the mode is hidden away.With respect to your preferred suggestion, why do you call it a 'wrapper'? I think you have something quite clear in mind already on how to implement this. I like the idea of using the word
mode. That would be my preferred naming.With respect to your question about what is global and what is mode specific I would say that anything related to
obsandobsmis global because that's the axis shared by all modes. Otherwise, each mode should have its own.uns,.var,.var_namesUnder your proposal, the following statements should be equivalent?
flying-sheep commentedon Oct 29, 2019
The idea is that it isn’t an
AnnDataobject, it just behaves like one. All operations regardingobsgo directly to a parentAnnDataobject, with the difference thatshape,X,layers,var{,m,p}, are for a different mode.Our API is already pretty big so I don’t think we should make different modes’
.var, … available directly via something likeadata.mode_var['prot]or so. I thinkadata.mode['prot'].varis clean enough.Hmm, That’s the same code, except that one uses
__getitem__and the other__call__. I’m open on which one to use, but it shouldn’t be both. I was also thinking about only allowing the following, but I think it might be cumbersome? Maybe it’s clearer 🤔That would force the use of alternative modes to be temporary, which would be clean for operations, but cumbersome to retrieve data, as aforementioned
adata.mode['prot'].varwouldn’t work anymore.fidelram commentedon Oct 29, 2019
Thanks for the reply. Sounds good to me. Any idea on how difficult/long it would be to implement this?
flying-sheep commentedon Oct 29, 2019
Thank you for the discussion 😄
It probably won’t take that long with a plan: We just need to
ModeView) that implements them by deferring toself._parent(orself._modelesssince_parentis already taken)AlignedMappingaligned to theobsaxis (almost likeobsm’s class, only using another_view_class)ModeView.The only question left: Currently, AnnData objects can be “actualized” and “slice views”. This is because slice views can be actualized without creating a new object. I’m not sure how to cleanly solve this with a second kind of view (mode views).
fidelram commentedon Nov 4, 2019
@flying-sheep With respect to the open question. If we start by the principle that modes are anndata objects that share
.obs, those actualizations and slices that involved.obsshould propagate to all other modes while anything to do with.varonly affects the current mode.ivirshup commentedon Nov 6, 2019
Sorry to have missed this discussion! I managed to injure myself and was out of action for most of the last couple weeks 🤕
Would it be fair to say what @flying-sheep is proposing is pretty similar to
SingleCellExperimentsAltExp? My understanding: This would define a new object which has one masterobsaxis, but allow multiple options forvaraxes. You can then pick an axis and get aModeViewwhich would behave a lot like a AnnData object, but would allow updating the original.I have a few api questions.
leidenor are these networks just objects inobspnow?It would be interesting, and powerful, if this could be extended to allow multiple
obs"modes" (i.e. multiple datasets) along with multiple modalities. Similar to performing a joint clustering on cells across modalities, can we find a consistent regulatory networks across experiments? Any thoughts on this?12 remaining items
flying-sheep commentedon Dec 22, 2019
Yeah, it’ll be quite complex to understand, not so much to implement. A good repr would help:
adamgayoso commentedon Jun 9, 2020
This looks interesting, are there any updates on implementing this? With totalVI we opted to put the protein expression in
adata.obsm["protein_expression"]and names in.uns. It's not a very elegant solution.scottgigante commentedon Jul 13, 2020
Bumping this. Would be extremely useful to have a unified API for this.
dweemx commentedon Dec 3, 2020
Hi,
AnnDatais a great format to work with! We would like to useAnnDataas our default data format. However this multi-modal feature is quite an important feature that we would require.I was wondering whether there is any ETA for having this feature implemented
AnnData?grst commentedon Dec 30, 2020
Hi all,
interesting discussion! I like the
adata.mode["prot"].{X,var,...}API and also its context-manager variant.As far as I understood, you are assuming that
obsis shared between all modes. However, when working with immune receptor (IR) data, it would be very "clean" to have the IR-relatedobscolumns in a separate "mode" than the transcriptome-related columns. Both modes would have the samen_obs, though.In scirpy, we currently store all IR-related information (such as VDJ-genes) in
obsforeasy plotting with scanpy. However, this clutters
obswith many automatically generated columns (see example below). Therefore, for this usecase it would be nice to have separateadata.obsandadata.mode["ir"].obs.In this context, parsing strings for explicit access to the different modes while plotting also sounds like a great idea:
gokceneraslan commentedon Jan 1, 2021
Just heard about dandelion (https://github.com/zktuong/dandelion/) on Twitter, looping in @zktuong too since he possibly thought about dandelion-scanpy integration.
zktuong commentedon Jan 5, 2021
Hi, +1 from me to the modes API as well and I can see how I can fit dandelion's slots to that system. Being a complete novice, I went about the long way to create a different class object to handle the bits I wanted to acheive with dandelion and then just transfer to the
.obsslot afterwards. I have the same issue as with @grst with the whole chunk of data that comes from immune receptors, and the format i'm adhering to is the one imposed by the Adaptive Immune Receptor Repertoire community standards for interoperability and consistency, but it may some times contain 100s of columns and not every column is going to be useful for every step. So a second data frame within the mode would be great i think.dawe commentedon Mar 5, 2021
Hi all, adding modes would be great, I stand for it as well!
I wouldn't enforce cells to be shared across modalities. The set of cell IDs can be equal, intersect but in principle they can be completely disjoint (say a scRNA-seq experiment + scATAC-seq experiment on two splits of the same sample). Each modality will have their own filters. Of course, one may add a function to retain only shared cells. Moreover, as there will be more than 2 modalities, there will be no guarantee that a cell will survive in all of them
Wouldn't be better to think to AnnData as a hierarchical container in which each mode is a AnnData in the way you intend it today? I believe hdf5 supports that, also in that case you don't need to fill with NA or to name things differently. You only need some high-level function that is able to retrieve data from a specific mode (pretty much like you do with layers today)
Nice! If modes will be available, MOFA+ could enter in the sc.external tools:
rcannood commentedon Jul 2, 2021
@flying-sheep @ivirshup Any updates on the mode API? 👀
gtca commentedon Jul 6, 2021
Since this issue is coming up in relevant discussions, I'd mention — to the benefit of the reader — a recently introduced multimodal datatype,
MuData, that builds onAnnDatafor individual modalities and has anAnnData-like interface itself (e.g..obs,.var,.obsmattributes, etc.). It does store modalities in its.modattribute (e.g.adata = mdata.mod["rna"]) and should address quite a few points from this discussion.This format is currently implemented as a part of the
muonframework for multimodal omics data analysis.For the CITE-seq analysis itself, which this thread has started with, there are a few relevant notebooks for
muon.With respect to the
anndatadevelopment, this raises a question if we might want to rather encourage the use ofMuDatafor multimodal datasets rather than rewritingAnnDatato handle multimodal designs.github-actions commentedon Jul 5, 2023
This issue has been automatically marked as stale because it has not had recent activity.
Please add a comment if you want to keep the issue open. Thank you for your contributions!
ivirshup commentedon Jul 5, 2023
Quite the issue!
While there were a ton of valuable ideas brought up in this thread, I'm going to mark this as completed since we now have MuData.