|
29 | 29 |
|
30 | 30 | import h5py |
31 | 31 | import numpy as np |
| 32 | +import pandas as pd |
32 | 33 | from anndata._core.sparse_dataset import BaseCompressedSparseDataset |
33 | 34 | from packaging.version import Version |
34 | 35 |
|
|
44 | 45 | from anndata import AnnData |
45 | 46 | from igraph import Graph |
46 | 47 | from numpy.typing import ArrayLike, NDArray |
| 48 | + from pandas._typing import Dtype as PdDtype |
47 | 49 |
|
48 | 50 | from .._compat import CSRBase |
49 | 51 | from ..neighbors import NeighborsParams, RPForestDict |
|
79 | 81 | "sanitize_anndata", |
80 | 82 | "select_groups", |
81 | 83 | "update_params", |
| 84 | + "with_cat_dtype", |
82 | 85 | ] |
83 | 86 |
|
84 | 87 |
|
@@ -287,7 +290,7 @@ def get_igraph_from_adjacency(adjacency: CSBase, *, directed: bool = False) -> G |
287 | 290 | import igraph as ig |
288 | 291 |
|
289 | 292 | sources, targets = adjacency.nonzero() |
290 | | - weights = dematrix(adjacency[sources, targets]).ravel() |
| 293 | + weights = dematrix(adjacency[sources, targets]).ravel() if len(sources) else [] |
291 | 294 | g = ig.Graph(directed=directed) |
292 | 295 | g.add_vertices(adjacency.shape[0]) # this adds adjacency.shape[0] vertices |
293 | 296 | g.add_edges(list(zip(sources, targets, strict=True))) |
@@ -494,6 +497,23 @@ def moving_average(a: np.ndarray, n: int): |
494 | 497 | return ret[n - 1 :] / n |
495 | 498 |
|
496 | 499 |
|
| 500 | +@singledispatch |
| 501 | +def with_cat_dtype[X: pd.Series | pd.CategoricalIndex | pd.Categorical]( |
| 502 | + x: X, dtype: PdDtype |
| 503 | +) -> X: |
| 504 | + raise NotImplementedError |
| 505 | + |
| 506 | + |
| 507 | +@with_cat_dtype.register(pd.Series) |
| 508 | +def _(x: pd.Series, dtype: PdDtype) -> pd.Series: |
| 509 | + return x.cat.set_categories(x.cat.categories.astype(dtype)) |
| 510 | + |
| 511 | + |
| 512 | +@with_cat_dtype.register(pd.Categorical | pd.CategoricalIndex) |
| 513 | +def _[X: pd.Categorical | pd.CategoricalIndex](x: X, dtype: PdDtype) -> X: |
| 514 | + return x.set_categories(x.categories.astype(dtype)) |
| 515 | + |
| 516 | + |
497 | 517 | # -------------------------------------------------------------------------------- |
498 | 518 | # Deal with tool parameters |
499 | 519 | # -------------------------------------------------------------------------------- |
|
0 commit comments