anndata2ri
anndata2ri copied to clipboard
Support BiocSingular’s LowRankMatrix
Hi!
I ran into a strange error when trying to write a quick script for Seurat -> Anndata conversion. I'm just loading data from a Seurat tutorial and then want to use their convert function to SingleCellExperiment, but anndata2ri is complaining. Here's the code:
%%R
library(Seurat)
# Load PBMC dataset from Seurat tutorial
pbmc.data <- Read10X(data.dir = "./filtered_gene_bc_matrices/hg19/")
# Initialize the Seurat object with the raw (non-normalized data).
pbmc <- CreateSeuratObject(counts = pbmc.data, project = "pbmc3k", min.cells = 3, min.features = 200)
%%R
#convert the Seurat object to a SingleCellExperiment object
pbmc_sce <- as.SingleCellExperiment(pbmc)
pbmc_sce
In the second cell, anndata2ri complains, although I have not put in any -o flags to output the object to python. The error message is the following:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-12-3fcf8ce65415> in <module>
----> 1 get_ipython().run_cell_magic('R', '', '#convert the Seurat object to a SingleCellExperiment object\npbmc_sce <- as.SingleCellExperiment(pbmc)\n\npbmc_sce\n')
/usr/local/lib/python3.7/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2350 with self.builtin_trap:
2351 args = (magic_arg_s, cell)
-> 2352 result = fn(*args, **kwargs)
2353 return result
2354
</usr/local/lib/python3.7/site-packages/decorator.py:decorator-gen-806> in R(self, line, cell, local_ns)
/usr/local/lib/python3.7/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
/usr/local/lib/python3.7/site-packages/rpy2/ipython/rmagic.py in R(self, line, cell, local_ns)
725 return_output = False
726 else:
--> 727 text_result, result, visible = self.eval(code)
728 text_output += text_result
729 if visible:
/usr/local/lib/python3.7/site-packages/rpy2/ipython/rmagic.py in eval(self, code)
257 try:
258 # Need the newline in case the last line in code is a comment.
--> 259 value, visible = ro.r("withVisible({%s\n})" % code)
260 except (ri.embedded.RRuntimeError, ValueError) as exception:
261 # Otherwise next return seems to have copy of error.
/usr/local/lib/python3.7/site-packages/rpy2/robjects/vectors.py in __getitem__(self, i)
260
261 if isinstance(res, Sexp):
--> 262 res = conversion.rpy2py(res)
263 return res
264
/usr/local/Cellar/python/3.7.2_2/Frameworks/Python.framework/Versions/3.7/lib/python3.7/functools.py in wrapper(*args, **kw)
822 '1 positional argument')
823
--> 824 return dispatch(args[0].__class__)(*args, **kw)
825
826 funcname = getattr(func, '__name__', 'singledispatch function')
/usr/local/lib/python3.7/site-packages/anndata2ri/r2py.py in rpy2py_s4(obj)
25 return rpy2py_data_frame(obj)
26 elif "SingleCellExperiment" in r_classes:
---> 27 return rpy2py_single_cell_experiment(obj)
28 elif supported_r_matrix_classes() & r_classes:
29 return rmat_to_spmat(obj)
/usr/local/lib/python3.7/site-packages/anndata2ri/r2py.py in rpy2py_single_cell_experiment(obj)
56 assay_names = [str(a) for a in se.assayNames(obj)]
57 # The assays can be stored in an env or elsewise so we don’t use obj.slots['assays']
---> 58 assays = [numpy2ri.rpy2py(assay).T for assay in (se.assay(obj, n) for n in assay_names)]
59 # There’s SingleCellExperiment with no assays
60 exprs, layers = assays[0], dict(zip(assay_names[1:], assays[1:]))
/usr/local/lib/python3.7/site-packages/anndata2ri/r2py.py in <listcomp>(.0)
56 assay_names = [str(a) for a in se.assayNames(obj)]
57 # The assays can be stored in an env or elsewise so we don’t use obj.slots['assays']
---> 58 assays = [numpy2ri.rpy2py(assay).T for assay in (se.assay(obj, n) for n in assay_names)]
59 # There’s SingleCellExperiment with no assays
60 exprs, layers = assays[0], dict(zip(assay_names[1:], assays[1:]))
AttributeError: 'RS4' object has no attribute 'T'
thx, works!
I get the same error message for a different problem, can't figure out what I am doing wrong, maybe someone could help me? I am trying to get fastMNN running in my jupyter notebook, but it's giving me this error. The line before (logcounts(adata) ...) works fine.
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
import anndata2ri
anndata2ri.activate()
%load_ext rpy2.ipython
import anndata
import numpy as np
importr('batchelor')
X = np.random.random((10, 20))
adata = anndata.AnnData(X)
adata.obs['cohort'] = ['c1', 'c2'] * 5
%%R -i adata
logcounts(adata) <- assay(adata, 'X')
fastMNN(adata, batch=adata$cohort)
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-4-7c3b7739d5cc> in <module>
----> 1 get_ipython().run_cell_magic('R', '-i adata', "\nlogcounts(adata) <- assay(adata, 'X')\nfastMNN(adata, batch=adata$cohort)\n")
~/miniconda3/envs/clinspect/lib/python3.8/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
2379 with self.builtin_trap:
2380 args = (magic_arg_s, cell)
-> 2381 result = fn(*args, **kwargs)
2382 return result
2383
<decorator-gen-121> in R(self, line, cell, local_ns)
~/miniconda3/envs/clinspect/lib/python3.8/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
185 # but it's overkill for just that one bit of state.
186 def magic_deco(arg):
--> 187 call = lambda f, *a, **k: f(*a, **k)
188
189 if callable(arg):
~/miniconda3/envs/clinspect/lib/python3.8/site-packages/rpy2/ipython/rmagic.py in R(self, line, cell, local_ns)
761 return_output = False
762 else:
--> 763 text_result, result, visible = self.eval(code)
764 text_output += text_result
765 if visible:
~/miniconda3/envs/clinspect/lib/python3.8/site-packages/rpy2/ipython/rmagic.py in eval(self, code)
266 try:
267 # Need the newline in case the last line in code is a comment.
--> 268 value, visible = ro.r("withVisible({%s\n})" % code)
269 except (ri.embedded.RRuntimeError, ValueError) as exception:
270 # Otherwise next return seems to have copy of error.
~/miniconda3/envs/clinspect/lib/python3.8/site-packages/rpy2/rinterface_lib/sexp.py in __iter__(self)
662 def __iter__(self) -> typing.Iterator[typing.Union[Sexp, VT, typing.Any]]:
663 for i in range(len(self)):
--> 664 yield self[i]
665
666 def index(self, item: typing.Any) -> int:
~/miniconda3/envs/clinspect/lib/python3.8/site-packages/rpy2/robjects/vectors.py in __getitem__(self, i)
266
267 if isinstance(res, Sexp):
--> 268 res = conversion.rpy2py(res)
269 return res
270
~/miniconda3/envs/clinspect/lib/python3.8/functools.py in wrapper(*args, **kw)
873 '1 positional argument')
874
--> 875 return dispatch(args[0].__class__)(*args, **kw)
876
877 funcname = getattr(func, '__name__', 'singledispatch function')
~/miniconda3/envs/clinspect/lib/python3.8/site-packages/anndata2ri/r2py.py in rpy2py_s4(obj)
26 return rpy2py_data_frame(obj)
27 elif "SingleCellExperiment" in r_classes:
---> 28 return rpy2py_single_cell_experiment(obj)
29 elif supported_r_matrix_classes() & r_classes:
30 return rmat_to_spmat(obj)
~/miniconda3/envs/clinspect/lib/python3.8/site-packages/anndata2ri/r2py.py in rpy2py_single_cell_experiment(obj)
74 assay_names = [str(a) for a in se.assayNames(obj)]
75 # The assays can be stored in an env or elsewise so we don’t use obj.slots['assays']
---> 76 assays = [mat_converter.rpy2py(assay).T for assay in (se.assay(obj, n) for n in assay_names)]
77 # There’s SingleCellExperiment with no assays
78 exprs, layers = assays[0], dict(zip(assay_names[1:], assays[1:]))
~/miniconda3/envs/clinspect/lib/python3.8/site-packages/anndata2ri/r2py.py in <listcomp>(.0)
74 assay_names = [str(a) for a in se.assayNames(obj)]
75 # The assays can be stored in an env or elsewise so we don’t use obj.slots['assays']
---> 76 assays = [mat_converter.rpy2py(assay).T for assay in (se.assay(obj, n) for n in assay_names)]
77 # There’s SingleCellExperiment with no assays
78 exprs, layers = assays[0], dict(zip(assay_names[1:], assays[1:]))
AttributeError: 'RS4' object has no attribute 'T'
Exact same problem here running fastMNN within Jupyter notebook. Things I tried that didn't work:
- saving the SingleCellExperiment object as RDS and reloading (works within R)
- Running
library(SingleCellExperiment)before conversion - converting all matrices in assays to
dgRMatrix
Was this ever resolved? Having same problem running fastMNN
I added some code that helps with error messages in #82, now we can see
TypeError: Cannot convert assay “reconstructed” of type(s) [LowRankMatrix] to Python
If you don’t need it, you can delete that assay before converting.
Otherwise we need to add support for that class, any idea what would fit?
I assume it’s this class: https://rdrr.io/bioc/BiocSingular/man/LowRankMatrix.html
Hi, if anyone here could manage to resolve that "AttributeError: 'RS4' object has no attribute 'T'" for fastMNN?