|
| 1 | +from typing import TypeAlias |
| 2 | + |
| 3 | +import leidenalg as la |
| 4 | +import numpy as np |
| 5 | +from anndata import AnnData |
| 6 | +from igraph import Graph |
| 7 | +from numpy.typing import NDArray |
| 8 | +from scipy.sparse import find, sparray, spmatrix |
| 9 | + |
| 10 | +_GraphArray: TypeAlias = sparray | spmatrix | np.ndarray |
| 11 | + |
| 12 | + |
| 13 | +def _build_igraph(adjacency: _GraphArray, *, directed: bool = True) -> Graph: |
| 14 | + # adapted from scanpy https://github.com/scverse/scanpy |
| 15 | + sources, targets, weights = find(adjacency) |
| 16 | + g = Graph(directed=directed) |
| 17 | + g.add_vertices(adjacency.shape[0]) |
| 18 | + g.add_edges(list(zip(sources, targets))) |
| 19 | + g.es["weight"] = weights |
| 20 | + if g.vcount() != adjacency.shape[0]: |
| 21 | + raise RuntimeError( |
| 22 | + f"The constructed graph has only {g.vcount()} nodes. " |
| 23 | + "Your adjacency matrix contained redundant nodes." |
| 24 | + ) |
| 25 | + return g |
| 26 | + |
| 27 | + |
| 28 | +def leiden_multiplex( |
| 29 | + latent_neighbors: _GraphArray, |
| 30 | + spatial_neighbors: _GraphArray, |
| 31 | + *, |
| 32 | + directed: tuple[bool, bool] = (True, True), |
| 33 | + use_weights: bool = True, |
| 34 | + n_iterations: int = -1, |
| 35 | + partition_type=la.RBConfigurationVertexPartition, |
| 36 | + layer_weights: tuple[int, int] = (1, 1), |
| 37 | + latent_partition_kwargs: dict | None = None, |
| 38 | + spatial_partition_kwargs: dict | None = None, |
| 39 | + seed: int = 42, |
| 40 | +) -> NDArray[np.integer]: |
| 41 | + |
| 42 | + adjacency_latent = _build_igraph(latent_neighbors, directed=directed[0]) |
| 43 | + adjacency_spatial = _build_igraph(spatial_neighbors, directed=directed[1]) |
| 44 | + |
| 45 | + # parameterise the partitions |
| 46 | + if spatial_partition_kwargs is None: |
| 47 | + spatial_partition_kwargs = dict() |
| 48 | + if latent_partition_kwargs is None: |
| 49 | + latent_partition_kwargs = dict() |
| 50 | + |
| 51 | + if use_weights: |
| 52 | + spatial_partition_kwargs["weights"] = "weight" |
| 53 | + latent_partition_kwargs["weights"] = "weight" |
| 54 | + |
| 55 | + latent_part = partition_type(adjacency_latent, **latent_partition_kwargs) |
| 56 | + spatial_part = partition_type(adjacency_spatial, **spatial_partition_kwargs) |
| 57 | + |
| 58 | + optimiser = la.Optimiser() |
| 59 | + optimiser.set_rng_seed(seed) |
| 60 | + |
| 61 | + _ = optimiser.optimise_partition_multiplex( |
| 62 | + [latent_part, spatial_part], |
| 63 | + layer_weights=list(layer_weights), |
| 64 | + n_iterations=n_iterations, |
| 65 | + ) |
| 66 | + |
| 67 | + return np.array(latent_part.membership) |
| 68 | + |
| 69 | + |
| 70 | +def spatialleiden( |
| 71 | + adata: AnnData, |
| 72 | + *, |
| 73 | + resolution: tuple[int, int] = (1, 1), |
| 74 | + latent_neighbors: _GraphArray | None = None, |
| 75 | + spatial_neighbors: _GraphArray | None = None, |
| 76 | + key_added: str = "spatialleiden", |
| 77 | + directed: tuple[bool, bool] = (True, True), |
| 78 | + use_weights: bool = True, |
| 79 | + n_iterations: int = -1, |
| 80 | + partition_type=la.RBConfigurationVertexPartition, |
| 81 | + layer_weights: tuple[int, int] = (1, 1), |
| 82 | + latent_distance_key: str = "connectivities", |
| 83 | + spatial_distance_key: str = "spatial_connectivities", |
| 84 | + latent_partition_kwargs: dict | None = None, |
| 85 | + spatial_partition_kwargs: dict | None = None, |
| 86 | + seed: int = 42, |
| 87 | +): |
| 88 | + |
| 89 | + if latent_neighbors is None: |
| 90 | + latent_distances = adata.obsp[latent_distance_key] |
| 91 | + if spatial_neighbors is None: |
| 92 | + spatial_distances = adata.obsp[spatial_distance_key] |
| 93 | + |
| 94 | + if latent_partition_kwargs is None: |
| 95 | + latent_partition_kwargs = dict() |
| 96 | + if spatial_partition_kwargs is None: |
| 97 | + spatial_partition_kwargs = dict() |
| 98 | + |
| 99 | + spatial_partition_kwargs["resolution"], latent_partition_kwargs["resolution"] = ( |
| 100 | + resolution |
| 101 | + ) |
| 102 | + |
| 103 | + cluster = leiden_multiplex( |
| 104 | + latent_distances, |
| 105 | + spatial_distances, |
| 106 | + directed=directed, |
| 107 | + use_weights=use_weights, |
| 108 | + n_iterations=n_iterations, |
| 109 | + partition_type=partition_type, |
| 110 | + layer_weights=layer_weights, |
| 111 | + spatial_partition_kwargs=spatial_partition_kwargs, |
| 112 | + latent_partition_kwargs=latent_partition_kwargs, |
| 113 | + seed=seed, |
| 114 | + ) |
| 115 | + |
| 116 | + adata.obs[key_added] = cluster |
| 117 | + adata.obs[key_added] = adata.obs[key_added].astype("category") |
0 commit comments