theislab / zellkonverter

Conversion between scRNA-seq objects
https://theislab.github.io/zellkonverter/
Other
144 stars 27 forks source link

Object to convert is not a Python object #104

Open ramadatta opened 9 months ago

ramadatta commented 9 months ago

Hi Luke,

Thanks for zellkonverter.

I downloaded one of the h5ad objects from here and ran the following code in jupyter notebook.

# Main packages
import scanpy as sc
import pandas as pd
import anndata as ad
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from scipy.stats import median_abs_deviation

# other packages
import os

# Figure parameters
sc.settings.set_figure_params(dpi=80, facecolor="white")

sc.settings.verbosity = 0
sc.logging.print_header()

# scanpy==1.9.6 anndata==0.10.3 umap==0.5.4 numpy==1.24.4 scipy==1.11.3 pandas==2.0.3 scikit-learn==1.3.2 statsmodels==0.14.0 pynndescent==0.5.10

adata = sc.read_h5ad('tabula-muris-senis-facs-processed-official-annotations-Aorta.h5ad')
adata

%%R
# BiocManager::install("zellkonverter")
library("zellkonverter")

%%R
# Convert an AnnData to a SingleCellExperiment
tabm4 <- zellkonverter::AnnData2SCE(adata, verbose = TRUE)

I can see the adata features:

AnnData object with n_obs × n_vars = 906 × 22966
    obs: 'FACS.selection', 'age', 'cell', 'cell_ontology_class', 'cell_ontology_id', 'free_annotation', 'method', 'mouse.id', 'sex', 'subtissue', 'tissue', 'n_genes', 'n_counts', 'louvain', 'leiden'
    var: 'n_cells', 'means', 'dispersions', 'dispersions_norm', 'highly_variable'
    uns: 'age_colors', 'cell_ontology_class_colors', 'leiden', 'louvain', 'neighbors', 'pca'
    obsm: 'X_pca', 'X_tsne', 'X_umap'
    varm: 'PCs'
    obsp: 'distances', 'connectivities'

but the AnnData2SCE command throws me below error:

ℹ Converting AnnData to SingleCellExperiment
✖ Converting AnnData to SingleCellExperiment ... failed

Fehler in py_to_r.default(adata$shape) : 
  Object to convert is not a Python object
---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/ipython/rmagic.py:401, in RMagics.eval(self, code)
    400     r_expr = ri.parse(code)
--> 401     value, visible = ri.evalr_expr_with_visible(
    402         r_expr
    403     )
    404 except (ri.embedded.RRuntimeError, ValueError) as exception:
    405     # Otherwise next return seems to have copy of error.

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/rinterface.py:196, in evalr_expr_with_visible(expr, envir)
    195 if error_occured[0]:
--> 196     raise embedded.RRuntimeError(_rinterface._geterrmessage())
    197 res = conversion._cdata_to_rinterface(r_res)

RRuntimeError: Fehler in py_to_r.default(adata$shape) : 
  Object to convert is not a Python object

During handling of the above exception, another exception occurred:

RInterpreterError                         Traceback (most recent call last)
Cell In[131], line 1
----> 1 get_ipython().run_cell_magic('R', '', '\n# Convert an AnnData to a SingleCellExperiment\ntabm4 <- zellkonverter::AnnData2SCE(adata, verbose = TRUE)\ntabm4\n')

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/IPython/core/interactiveshell.py:2515, in InteractiveShell.run_cell_magic(self, magic_name, line, cell)
   2513 with self.builtin_trap:
   2514     args = (magic_arg_s, cell)
-> 2515     result = fn(*args, **kwargs)
   2517 # The code below prevents the output from being displayed
   2518 # when using magics with decorator @output_can_be_silenced
   2519 # when the last Python token in the expression is a ';'.
   2520 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/ipython/rmagic.py:978, in RMagics.R(self, line, cell, local_ns)
    976     if not e.stdout.endswith(e.err):
    977         print(e.err)
--> 978     raise e
    979 finally:
    980     if self.device in DEVICES_STATIC:

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/ipython/rmagic.py:943, in RMagics.R(self, line, cell, local_ns)
    941         return_output = False
    942 else:
--> 943     text_result, result, visible = self.eval(code)
    944     text_output += text_result
    945     if visible:

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/ipython/rmagic.py:407, in RMagics.eval(self, code)
    404 except (ri.embedded.RRuntimeError, ValueError) as exception:
    405     # Otherwise next return seems to have copy of error.
    406     warning_or_other_msg = self.flush()
--> 407     raise RInterpreterError(code, str(exception),
    408                             warning_or_other_msg)
    409 finally:
    410     ro._print_deferred_warnings()

RInterpreterError: Failed to parse and evaluate line '\n# Convert an AnnData to a SingleCellExperiment\ntabm4 <- zellkonverter::AnnData2SCE(adata, verbose = TRUE)\ntabm4\n'.
R error message: 'Fehler in py_to_r.default(adata$shape) : \n  Object to convert is not a Python object'

May I kindly know how I can fix this error? Many thanks in advance!

lazappi commented 9 months ago

Running {zellkonverter} in a Jupyter notebook can be sometimes problematic. It seems like for some reason R doesn't see adata as a Python object. Do you have anndata2ri installed? What happens if you just print adata in an R chunk?

ramadatta commented 9 months ago

Yes, I have anndata2ri installed.

I have tried in a new notebook fresh and I get this:


%%R

adata

---------------------------------------------------------------------------
RRuntimeError                             Traceback (most recent call last)
File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/ipython/rmagic.py:401, in RMagics.eval(self, code)
    400     r_expr = ri.parse(code)
--> 401     value, visible = ri.evalr_expr_with_visible(
    402         r_expr
    403     )
    404 except (ri.embedded.RRuntimeError, ValueError) as exception:
    405     # Otherwise next return seems to have copy of error.

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/rinterface.py:196, in evalr_expr_with_visible(expr, envir)
    195 if error_occured[0]:
--> 196     raise embedded.RRuntimeError(_rinterface._geterrmessage())
    197 res = conversion._cdata_to_rinterface(r_res)

RRuntimeError: Fehler in (function (expr, envir = parent.frame(), enclos = if (is.list(envir) ||  : 
  Objekt 'adata' nicht gefunden

During handling of the above exception, another exception occurred:

RInterpreterError                         Traceback (most recent call last)
Cell In[10], line 1
----> 1 get_ipython().run_cell_magic('R', '', '\nadata\n')

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/IPython/core/interactiveshell.py:2515, in InteractiveShell.run_cell_magic(self, magic_name, line, cell)
   2513 with self.builtin_trap:
   2514     args = (magic_arg_s, cell)
-> 2515     result = fn(*args, **kwargs)
   2517 # The code below prevents the output from being displayed
   2518 # when using magics with decorator @output_can_be_silenced
   2519 # when the last Python token in the expression is a ';'.
   2520 if getattr(fn, magic.MAGIC_OUTPUT_CAN_BE_SILENCED, False):

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/ipython/rmagic.py:978, in RMagics.R(self, line, cell, local_ns)
    976     if not e.stdout.endswith(e.err):
    977         print(e.err)
--> 978     raise e
    979 finally:
    980     if self.device in DEVICES_STATIC:

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/ipython/rmagic.py:943, in RMagics.R(self, line, cell, local_ns)
    941         return_output = False
    942 else:
--> 943     text_result, result, visible = self.eval(code)
    944     text_output += text_result
    945     if visible:

File /opt/homebrew/Caskroom/mambaforge/base/envs/singlecell/lib/python3.11/site-packages/rpy2/ipython/rmagic.py:407, in RMagics.eval(self, code)
    404 except (ri.embedded.RRuntimeError, ValueError) as exception:
    405     # Otherwise next return seems to have copy of error.
    406     warning_or_other_msg = self.flush()
--> 407     raise RInterpreterError(code, str(exception),
    408                             warning_or_other_msg)
    409 finally:
    410     ro._print_deferred_warnings()

RInterpreterError: Failed to parse and evaluate line '\nadata\n'.
R error message: "Fehler in (function (expr, envir = parent.frame(), enclos = if (is.list(envir) ||  : \n  Objekt 'adata' nicht gefunden"```
lazappi commented 8 months ago

I think this is because you haven't passed adata to your R chunk using the --i option. See the example in the best practices book https://www.sc-best-practices.org/introduction/interoperability.html#accessing-r-from-python.

ramadatta commented 8 months ago

Thanks @lazappi. Let me work on this and come back!