|
2 | 2 |
|
3 | 3 | from __future__ import annotations |
4 | 4 |
|
5 | | -from typing import TYPE_CHECKING |
| 5 | +from typing import TYPE_CHECKING, overload |
6 | 6 |
|
7 | 7 | import numpy as np |
8 | 8 | import pandas as pd |
| 9 | +from anndata import AnnData |
9 | 10 | from natsort import natsorted |
10 | 11 | from pandas.api.types import CategoricalDtype |
11 | 12 |
|
| 13 | +from .._utils import NeighborsView |
| 14 | + |
12 | 15 | if TYPE_CHECKING: |
13 | 16 | from collections.abc import Sequence |
| 17 | + from typing import Literal |
| 18 | + |
| 19 | + if TYPE_CHECKING: |
| 20 | + from pandas.api.typing.aliases import AnyArrayLike |
| 21 | + else: # sphinx-autodoc-typehints will execute the outer block, but end up here: |
| 22 | + AnyArrayLike = type( |
| 23 | + "AnyArrayLike", (), dict(__module__="pandas.api.typing.aliases") |
| 24 | + ) |
| 25 | + |
| 26 | + from .._compat import SpBase |
14 | 27 |
|
15 | 28 |
|
16 | 29 | def confusion_matrix( |
@@ -89,3 +102,119 @@ def confusion_matrix( |
89 | 102 | df = df.loc[np.array(orig_idx), np.array(new_idx)] |
90 | 103 |
|
91 | 104 | return df |
| 105 | + |
| 106 | + |
| 107 | +@overload |
| 108 | +def modularity( |
| 109 | + connectivities: AnyArrayLike | SpBase, /, labels: AnyArrayLike, *, is_directed: bool |
| 110 | +) -> float: ... |
| 111 | + |
| 112 | + |
| 113 | +@overload |
| 114 | +def modularity( |
| 115 | + adata: AnnData, |
| 116 | + /, |
| 117 | + labels: str | AnyArrayLike = "leiden", |
| 118 | + *, |
| 119 | + neighbors_key: str | None = None, |
| 120 | + mode: Literal["calculate", "update", "retrieve"] = "calculate", |
| 121 | +) -> float: ... |
| 122 | + |
| 123 | + |
| 124 | +def modularity( |
| 125 | + adata_or_connectivities: AnnData | AnyArrayLike | SpBase, |
| 126 | + /, |
| 127 | + labels: str | AnyArrayLike = "leiden", |
| 128 | + *, |
| 129 | + neighbors_key: str | None = None, |
| 130 | + is_directed: bool | None = None, |
| 131 | + mode: Literal["calculate", "update", "retrieve"] = "calculate", |
| 132 | +) -> float: |
| 133 | + """Compute the modularity of a graph given its connectivities and labels. |
| 134 | +
|
| 135 | + Parameters |
| 136 | + ---------- |
| 137 | + adata_or_connectivities |
| 138 | + The AnnData object containing the data or a weighted adjacency matrix representing the graph. |
| 139 | + labels |
| 140 | + Cluster labels for each node in the graph. |
| 141 | + When `AnnData` is provided, this can be the key in `adata.obs` that contains the clustering labels and defaults to `"leiden"`. |
| 142 | + neighbors_key |
| 143 | + When `AnnData` is provided, the key in `adata.obsp` that contains the connectivities. |
| 144 | + is_directed |
| 145 | + Whether the connectivities are directed or undirected. |
| 146 | + Always `False` if `AnnData` is provided, as connectivities are derived from (symmetric) neighbors. |
| 147 | + mode |
| 148 | + When `AnnData` is provided, |
| 149 | + this controls if the stored modularity is retrieved, |
| 150 | + or if we should calculate it (and optionally update it in `adata.uns[labels]`). |
| 151 | +
|
| 152 | + Returns |
| 153 | + ------- |
| 154 | + The modularity of the graph based on the provided clustering. |
| 155 | + """ |
| 156 | + if isinstance(adata_or_connectivities, AnnData): |
| 157 | + if is_directed: |
| 158 | + msg = f"Connectivities stored in `AnnData` are undirected, can’t specify `{is_directed=!r}`" |
| 159 | + raise ValueError(msg) |
| 160 | + return modularity_adata( |
| 161 | + adata_or_connectivities, |
| 162 | + labels=labels, |
| 163 | + neighbors_key=neighbors_key, |
| 164 | + mode=mode, |
| 165 | + ) |
| 166 | + if isinstance(labels, str): |
| 167 | + msg = "`labels` must be provided as array when passing a connectivities array" |
| 168 | + raise TypeError(msg) |
| 169 | + if is_directed is None: |
| 170 | + msg = "`is_directed` must be provided when passing a connectivities array" |
| 171 | + raise TypeError(msg) |
| 172 | + return modularity_array( |
| 173 | + adata_or_connectivities, labels=labels, is_directed=is_directed |
| 174 | + ) |
| 175 | + |
| 176 | + |
| 177 | +def modularity_adata( |
| 178 | + adata: AnnData, |
| 179 | + /, |
| 180 | + *, |
| 181 | + labels: str | AnyArrayLike, |
| 182 | + neighbors_key: str | None, |
| 183 | + mode: Literal["calculate", "update", "retrieve"], |
| 184 | +) -> float: |
| 185 | + if mode in {"retrieve", "update"} and not isinstance(labels, str): |
| 186 | + msg = "`labels` must be a string when `mode` is `'retrieve'` or `'update'`" |
| 187 | + raise ValueError(msg) |
| 188 | + if mode == "retrieve": |
| 189 | + return adata.uns[labels]["modularity"] |
| 190 | + |
| 191 | + labels_vec = adata.obs[labels] if isinstance(labels, str) else labels |
| 192 | + connectivities = NeighborsView(adata, neighbors_key)["connectivities"] |
| 193 | + |
| 194 | + # distances are treated as symmetric, so connectivities as well |
| 195 | + m = modularity(connectivities, labels_vec, is_directed=False) |
| 196 | + if mode == "update": |
| 197 | + adata.uns[labels]["modularity"] = m |
| 198 | + return m |
| 199 | + |
| 200 | + |
| 201 | +def modularity_array( |
| 202 | + connectivities: AnyArrayLike | SpBase, /, *, labels: AnyArrayLike, is_directed: bool |
| 203 | +) -> float: |
| 204 | + try: |
| 205 | + import igraph as ig |
| 206 | + except ImportError as e: # pragma: no cover |
| 207 | + msg = "igraph is require for computing modularity" |
| 208 | + raise ImportError(msg) from e |
| 209 | + igraph_mode: str = ig.ADJ_DIRECTED if is_directed else ig.ADJ_UNDIRECTED |
| 210 | + graph: ig.Graph = ig.Graph.Weighted_Adjacency(connectivities, mode=igraph_mode) |
| 211 | + return graph.modularity(_codes(labels)) |
| 212 | + |
| 213 | + |
| 214 | +def _codes(labels: AnyArrayLike) -> AnyArrayLike: |
| 215 | + """Convert cluster labels to integer codes as required by igraph.""" |
| 216 | + if isinstance(labels, pd.Series): |
| 217 | + labels = labels.astype("category").array |
| 218 | + if not isinstance(labels, pd.Categorical): |
| 219 | + labels = pd.Categorical(labels) |
| 220 | + return labels.codes |
0 commit comments