scverse / scanpy

Single-cell analysis in Python. Scales to >1M cells.
https://scanpy.readthedocs.io
BSD 3-Clause "New" or "Revised" License
1.87k stars 595 forks source link

unexpected error in sc.pl.dpt_timeseries and dpt_groups_pseudotime #3086

Open FessenSimon opened 3 months ago

FessenSimon commented 3 months ago

Please make sure these conditions are met

What happened?

sc.tl.dpt was successfully done. But when I want to plot the result of dpt,the error comes out

Minimal code sample

sc.tl.dpt(a1,n_branchings=2)
sc.pl.dpt_groups_pseudotime(a1)
sc.pl.dpt_timeseries(a1)

Error output

Error in dpt_timeseries:

WARNING: Plotting more than 100 genes might take some while, consider selecting only highly variable genes, for example.
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
TypeError: float() argument must be a string or a real number, not 'csr_matrix'

The above exception was the direct cause of the following exception:

ValueError                                Traceback (most recent call last)
Cell In[85], line 1
----> 1 sc.pl.dpt_timeseries(a1)

File D:\anaconda\Lib\site-packages\legacy_api_wrap\__init__.py:80, in legacy_api.<locals>.wrapper.<locals>.fn_compatible(*args_all, **kw)
     77 @wraps(fn)
     78 def fn_compatible(*args_all: P.args, **kw: P.kwargs) -> R:
     79     if len(args_all) <= n_positional:
---> 80         return fn(*args_all, **kw)
     82     args_pos: P.args
     83     args_pos, args_rest = args_all[:n_positional], args_all[n_positional:]

File D:\anaconda\Lib\site-packages\scanpy\plotting\_tools\__init__.py:245, in dpt_timeseries(adata, color_map, show, save, as_heatmap, marker)
    242 # only if number of genes is not too high
    243 if as_heatmap:
    244     # plot time series as heatmap, as in Haghverdi et al. (2016), Fig. 1d
--> 245     timeseries_as_heatmap(
    246         adata.X[adata.obs["dpt_order_indices"].values],
    247         var_names=adata.var_names,
    248         highlights_x=adata.uns["dpt_changepoints"],
    249         color_map=color_map,
    250     )
    251 else:
    252     # plot time series as gene expression vs time
    253     timeseries(
    254         adata.X[adata.obs["dpt_order_indices"].values],
    255         var_names=adata.var_names,
   (...)
    258         marker=marker,
    259     )

File D:\anaconda\Lib\site-packages\scanpy\plotting\_utils.py:227, in timeseries_as_heatmap(X, var_names, highlights_x, color_map)
    223     x_new[:, _hold:] = X[:, hold:]
    225 _, ax = plt.subplots(figsize=(1.5 * 4, 2 * 4))
    226 img = ax.imshow(
--> 227     np.array(X, dtype=np.float_),
    228     aspect="auto",
    229     interpolation="nearest",
    230     cmap=color_map,
    231 )
    232 plt.colorbar(img, shrink=0.5)
    233 plt.yticks(range(X.shape[0]), var_names)

ValueError: setting an array element with a sequence.

Error in dpt_groups_pseudotime:

ValueError                                Traceback (most recent call last)
Cell In[91], line 1
----> 1 sc.pl.dpt_groups_pseudotime(a1)

File D:\anaconda\Lib\site-packages\legacy_api_wrap\__init__.py:80, in legacy_api.<locals>.wrapper.<locals>.fn_compatible(*args_all, **kw)
     77 @wraps(fn)
     78 def fn_compatible(*args_all: P.args, **kw: P.kwargs) -> R:
     79     if len(args_all) <= n_positional:
---> 80         return fn(*args_all, **kw)
     82     args_pos: P.args
     83     args_pos, args_rest = args_all[:n_positional], args_all[n_positional:]

File D:\anaconda\Lib\site-packages\scanpy\plotting\_tools\__init__.py:276, in dpt_groups_pseudotime(adata, color_map, palette, show, save, marker)
    274 """Plot groups and pseudotime."""
    275 _, (ax_grp, ax_ord) = plt.subplots(2, 1)
--> 276 timeseries_subplot(
    277     adata.obs["dpt_groups"].cat.codes,
    278     time=adata.obs["dpt_order"].values,
    279     color=np.asarray(adata.obs["dpt_groups"]),
    280     highlights_x=adata.uns["dpt_changepoints"],
    281     ylabel="dpt groups",
    282     yticks=(
    283         np.arange(len(adata.obs["dpt_groups"].cat.categories), dtype=int)
    284         if len(adata.obs["dpt_groups"].cat.categories) < 5
    285         else None
    286     ),
    287     palette=palette,
    288     ax=ax_grp,
    289     marker=marker,
    290 )
    291 timeseries_subplot(
    292     adata.obs["dpt_pseudotime"].values,
    293     time=adata.obs["dpt_order"].values,
   (...)
    301     marker=marker,
    302 )
    303 savefig_or_show("dpt_groups_pseudotime", save=save, show=show)

File D:\anaconda\Lib\site-packages\scanpy\plotting\_utils.py:140, in timeseries_subplot(X, time, color, var_names, highlights_x, xlabel, ylabel, yticks, xlim, legend, palette, color_map, ax, marker)
    138 x_range = np.arange(X.shape[0]) if time is None else time
    139 if X.ndim == 1:
--> 140     X = X[:, None]
    141 if X.shape[1] > 1:
    142     colors = palette[: X.shape[1]].by_key()["color"]

File ~\AppData\Roaming\Python\Python311\site-packages\pandas\core\series.py:1153, in Series.__getitem__(self, key)
   1150     key = np.asarray(key, dtype=bool)
   1151     return self._get_rows_with_mask(key)
-> 1153 return self._get_with(key)

File ~\AppData\Roaming\Python\Python311\site-packages\pandas\core\series.py:1163, in Series._get_with(self, key)
   1158     raise TypeError(
   1159         "Indexing a Series with DataFrame is not "
   1160         "supported, use the appropriate DataFrame column"
   1161     )
   1162 elif isinstance(key, tuple):
-> 1163     return self._get_values_tuple(key)
   1165 elif not is_list_like(key):
   1166     # e.g. scalars that aren't recognized by lib.is_scalar, GH#32684
   1167     return self.loc[key]

File ~\AppData\Roaming\Python\Python311\site-packages\pandas\core\series.py:1203, in Series._get_values_tuple(self, key)
   1198 if com.any_none(*key):
   1199     # mpl compat if we look up e.g. ser[:, np.newaxis];
   1200     #  see tests.series.timeseries.test_mpl_compat_hack
   1201     # the asarray is needed to avoid returning a 2D DatetimeArray
   1202     result = np.asarray(self._values[key])
-> 1203     disallow_ndim_indexing(result)
   1204     return result
   1206 if not isinstance(self.index, MultiIndex):

File ~\AppData\Roaming\Python\Python311\site-packages\pandas\core\indexers\utils.py:341, in disallow_ndim_indexing(result)
    333 """
    334 Helper function to disallow multi-dimensional indexing on 1D Series/Index.
    335 
   (...)
    338 in GH#30588.
    339 """
    340 if np.ndim(result) > 1:
--> 341     raise ValueError(
    342         "Multi-dimensional indexing (e.g. `obj[:, None]`) is no longer "
    343         "supported. Convert to a numpy array before indexing instead."
    344     )

ValueError: Multi-dimensional indexing (e.g. `obj[:, None]`) is no longer supported. Convert to a numpy array before indexing instead.

Versions

```----- anndata 0.10.5.post1 scanpy 1.10.1 ----- PIL 9.4.0 annoy NA anyio NA asttokens NA attr 22.1.0 autograd NA autograd_gamma NA babel 2.11.0 backcall 0.2.0 bbknn 1.6.0 beta_ufunc NA binom_ufunc NA bottleneck 1.3.5 brotli NA certifi 2024.02.02 cffi 1.15.1 chardet 4.0.0 charset_normalizer 2.0.4 cloudpickle 2.2.1 colorama 0.4.6 comm 0.1.2 cycler 0.10.0 cython_runtime NA cytoolz 0.12.0 dask 2023.6.0 dateutil 2.8.2 debugpy 1.6.7 decorator 5.1.1 defusedxml 0.7.1 dill 0.3.6 entrypoints 0.4 executing 0.8.3 fastjsonschema NA formulaic 1.0.1 future 0.18.3 gseapy 1.1.2 h5py 3.9.0 hypergeom_ufunc NA idna 3.4 igraph 0.11.5 interface_meta 1.3.0 invgauss_ufunc NA ipykernel 6.25.0 ipython_genutils 0.2.0 ipywidgets 8.0.4 jedi 0.18.1 jinja2 3.1.2 joblib 1.2.0 json5 NA jsonpointer 2.1 jsonschema 4.17.3 jupyter_server 1.23.4 jupyterlab_server 2.22.0 kiwisolver 1.4.4 legacy_api_wrap NA leidenalg 0.10.2 lifelines 0.28.0 llvmlite 0.42.0 louvain 0.8.2 lz4 4.3.2 markupsafe 2.1.1 matplotlib 3.7.2 matplotlib_inline 0.1.6 mpl_toolkits NA natsort 8.4.0 nbformat 5.9.2 nbinom_ufunc NA ncf_ufunc NA nct_ufunc NA ncx2_ufunc NA numba 0.59.1 numexpr 2.8.4 numpy 1.26.4 packaging 23.1 pandas 2.2.2 parso 0.8.3 patsy 0.5.3 pickleshare 0.7.5 pkg_resources NA platformdirs 3.10.0 plotly 5.9.0 prometheus_client NA prompt_toolkit 3.0.36 psutil 5.9.0 pure_eval 0.2.2 pvectorc NA pyarrow 11.0.0 pycparser 2.21 pydev_ipython NA pydevconsole NA pydevd 2.9.5 pydevd_file_utils NA pydevd_plugins NA pydevd_tracing NA pygments 2.15.1 pynndescent 0.5.11 pyparsing 3.0.9 pyrsistent NA pythoncom NA pytz 2023.3.post1 pywintypes NA requests 2.31.0 rfc3339_validator 0.1.4 rfc3986_validator 0.1.1 ruamel NA scipy 1.11.1 seaborn 0.13.2 send2trash NA session_info 1.0.0 setuptools 69.5.1 six 1.16.0 skewnorm_ufunc NA sklearn 1.3.0 sniffio 1.2.0 socks 1.7.1 sparse 0.15.1 sphinxcontrib NA stack_data 0.2.0 statsmodels 0.14.0 tblib 1.7.0 terminado 0.17.1 texttable 1.7.0 threadpoolctl 2.2.0 tlz 0.12.0 toolz 0.12.0 torch 2.2.1+cpu torchgen NA tornado 6.3.2 tqdm 4.65.0 traitlets 5.7.1 typing_extensions NA umap 0.5.5 urllib3 1.26.16 wcwidth 0.2.5 websocket 0.58.0 win32api NA win32com NA win32con NA win32trace NA winerror NA winpty 2.0.10 wrapt 1.14.1 xxhash 2.0.2 yaml 6.0 zipp NA zmq 23.2.0 zope NA ----- IPython 8.15.0 jupyter_client 7.4.9 jupyter_core 5.3.0 jupyterlab 3.6.3 notebook 6.5.4 ----- Python 3.11.5 | packaged by Anaconda, Inc. | (main, Sep 11 2023, 13:26:23) [MSC v.1916 64 bit (AMD64)] Windows-10-10.0.22631-SP0 ----- Session information updated at 2024-06-02 17:20 ```
flying-sheep commented 3 months ago

Please create a fully reproducible example. I can’t help if I don’t have an AnnData object that doesn’t behave like yours.

FessenSimon commented 3 months ago

Dear professor Philipp A.

Thank you of your patience. I've attached my Anndata and codes in the attachment.

Kind regards

Original Email

Sender:"Philipp A."< @.*** >;

Sent Time:2024/6/7 19:28

To:"scverse/scanpy"< @.*** >;

Cc recipient:"FessenSimon"< @. >;"Author"< @. >;

Subject:Re: [scverse/scanpy] unexpected error in sc.pl.dpt_timeseries anddpt_groups_pseudotime (Issue #3086)

Please create a fully reproducible example. I can’t help if I don’t have an AnnData object that doesn’t behave like yours.

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you authored the thread.Message ID: @.***>

                    从QQ邮箱发来的超大附件    

                                                                    repro.zip                            (321.0MB, 2024年7月8日 16:26)                                                                             进入下载页面                          :https://wx.mail.qq.com/ftn/download?func=3&k=ca9c3c356e51f263f8ef48353a6462397a35692138646239104c1e410b56560c535b4b025c050314505550571501005a034e055008575700575252015d546b3947061647574a1850457756363f313de49719e585e08cd2a2c51d8b742d5c&key=ca9c3c356e51f263f8ef48353a6462397a35692138646239104c1e410b56560c535b4b025c050314505550571501005a034e055008575700575252015d546b3947061647574a1850457756363f313de49719e585e08cd2a2c51d8b742d5c&code=5cf58db9&from=