Skip to content

Commit

Permalink
Merge pull request #36 from CSOgroup/enrichment
Browse files Browse the repository at this point in the history
Update docs
  • Loading branch information
marcovarrone authored May 6, 2024
2 parents 396c415 + 70aae18 commit 15c1164
Show file tree
Hide file tree
Showing 14 changed files with 203 additions and 67 deletions.
2 changes: 2 additions & 0 deletions docs/graph.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
gr.aggregate_neighbors
gr.connected_components
gr.diff_nhood_enrichment
gr.enrichment
gr.nhood_enrichment
gr.remove_long_links
gr.remove_intra_cluster_links
Expand Down
111 changes: 54 additions & 57 deletions docs/notebooks/codex_mouse_spleen.ipynb

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions docs/plotting.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@
:toctree: generated
pl.autok_stability
pl.diff_nhood_enrichment
pl.enrichment
pl.nhood_enrichment
pl.proportion
pl.boundaries
pl.shape_metrics
```
5 changes: 5 additions & 0 deletions docs/tools.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@
.. autosummary::
:toctree: generated
tl.boundaries
tl.Cluster
tl.ClusterAutoK
tl.curl
tl.elongation
tl.linearity
tl.purity
```
4 changes: 2 additions & 2 deletions src/cellcharter/gr/_aggr.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from anndata import AnnData
from scipy.sparse import spdiags
from squidpy._constants._pkg_constants import Key as sqKey
from squidpy._docs import d
from tqdm.auto import tqdm

from cellcharter._constants._pkg_constants import Key
Expand Down Expand Up @@ -76,15 +77,13 @@ def _aggregate_neighbors(
aggregations: Optional[Union[str, list]] = "mean",
disable_tqdm: bool = True,
) -> np.ndarray:

adj = adj.astype(bool)
adj = _setdiag(adj, 0)
adj_hop = adj.copy()
adj_visited = _setdiag(adj.copy(), 1)

Xs = []
for i in tqdm(range(0, max(nhood_layers) + 1), disable=disable_tqdm):

if i in nhood_layers:
if i == 0:
Xs.append(X)
Expand All @@ -102,6 +101,7 @@ def _aggregate_neighbors(
return np.hstack(Xs)


@d.dedent
def aggregate_neighbors(
adata: AnnData,
n_layers: Union[int, list],
Expand Down
8 changes: 5 additions & 3 deletions src/cellcharter/gr/_build.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,12 @@
import scipy.sparse as sps
from anndata import AnnData
from scipy.sparse import csr_matrix
from squidpy._constants._constants import CoordType, Transform
from squidpy._constants._pkg_constants import Key
from squidpy._docs import inject_docs
from squidpy._docs import d
from squidpy.gr._utils import _assert_connectivity_key


@inject_docs(t=Transform, c=CoordType)
@d.dedent
def remove_long_links(
adata: AnnData,
distance_percentile: float = 99.0,
Expand Down Expand Up @@ -75,6 +74,7 @@ def remove_long_links(
adata.uns[neighs_key]["params"]["radius"] = threshold


@d.dedent
def remove_intra_cluster_links(
adata: AnnData,
cluster_key: str,
Expand Down Expand Up @@ -118,6 +118,7 @@ def remove_intra_cluster_links(
conns = adata.obsp[connectivity_key].copy() if copy else adata.obsp[connectivity_key]
dists = adata.obsp[distances_key].copy() if copy else adata.obsp[distances_key]

# ToDo: compute inter_cluster_mask only on conns and apply mask to both matrices
for matrix in [conns, dists]:
target_clusters = np.array(adata.obs[cluster_key][matrix.indices])
source_clusters = np.array(
Expand Down Expand Up @@ -146,6 +147,7 @@ def _connected_components(adj: sps.spmatrix, min_cells: int = 250, count: int =
return labels, (n_components - len(small_components))


@d.dedent
def connected_components(
adata: AnnData,
cluster_key: str = None,
Expand Down
6 changes: 4 additions & 2 deletions src/cellcharter/gr/_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import numpy as np
import pandas as pd
from anndata import AnnData
from squidpy._docs import d


def _proportion(adata, id_key, val_key, normalize=True):
Expand All @@ -24,6 +25,7 @@ def _enrichment(observed, expected, log=True):
return enrichment


@d.dedent
def enrichment(
adata: AnnData,
group_key: str,
Expand Down Expand Up @@ -56,8 +58,8 @@ def enrichment(
- ``'expected'`` - the expected proportions (if `observed_expected is True`).
Otherwise, modifies the ``adata`` with the following keys:
- :attr:`anndata.AnnData.uns` ``['{cluster_key}_nhood_enrichment']`` - the above mentioned dict.
- :attr:`anndata.AnnData.uns` ``['{cluster_key}_nhood_enrichment']['params']`` - the parameters used.
- :attr:`anndata.AnnData.uns` ``['{group_key}_{label_key}_nhood_enrichment']`` - the above mentioned dict.
- :attr:`anndata.AnnData.uns` ``['{group_key}_{label_key}_nhood_enrichment']['params']`` - the parameters used.
"""
observed = _proportion(adata, id_key=label_key, val_key=group_key).reindex().T
observed[observed.isna()] = 0
Expand Down
3 changes: 3 additions & 0 deletions src/cellcharter/gr/_nhood.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from anndata import AnnData
from joblib import Parallel, delayed
from squidpy._constants._pkg_constants import Key
from squidpy._docs import d
from squidpy.gr._utils import _assert_categorical_obs, _assert_connectivity_key
from tqdm.auto import tqdm

Expand Down Expand Up @@ -133,6 +134,7 @@ def _nhood_enrichment(
return result


@d.dedent
def nhood_enrichment(
adata: AnnData,
cluster_key: str,
Expand Down Expand Up @@ -236,6 +238,7 @@ def _diff_enrichment_permuted(
return result


@d.dedent
def diff_nhood_enrichment(
adata: AnnData,
cluster_key: str,
Expand Down
2 changes: 1 addition & 1 deletion src/cellcharter/pl/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from ._autok import autok_stability
from ._group import enrichment, proportion
from ._nhood import diff_nhood_enrichment, nhood_enrichment
from ._shape import plot_boundaries, plot_shape_metrics
from ._shape import boundaries, shape_metrics
3 changes: 3 additions & 0 deletions src/cellcharter/pl/_group.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import matplotlib.pyplot as plt
import numpy as np
from anndata import AnnData
from squidpy._docs import d
from squidpy.gr._utils import _assert_categorical_obs
from squidpy.pl._color_utils import Palette_t, _get_palette, _maybe_set_colors

Expand All @@ -18,6 +19,7 @@
from cellcharter.pl._utils import _dotplot


@d.dedent
def proportion(
adata: AnnData,
group_key: str,
Expand Down Expand Up @@ -90,6 +92,7 @@ def proportion(
plt.savefig(save, bbox_extra_artists=(lgd, lgd), bbox_inches="tight")


@d.dedent
def enrichment(
adata: AnnData,
group_key: str,
Expand Down
3 changes: 3 additions & 0 deletions src/cellcharter/pl/_nhood.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
from anndata import AnnData
from matplotlib import rcParams
from matplotlib.axes import Axes
from squidpy._docs import d
from squidpy.gr._utils import _assert_categorical_obs
from squidpy.pl._color_utils import Palette_t, _maybe_set_colors
from squidpy.pl._graph import _get_data
Expand Down Expand Up @@ -85,6 +86,7 @@ def _plot_nhood_enrichment(
)


@d.dedent
def nhood_enrichment(
adata: AnnData,
cluster_key: str,
Expand Down Expand Up @@ -168,6 +170,7 @@ def nhood_enrichment(
plt.savefig(save, bbox_inches="tight")


@d.dedent
def diff_nhood_enrichment(
adata: AnnData,
cluster_key: str,
Expand Down
109 changes: 109 additions & 0 deletions src/cellcharter/pl/_shape.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from __future__ import annotations

import warnings
from itertools import combinations
from pathlib import Path

Expand All @@ -13,6 +14,7 @@
from anndata import AnnData
from scipy.stats import ttest_ind
from spatialdata_plot.pl.utils import _get_colors_for_categorical_obs
from squidpy._docs import d

from ._utils import adjust_box_widths

Expand All @@ -29,6 +31,54 @@ def plot_boundaries(
"""
Plot the boundaries of the clusters.
Parameters
----------
%(adata)s
sample
Sample to plot.
library_key
Key in :attr:`anndata.AnnData.obs` where the sample labels are stored.
component_key
Key in :attr:`anndata.AnnData.obs` where the component labels are stored.
alpha_boundary
Transparency of the boundaries.
show_cells
Whether to show the cells or not.
Returns
-------
%(plotting_returns)s
"""
# Print warning and call boundaries
warnings.warn(
"plot_boundaries is deprecated and will be removed in the next release. " "Please use `boundaries` instead.",
FutureWarning,
stacklevel=2,
)
boundaries(
adata=adata,
sample=sample,
library_key=library_key,
component_key=component_key,
alpha_boundary=alpha_boundary,
show_cells=show_cells,
save=save,
)


@d.dedent
def boundaries(
adata: AnnData,
sample: str,
library_key: str = "sample",
component_key: str = "component",
alpha_boundary: float = 0.5,
show_cells: bool = True,
save: str | Path | None = None,
) -> None:
"""
Plot the boundaries of the clusters.
Parameters
----------
%(adata)s
Expand Down Expand Up @@ -132,6 +182,65 @@ def plot_shape_metrics(
"""
Boxplots of the shape metrics between two conditions.
Parameters
----------
%(adata)s
condition_key
Key in :attr:`anndata.AnnData.obs` where the condition labels are stored.
condition_groups
List of two conditions to compare. If None, all pairwise comparisons are made.
cluster_key
Key in :attr:`anndata.AnnData.obs` where the cluster labels are stored. This is used to filter the clusters to plot.
cluster_id
List of clusters to plot. If None, all clusters are plotted.
component_key
Key in :attr:`anndata.AnnData.obs` where the component labels are stored.
metrics
List of metrics to plot. Available metrics are ``linearity``, ``curl``, ``elongation``, ``purity``.
figsize
Figure size.
title
Title of the plot.
Returns
-------
%(plotting_returns)s
"""
# Print warning and call shape_metrics
warnings.warn(
"plot_shape_metrics is deprecated and will be removed in the next release. "
"Please use `shape_metrics` instead.",
FutureWarning,
stacklevel=2,
)
shape_metrics(
adata=adata,
condition_key=condition_key,
condition_groups=condition_groups,
cluster_key=cluster_key,
cluster_id=cluster_id,
component_key=component_key,
metrics=metrics,
figsize=figsize,
title=title,
)


@d.dedent
def shape_metrics(
adata: AnnData,
condition_key: str,
condition_groups: list[str] | None = None,
cluster_key: str | None = None,
cluster_id: list[str] | None = None,
component_key: str = "component",
metrics: str | tuple[str] | list[str] = ("linearity", "curl"),
figsize: tuple[float, float] = (8, 7),
title: str | None = None,
) -> None:
"""
Boxplots of the shape metrics between two conditions.
Parameters
----------
%(adata)s
Expand Down
6 changes: 6 additions & 0 deletions src/cellcharter/tl/_shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from shapely import geometry
from shapely.ops import polygonize, unary_union
from skimage.morphology import skeletonize
from squidpy._docs import d


def _alpha_shape(coords, alpha):
Expand Down Expand Up @@ -81,6 +82,7 @@ def _process_component(points, component, hole_area_ratio=0.1, alpha_start=2000)
return component, boundary


@d.dedent
def boundaries(
adata: AnnData,
cluster_key: str = "component",
Expand Down Expand Up @@ -232,6 +234,7 @@ def _rasterize(boundary, height=1000):
return features.rasterize([poly], out_shape=(height, int(height * (maxx - minx) / (maxy - miny)))), scale_factor


@d.dedent
def linearity(
adata: AnnData,
cluster_key: str = "component",
Expand Down Expand Up @@ -291,6 +294,7 @@ def _elongation(boundary):
return 1 - minor_axis / major_axis


@d.dedent
def elongation(
adata: AnnData,
cluster_key: str = "component",
Expand Down Expand Up @@ -349,6 +353,7 @@ def _curl(boundary):
return 1 - length / fibre_length


@d.dedent
def curl(
adata: AnnData,
cluster_key: str = "component",
Expand Down Expand Up @@ -384,6 +389,7 @@ def curl(
adata.uns[f"shape_{cluster_key}"][out_key] = curl_score


@d.dedent
def purity(
adata: AnnData,
cluster_key: str = "component",
Expand Down
Loading

0 comments on commit 15c1164

Please sign in to comment.