Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions docs/release-notes/4112.fix.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
Make {func}`scanpy.metrics.modularity` produce the exact same results as `igraph` itself,
see `https://github.com/scverse/scanpy/blob/e4e43830ea3d5af0acd99648612612551fa7b83e/tests/test_metrics.py#L340 <here>`__.
In Scanpy 2.0, all graphs will be calculated slightly differently, using {meth}`igraph.Graph.Weighted_Adjacency`.
{smaller}`P Angerer`
3 changes: 2 additions & 1 deletion src/scanpy/_utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@
"compute_association_matrix_of_groups",
"descend_classes_and_funcs",
"ensure_igraph",
"get_igraph_from_adjacency",
"get_literal_vals",
"indent",
"is_backed_type",
Expand Down Expand Up @@ -287,7 +288,7 @@ def check_use_raw(
# --------------------------------------------------------------------------------


def get_igraph_from_adjacency(adjacency: CSBase, *, directed: bool = False) -> Graph:
def get_igraph_from_adjacency(adjacency: CSBase, *, directed: bool) -> Graph:
"""Get igraph graph from adjacency matrix."""
import igraph as ig

Expand Down
7 changes: 3 additions & 4 deletions src/scanpy/metrics/_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from natsort import natsorted
from pandas.api.types import CategoricalDtype

from .._utils import NeighborsView
from .._utils import NeighborsView, get_igraph_from_adjacency

if TYPE_CHECKING:
from collections.abc import Sequence
Expand Down Expand Up @@ -203,15 +203,14 @@ def modularity_array(
connectivities: AnyArrayLike | SpBase, /, *, labels: AnyArrayLike, is_directed: bool
) -> float:
try:
import igraph as ig
import igraph # noqa: F401
except ImportError as e: # pragma: no cover
e.add_note(
"`igraph` is required for computing modularity. "
"Please install `igraph` and try again."
)
raise
igraph_mode: str = ig.ADJ_DIRECTED if is_directed else ig.ADJ_UNDIRECTED
graph: ig.Graph = ig.Graph.Weighted_Adjacency(connectivities, mode=igraph_mode)
graph = get_igraph_from_adjacency(connectivities, directed=is_directed)
return graph.modularity(_codes(labels), "weight")


Expand Down
2 changes: 1 addition & 1 deletion src/scanpy/neighbors/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -571,7 +571,7 @@ def distances_dpt(self) -> OnFlySymMatrix:

def to_igraph(self) -> Graph:
"""Generate igraph from connectiviies."""
return _utils.get_igraph_from_adjacency(self.connectivities)
return _utils.get_igraph_from_adjacency(self.connectivities, directed=False)

@_doc_params(n_pcs=doc_n_pcs, use_rep=doc_use_rep)
def compute_neighbors(
Expand Down
2 changes: 1 addition & 1 deletion src/scanpy/plotting/_tools/paga.py
Original file line number Diff line number Diff line change
Expand Up @@ -259,7 +259,7 @@ def _compute_pos( # noqa: PLR0912
else:
# igraph layouts
random.seed(random_state.bytes(8))
g = _sc_utils.get_igraph_from_adjacency(adjacency_solid)
g = _sc_utils.get_igraph_from_adjacency(adjacency_solid, directed=False)
if "rt" in layout:
g_tree = _sc_utils.get_igraph_from_adjacency(adj_tree)
pos_list = g_tree.layout(
Expand Down
2 changes: 1 addition & 1 deletion src/scanpy/tools/_draw_graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ def draw_graph( # noqa: PLR0913
# igraph doesn't use numpy seed
random.seed(random_state)

g = _utils.get_igraph_from_adjacency(adjacency)
g = _utils.get_igraph_from_adjacency(adjacency, directed=False)
if layout in {"fr", "drl", "kk", "grid_fr"}:
ig_layout = g.layout(layout, seed=init_coords.tolist(), **kwds)
elif "rt" in layout:
Expand Down
2 changes: 1 addition & 1 deletion src/scanpy/tools/_paga.py
Original file line number Diff line number Diff line change
Expand Up @@ -214,7 +214,7 @@ def _compute_connectivities_v1_0(self):

ones = self._neighbors.connectivities.copy()
ones.data = np.ones(len(ones.data))
g = _utils.get_igraph_from_adjacency(ones)
g = _utils.get_igraph_from_adjacency(ones, directed=False)
vc = igraph.VertexClustering(
g, membership=self._adata.obs[self._groups_key].cat.codes.values
)
Expand Down
11 changes: 6 additions & 5 deletions src/scanpy/tools/_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -54,12 +54,13 @@ def _get_pca_or_small_x(adata: AnnData, n_pcs: int | None) -> np.ndarray | CSRBa
logg.info(" using data matrix X directly")
return adata.X

if "X_pca" in adata.obsm:
if n_pcs is not None and n_pcs > adata.obsm["X_pca"].shape[1]:
msg = "`X_pca` does not have enough PCs. Rerun `sc.pp.pca` with adjusted `n_comps`."
pca_key = next((k for k in ("pca", "X_pca") if k in adata.obsm), None)
if pca_key is not None:
if n_pcs is not None and n_pcs > adata.obsm[pca_key].shape[1]:
msg = f"`{pca_key}` does not have enough PCs. Rerun `sc.pp.pca` with adjusted `n_comps`."
raise ValueError(msg)
x = adata.obsm["X_pca"][:, :n_pcs]
logg.info(f" using 'X_pca' with n_pcs = {x.shape[1]}")
x = adata.obsm[pca_key][:, :n_pcs]
logg.info(f" using {pca_key!r} with n_pcs = {x.shape[1]}")
return x

from ..preprocessing import pca
Expand Down
2 changes: 1 addition & 1 deletion tests/test_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -334,7 +334,7 @@ def test_modularity_adata(
assert 0 <= s <= 1
for (n0, s0), (n1, s1) in combinations(scores.items(), 2):
with subtests.test("equality", l=n0, r=n1):
assert pytest.approx(s0, rel=1e-6) == s1
assert s0 == s1
with subtests.test("update"):
assert adata.uns["leiden"]["modularity"] is scores["update"]

Expand Down
Loading