Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

%%R -i data_ent #49

Open
hatuyen4994 opened this issue Oct 19, 2020 · 21 comments
Open

%%R -i data_ent #49

hatuyen4994 opened this issue Oct 19, 2020 · 21 comments

Comments

@hatuyen4994
Copy link

hatuyen4994 commented Oct 19, 2020

Hi.
Thank you for a very thorough and excellent guide.
I've encountered a a type error while running the cell in the slingshot section. Error starts at the first line of the cell.
%%R -i adata_ent

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-142-648349c1be8b> in <module>
----> 1 get_ipython().run_cell_magic('R', '-i adata_ent', '\n#Plot 1\ncolour_map = brewer.pal(20,\'Set1\')\npar(xpd=TRUE)\npar(mar=c(4.5,5.5,2,7))\nplot(reducedDims(adata_ent)$PCA[,1], reducedDims(adata_ent)$PCA[,2], col=colour_map[colData(adata_ent)$louvain_final], bty=\'L\', xlab=\'PC1\', ylab=\'PC2\')\nlegend(x=12, y=12, legend=unique(colData(adata_ent)$louvain_final), fill=colour_map[as.integer(unique(colData(adata_ent)$louvain_final))])\n\nprint("1:")\nadata_ent_start <- slingshot(adata_ent, clusterLabels = \'louvain_final\', reducedDim = \'PCA\', start.clus=\'Stem\')\nprint(SlingshotDataSet(adata_ent_start))\n\nprint("")\nprint("2:")\nadata_ent_startend <- slingshot(adata_ent, clusterLabels = \'louvain_final\', reducedDim = \'PCA\', start.clus=\'Stem\', end.clus=c(\'Enterocyte mat. (Proximal)\', \'Enterocyte mat. (Distal)\'))\nprint(SlingshotDataSet(adata_ent_startend))\n\nprint("")\nprint("3:")\nadata_ent_simple_startend <- slingshot(adata_ent, clusterLabels = \'louvain_r0.5\', reducedDim = \'PCA\', start.clus=\'Stem\', end.clus=\'Enterocyte\')\nprint(SlingshotDataSet(adata_ent_simple_startend))\n')

~\Anaconda3\envs\sc-tutorial\lib\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-122> in R(self, line, cell, local_ns)

~\Anaconda3\envs\sc-tutorial\lib\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):

~\Anaconda3\envs\sc-tutorial\lib\site-packages\rpy2\ipython\rmagic.py in R(self, line, cell, local_ns)
    735                         raise NameError("name '%s' is not defined" % input)
    736                 with localconverter(converter) as cv:
--> 737                     ro.r.assign(input, val)
    738 
    739         if args.display:

~\Anaconda3\envs\sc-tutorial\lib\site-packages\rpy2\robjects\functions.py in __call__(self, *args, **kwargs)
    195                 v = kwargs.pop(k)
    196                 kwargs[r_k] = v
--> 197         return (super(SignatureTranslatedFunction, self)
    198                 .__call__(*args, **kwargs))
    199 

~\Anaconda3\envs\sc-tutorial\lib\site-packages\rpy2\robjects\functions.py in __call__(self, *args, **kwargs)
    124                 new_kwargs[k] = conversion.py2rpy(v)
    125         res = super(Function, self).__call__(*new_args, **new_kwargs)
--> 126         res = conversion.rpy2py(res)
    127         return res
    128 

~\Anaconda3\envs\sc-tutorial\lib\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')

~\Anaconda3\envs\sc-tutorial\lib\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)

~\Anaconda3\envs\sc-tutorial\lib\site-packages\anndata2ri\r2py.py in rpy2py_single_cell_experiment(obj)
     82 
     83     # TODO: Once the AnnData bug is fixed, remove the “or None”
---> 84     return AnnData(exprs, obs, var, uns, obsm or None, layers=layers)

~\Anaconda3\envs\sc-tutorial\lib\site-packages\anndata\_core\anndata.py in __init__(self, X, obs, var, uns, obsm, varm, layers, raw, dtype, shape, filename, filemode, asview, obsp, varp, oidx, vidx)
    305             self._init_as_view(X, oidx, vidx)
    306         else:
--> 307             self._init_as_actual(
    308                 X=X,
    309                 obs=obs,

~\Anaconda3\envs\sc-tutorial\lib\site-packages\anndata\_core\anndata.py in _init_as_actual(self, X, obs, var, uns, obsm, varm, varp, obsp, raw, layers, dtype, shape, filename, filemode)
    514 
    515         # Backwards compat for connectivities matrices in uns["neighbors"]
--> 516         _move_adj_mtx({"uns": self._uns, "obsp": self._obsp})
    517 
    518         self._check_dimensions()

~\Anaconda3\envs\sc-tutorial\lib\site-packages\anndata\compat\__init__.py in _move_adj_mtx(d)
    153         if (
    154             (k in n)
--> 155             and isinstance(n[k], (spmatrix, np.ndarray))
    156             and len(n[k].shape) == 2
    157         ):

~\Anaconda3\envs\sc-tutorial\lib\site-packages\rpy2\robjects\vectors.py in __getitem__(self, i)
    263 
    264     def __getitem__(self, i):
--> 265         res = super().__getitem__(i)
    266 
    267         if isinstance(res, Sexp):

~\Anaconda3\envs\sc-tutorial\lib\site-packages\rpy2\rinterface_lib\sexp.py in __getitem__(self, i)
    628             )
    629         else:
--> 630             raise TypeError(
    631                 'Indices must be integers or slices, not %s' % type(i))
    632         return res

TypeError: Indices must be integers or slices, not <class 'str'>

Here's is my adata_ent before input in the cell :

adata_ent
[Out]
AnnData object with n_obs × n_vars = 5495 × 4000
    obs: 'sample', 'region', 'donor', 'n_counts', 'log_counts', 'n_genes', 'mt_frac', 'size_factors', 'S_score', 'G2M_score', 'phase', 'louvain_r1', 'louvain_r0.5', 'Enterocyte_marker_expr', 'Stem_marker_expr', 'louvain_r0.5_entero_sub', 'louvain_r0.5_entero_mat_sub', 'louvain_final', 'prox_dist', 'umap_density_prox_dist'
    var: 'gene_id', 'n_cells', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
    uns: 'sample_colors', 'log1p', 'hvg', 'pca', 'neighbors', 'umap', 'diffmap_evals', 'draw_graph', 'phase_colors', 'louvain', 'louvain_r1_colors', 'louvain_r0.5_colors', 'region_colors', 'rank_genes_r0.5', 'louvain_r0.5_entero_sub_colors', 'rank_genes_r0.5_entero_sub', 'louvain_r0.5_entero_mat_sub_colors', 'rank_genes_r0.5_entero_mat_sub', 'louvain_final_colors', 'umap_density_prox_dist_params'
    obsm: 'X_pca', 'X_tsne', 'X_umap', 'X_diffmap', 'X_draw_graph_fa'
    varm: 'PCs'
    layers: 'counts'
    obsp: 'distances', 'connectivities'

Thank you for looking into this.

Regards,
T

@LuckyMD
Copy link
Contributor

LuckyMD commented Oct 20, 2020

Hi @hatuyen4994,

I notice that you have adapted the notebook code for Scanpy 1.5+ and a newer AnnData version as well. That's great, but unfortunately this also brings with it some anndata2ri issues. It looks to be as though your AnnData object has stored the neighborhood graph in adata.obsp, which is new since Scanpy 1.5. anndata2ri has not been updated to include to this yet. If you would like to move your adata object to R, I assume you would need to just store what is currently in adata.obsp in adata.uns['neighbors']. Something like:

adata.uns['neighbors']['connectivities'] = adata.obsp['connectivities']
adata.uns['neighbors']['distances'] = adata.obsp['distances']

should do the trick. You would of course have to move this back later if you plan to continue working with the object. You can check if this is the problem by just running an cell with:

%%R -i adata_ent
str(adata_ent)

To see if the same error occurs.

If the same error occurs there, I would suggest a you post a github issue to anndata2ri github. If I'm wrong, let me know :).

@mliiv
Copy link

mliiv commented Oct 29, 2020

Hi,

I have a similar issue I guess. AnnData object can not be read into R.

adata
AnnData object with n_obs × n_vars = 23873 × 16904
    obs: 'ClusterID', 'ClusterName', 'anno', 'condition', 'diffDay', 'hg19counts', 'nCount_RNA', 'nFeature_RNA', 'orig_ident', 'treatment', 'n_genes', 'percent_mito', 'percent_ribo', 'n_counts', 'size_factors', 'S_score', 'G2M_score', 'phase', 'louvain_r1', 'louvain_r05', 'leiden_r03'
    var: 'Selected', 'vst_mean', 'vst_variable', 'vst_variance', 'vst_variance_expected', 'vst_variance_standardized', 'gene_name', 'n_cells', 'highly_variable', 'means', 'dispersions', 'dispersions_norm'
    uns: 'pca', 'neighbors', 'draw_graph', 'louvain', 'leiden'
    obsm: 'X_pca', 'X_tsne', 'X_umap', 'X_draw_graph_fa'
    varm: 'PCs'
    layers: 'norm_data', 'counts'
    obsp: 'distances', 'connectivities'

%%R -i adata_test
str(adata_test)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-62-31544d8da0eb> in <module>
----> 1 get_ipython().run_cell_magic('R', '-i adata_test', 'str(adata_test)\n')

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_cell_magic(self, magic_name, line, cell)
   2357             with self.builtin_trap:
   2358                 args = (magic_arg_s, cell)
-> 2359                 result = fn(*args, **kwargs)
   2360             return result
   2361 

</research/users/marialiiv/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/site-packages/decorator.py:decorator-gen-844> in R(self, line, cell, local_ns)

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/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/sc-analysis3-clone2-clone/lib/python3.6/site-packages/rpy2/ipython/rmagic.py in R(self, line, cell, local_ns)
    710                         raise NameError("name '%s' is not defined" % input)
    711                 with localconverter(converter) as cv:
--> 712                     ro.r.assign(input, val)
    713 
    714         tmpd = self.setup_graphics(args)

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/site-packages/rpy2/robjects/functions.py in __call__(self, *args, **kwargs)
    190                 kwargs[r_k] = v
    191         return (super(SignatureTranslatedFunction, self)
--> 192                 .__call__(*args, **kwargs))
    193 
    194 

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/site-packages/rpy2/robjects/functions.py in __call__(self, *args, **kwargs)
    111 
    112     def __call__(self, *args, **kwargs):
--> 113         new_args = [conversion.py2rpy(a) for a in args]
    114         new_kwargs = {}
    115         for k, v in kwargs.items():

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/site-packages/rpy2/robjects/functions.py in <listcomp>(.0)
    111 
    112     def __call__(self, *args, **kwargs):
--> 113         new_args = [conversion.py2rpy(a) for a in args]
    114         new_kwargs = {}
    115         for k, v in kwargs.items():

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/functools.py in wrapper(*args, **kw)
    805                             '1 positional argument')
    806 
--> 807         return dispatch(args[0].__class__)(*args, **kw)
    808 
    809     funcname = getattr(func, '__name__', 'singledispatch function')

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/site-packages/anndata2ri/py2r.py in py2rpy_anndata(obj)
     58         assays = ListVector({**x, **layers})
     59 
---> 60         row_args = {k: pandas2ri.py2rpy(v) for k, v in obj.var.items()}
     61         if check_no_dupes(obj.var_names, "var_names"):
     62             row_args["row.names"] = pandas2ri.py2rpy(obj.var_names)

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/site-packages/anndata2ri/py2r.py in <dictcomp>(.0)
     58         assays = ListVector({**x, **layers})
     59 
---> 60         row_args = {k: pandas2ri.py2rpy(v) for k, v in obj.var.items()}
     61         if check_no_dupes(obj.var_names, "var_names"):
     62             row_args["row.names"] = pandas2ri.py2rpy(obj.var_names)

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/functools.py in wrapper(*args, **kw)
    805                             '1 positional argument')
    806 
--> 807         return dispatch(args[0].__class__)(*args, **kw)
    808 
    809     funcname = getattr(func, '__name__', 'singledispatch function')

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/site-packages/rpy2/robjects/pandas2ri.py in py2rpy_pandasseries(obj)
    142         # current conversion as performed by numpy
    143 
--> 144         res = func(obj)
    145         if len(obj.shape) == 1:
    146             if (obj.dtype != dt_O_type):

~/miniconda3/envs/sc-analysis3-clone2-clone/lib/python3.6/site-packages/rpy2/robjects/numpy2ri.py in numpy2rpy(o)
     69     # R does not support unsigned types:
     70     elif o.dtype.kind == 'u':
---> 71         raise(ValueError('Cannot convert numpy array of unsigned values '
     72                          '-- R does not have unsigned integers.'))
     73     # Array-of-PyObject is treated like a Python list:

ValueError: Cannot convert numpy array of unsigned values -- R does not have unsigned integers.

The fix you suggested @LuckyMD above did not help.

Packages are:
scanpy==1.4.4.post1 anndata==0.7.4 umap==0.3.10 numpy==1.17.3 scipy==1.3.1 pandas==1.1.3 scikit-learn==0.21.3 statsmodels==0.10.1 python-igraph==0.7.1 louvain==0.6.1

Would greatly appreciate help!
Thank you in advance,
Maria

@LuckyMD
Copy link
Contributor

LuckyMD commented Oct 29, 2020

Hi @mliiv,
Your error is related to anndata2ri rather than this tutorial. As the error says, you seem to have an array of unsigned integers in you adata object. This cannot be converted to R.

You can check which column of adata.obs or adata.var this is (I assume it's in there) via dtype.

@mliiv
Copy link

mliiv commented Oct 30, 2020

Hi @LuckyMD ,
ok, I see, thank you for the rapid response! Could it be that "dot..dot..dot" column between %mito and G2m score?
I will need to see where that is coming from.

image

@LuckyMD
Copy link
Contributor

LuckyMD commented Oct 30, 2020

no, that is just a question of how many columns you display in your jupyter notebook.

You should be able to check dtypes via adata.obs.dtypes (or just dtype, not sure about the s).

@mliiv
Copy link

mliiv commented Oct 30, 2020

thank you! I really can't really figure out what the unsigned integers are. Could it be the unit8 in var?

image

@LuckyMD
Copy link
Contributor

LuckyMD commented Oct 30, 2020

There you go... yes, it's the vst_variable column. You can convert to integer via adata.var['vst_variable'] = adata.var['vst_variable'].astype(int) and then it should work.

@mliiv
Copy link

mliiv commented Oct 30, 2020

It worked, thank you very much! Don't know how this one column changed like this, but such weird things happen when going through loom<->h5ad files back and forth, I guess.

@xuesen07
Copy link

xuesen07 commented Dec 16, 2020

Any follow-ups to this question? I've also encountered the same problem as @hatuyen4994 in trying to reproduce the results of the tutorial. The adata.uns['neighbors']['connectivities'] and adata.obsp['connectivities'] seem to have the same data structure.

In [159]:
adata_ent.uns['neighbors']['distances']
<ipython-input-159-cd1996413662>:1: FutureWarning: This location for 'distances' is deprecated. It has been moved to .obsp[distances], and will not be accesible here in a future version of anndata.
  adata_ent.uns['neighbors']['distances']
Out[159]:
<9466x9466 sparse matrix of type '<class 'numpy.float64'>'
	with 132142 stored elements in Compressed Sparse Row format>

In [160]:
adata_ent.obsp['distances']
Out[160]:
<9466x9466 sparse matrix of type '<class 'numpy.float64'>'
	with 132142 stored elements in Compressed Sparse Row format>

Anyone would like to post the data structure of adata_ent running the same version of scanpy as in the tutorial? Or any other suggestions?

@LuckyMD
Copy link
Contributor

LuckyMD commented Dec 16, 2020

Hi @jasonz-dot,

I am working to update the tutorial version to scanpy 1.6 compatibility. One part of that is indeed just replacing adata.uns['neighbors']['connectivities'] with adata.obsp['connectivities']. anndata2ri might also need an update for this. You could replace the two and things should work fine.

@xuesen07
Copy link

xuesen07 commented Dec 16, 2020

The adata_ent.obsp['connectivities'] and adata_ent.uns['neighbors']['connectivities'] store the same data and seem a little bit redundant. I've also noticed this is deprecated from the output of the codes.
I've run the commands as you mentioned before

adata_ent_1 = adata_ent.copy()
adata_ent_1.uns['neighbors']['connectivities'] = adata_ent_1.obsp['connectivities']
adata_ent_1.uns['neighbors']['distances'] = adata_ent_1.obsp['distances']

but when I run the following commands

%%R -i adata_ent_1
adata_ent_1

I still got the same error. So I'm guessing there may be some other bugs that caused the problem. Definitely looking forward to the updated tutorial! Thanks for the hardworking.

@LuckyMD
Copy link
Contributor

LuckyMD commented Dec 17, 2020

You would need to remove the .obsp as well for anndata2ri not to notice there's something stored there ;).

@xuesen07
Copy link

I run the command del adata_ent_1.obsp to remove the .obsp attribute, same error as before when import data into R...

@galib36
Copy link

galib36 commented Dec 18, 2020

I am also having the same issue. While I run %%R -i adata it gives the error TypeError: Indices must be integers or slices, not <class 'str'>. I tried running

adata.uns['neighbors']['connectivities'] = adata.obsp['connectivities']
adata.uns['neighbors']['distances'] = adata.obsp['distances']
del adata.obsp

but the issue persists. Any suggestion on how to solve this please?

@LuckyMD
Copy link
Contributor

LuckyMD commented Jan 5, 2021

Hi @galib36,

Your issue is not related to AnnData>0.7.1, and maybe should be reported in a separate issue. It seems instead that some indices in your adata object are strings. Do you know where this issue is coming up?

@LuckyMD
Copy link
Contributor

LuckyMD commented Jan 5, 2021

@jasonz-dot what error is it that you are getting? It would probably be good to report this in a separate issue.

@zenghua-git
Copy link

I am also having the same issue. While I run %%R -i adata it gives the error TypeError: Indices must be integers or slices, not <class 'str'>. I tried running

adata.uns['neighbors']['connectivities'] = adata.obsp['connectivities']
adata.uns['neighbors']['distances'] = adata.obsp['distances']
del adata.obsp

but the issue persists. Any suggestion on how to solve this please?

I've done the same and have the excatly same issue here!

@LuckyMD
Copy link
Contributor

LuckyMD commented Sep 30, 2021

Could you check adata.var_names.dtype, adata.obs_names.dtype, adata.var.dtypes, and adata.obs.dtypes.

@zenghua-git
Copy link

zenghua-git commented Oct 1, 2021

Could you check adata.var_names.dtype, adata.obs_names.dtype, adata.var.dtypes, and adata.obs.dtypes.

Thanks for reply! Yes, they look like this,
screen-2021-10-01-09-57-10

My anndata=0.7.4, scanpy=1.6.0.

But I tried to delete adata.uns , adata.varm, adata.obsp, and then imported to R, and it seems to work.
image

I was guessing slingshot doesn't need that much input, which may cause errors, so I tried to remove those layers. Now I'm not sure whether it may affect the followup slingshot code blocks in the notebook.

@LuckyMD
Copy link
Contributor

LuckyMD commented Oct 4, 2021

Hi @zenghua-git,

I haven't seen your full error traceback, but if it's the same as the OP above, then the issue lies in .uns or .obsp. So you removing those, would resolve this. Slingshot uses only the obs labels and the PCA computed in scanpy I think. So you should be fine as they are stored in .obs and .obsm.

I would be nice to find the root of this error though. Could it be that your object was subsetted before running slingshot? In that case you may need to ensure that the indices in the sparse matrices are contiguous. For adata.obsp['connectivities'] that can be done via (note: untested code):

if sparse.issparse(adata.obsp['connectivities']):
    if not adata.obsp['connectivities'].has_sorted_indices:
        adata.obsp['connectivities'].sort_indices()

@LuckyMD LuckyMD reopened this Oct 4, 2021
@zenghua-git
Copy link

zenghua-git commented Oct 4, 2021

Hi @zenghua-git,

I haven't seen your full error traceback, but if it's the same as the OP above, then the issue lies in .uns or .obsp. So you removing those, would resolve this. Slingshot uses only the obs labels and the PCA computed in scanpy I think. So you should be fine as they are stored in .obs and .obsm.

I would be nice to find the root of this error though. Could it be that your object was subsetted before running slingshot? In that case you may need to ensure that the indices in the sparse matrices are contiguous. For adata.obsp['connectivities'] that can be done via (note: untested code):

if sparse.issparse(adata.obsp['connectivities']):
    if not adata.obsp['connectivities'].has_sorted_indices:
        adata.obsp['connectivities'].sort_indices()

My error was exactly the same as the first post (hatuyen4994).

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-17-4f83d5b8882a> in <module>
----> 1 get_ipython().run_cell_magic('R', '-i adata', 'adata\n')

~/miniconda3/envs/sc-tutorial/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/sc-tutorial/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/sc-tutorial/lib/python3.8/site-packages/rpy2/ipython/rmagic.py in R(self, line, cell, local_ns)
    735                         raise NameError("name '%s' is not defined" % input)
    736                 with localconverter(converter) as cv:
--> 737                     ro.r.assign(input, val)
    738 
    739         if args.display:

~/miniconda3/envs/sc-tutorial/lib/python3.8/site-packages/rpy2/robjects/functions.py in __call__(self, *args, **kwargs)
    195                 v = kwargs.pop(k)
    196                 kwargs[r_k] = v
--> 197         return (super(SignatureTranslatedFunction, self)
    198                 .__call__(*args, **kwargs))
    199 

~/miniconda3/envs/sc-tutorial/lib/python3.8/site-packages/rpy2/robjects/functions.py in __call__(self, *args, **kwargs)
    124                 new_kwargs[k] = conversion.py2rpy(v)
    125         res = super(Function, self).__call__(*new_args, **new_kwargs)
--> 126         res = conversion.rpy2py(res)
    127         return res
    128 

~/miniconda3/envs/sc-tutorial/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/sc-tutorial/lib/python3.8/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)

~/miniconda3/envs/sc-tutorial/lib/python3.8/site-packages/anndata2ri/r2py.py in rpy2py_single_cell_experiment(obj)
     82 
     83     # TODO: Once the AnnData bug is fixed, remove the “or None”
---> 84     return AnnData(exprs, obs, var, uns, obsm or None, layers=layers)

~/miniconda3/envs/sc-tutorial/lib/python3.8/site-packages/anndata/_core/anndata.py in __init__(self, X, obs, var, uns, obsm, varm, layers, raw, dtype, shape, filename, filemode, asview, obsp, varp, oidx, vidx)
    305             self._init_as_view(X, oidx, vidx)
    306         else:
--> 307             self._init_as_actual(
    308                 X=X,
    309                 obs=obs,

~/miniconda3/envs/sc-tutorial/lib/python3.8/site-packages/anndata/_core/anndata.py in _init_as_actual(self, X, obs, var, uns, obsm, varm, varp, obsp, raw, layers, dtype, shape, filename, filemode)
    514 
    515         # Backwards compat for connectivities matrices in uns["neighbors"]
--> 516         _move_adj_mtx({"uns": self._uns, "obsp": self._obsp})
    517 
    518         self._check_dimensions()

~/miniconda3/envs/sc-tutorial/lib/python3.8/site-packages/anndata/compat/__init__.py in _move_adj_mtx(d)
    153         if (
    154             (k in n)
--> 155             and isinstance(n[k], (spmatrix, np.ndarray))
    156             and len(n[k].shape) == 2
    157         ):

~/miniconda3/envs/sc-tutorial/lib/python3.8/site-packages/rpy2/robjects/vectors.py in __getitem__(self, i)
    263 
    264     def __getitem__(self, i):
--> 265         res = super().__getitem__(i)
    266 
    267         if isinstance(res, Sexp):

~/miniconda3/envs/sc-tutorial/lib/python3.8/site-packages/rpy2/rinterface_lib/sexp.py in __getitem__(self, i)
    627             )
    628         else:
--> 629             raise TypeError(
    630                 'Indices must be integers or slices, not %s' % type(i))
    631         return res

TypeError: Indices must be integers or slices, not <class 'str'>

Right, removing 'uns, 'varm', 'obsp' did work.

You're right, my object was subsetted before running slingshot. Your code didn't work for me, and it still shows the same error before removing those slots, though I changed a little of the code (sparse --> scipy.sparse)

if scipy.sparse.issparse(adata.obsp['connectivities']):
    if not adata.obsp['connectivities'].has_sorted_indices:
        adata.obsp['connectivities'].sort_indices()

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

No branches or pull requests

6 participants