Skip to content

Commit 1794a3a

Browse files
committed
add usage example to docs
1 parent e07bc39 commit 1794a3a

File tree

4 files changed

+119
-1
lines changed

4 files changed

+119
-1
lines changed

docs/source/conf.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@
2727
"sphinx.ext.napoleon",
2828
"sphinx.ext.autosummary",
2929
"sphinx.ext.mathjax",
30+
"myst_nb",
3031
]
3132

3233

@@ -41,6 +42,8 @@
4142
nitpicky = True
4243
nitpick_ignore = [("py:class", "optional")]
4344

45+
# MyST-NB config
46+
nb_execution_timeout = 3 * 60
4447

4548
exclude_patterns: list[str] = []
4649

@@ -51,6 +54,7 @@
5154
python=("https://docs.python.org/3", None),
5255
scanpy=("https://scanpy.readthedocs.io/en/stable/", None),
5356
scipy=("https://docs.scipy.org/doc/scipy/", None),
57+
squidpy=("https://squidpy.readthedocs.io/en/stable/", None),
5458
)
5559

5660
# -- Options for HTML output -------------------------------------------------

docs/source/index.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ but can also be used independently.
1616

1717
self
1818
installation
19+
usage
1920
api
2021

2122

docs/source/usage.md

Lines changed: 113 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,113 @@
1+
---
2+
file_format: mystnb
3+
kernelspec:
4+
name: python
5+
jupytext:
6+
text_representation:
7+
extension: .md
8+
format_name: myst
9+
format_version: 0.13
10+
jupytext_version: 1.16.2
11+
---
12+
13+
# Usage
14+
15+
+++
16+
17+
To demonstrate the usage of the `spatialleiden` package we are going to use a MERFISH data set from [Moffit _et al._ 2018](https://doi.org/10.1126/science.aau5324) that can be downloaded from [figshare](https://figshare.com/articles/dataset/MERFISH_datasets/22565170) and then loaded as {py:class}`anndata.AnnData` object.
18+
19+
```{code-cell} ipython3
20+
---
21+
tags: [hide-cell]
22+
---
23+
24+
from tempfile import NamedTemporaryFile
25+
from urllib.request import urlretrieve
26+
27+
import anndata as ad
28+
29+
with NamedTemporaryFile(suffix=".h5ad") as h5ad_file:
30+
urlretrieve("https://figshare.com/ndownloader/files/40038538", h5ad_file.name)
31+
adata = ad.read_h5ad(h5ad_file)
32+
```
33+
34+
First of all we are going to load the relevant packages that we will be working with as well as setting a random seed that we will use throughout this example to make the results reproducible.
35+
36+
```{code-cell} ipython3
37+
import scanpy as sc
38+
import spatialleiden as sl
39+
import squidpy as sq
40+
41+
seed = 42
42+
```
43+
44+
The data set consists of 155 genes and ~5,500 cells including their annotation for cell type as well as domains.
45+
46+
+++
47+
48+
## SpatialLeiden
49+
50+
We will do some standard preprocessing by log-transforming the data and then using PCA for dimensionality reduction. The PCA will be used to build a kNN graph in the latent gene expression space. This graph is the basis for the Leiden clustering.
51+
52+
```{code-cell} ipython3
53+
sc.pp.log1p(adata)
54+
sc.pp.pca(adata, random_state=seed)
55+
56+
sc.pp.neighbors(adata, random_state=seed)
57+
```
58+
59+
For SpatialLeiden we need an additional graph representing the connectivities in the topological space. Here we will use a kNN graph with 10 neighbors that we generate with {py:func}`squidpy.gr.spatial_neighbors`. Alternatives are Delaunay triangulation or regular grids in case of e.g. Visium data.
60+
61+
We can use the calculated distances between neighboring points and transform them into connectivities using the {py:func}`spatialleiden.distance2connectivity` function.
62+
63+
```{code-cell} ipython3
64+
sq.gr.spatial_neighbors(adata, coord_type="generic", n_neighs=10)
65+
66+
adata.obsp["spatial_connectivities"] = sl.distance2connectivity(
67+
adata.obsp["spatial_distances"]
68+
)
69+
```
70+
71+
Now, we can already run {py:func}`spatialleiden.spatialleiden` (which we will also compare to normal Leiden clustering).
72+
73+
The `layer_ratio` determines the weighting between the gene expression and the topological layer and is influenced by the graph structures (i.e. how many connections exist, the edge weights, etc.); the lower the value is the closer SpatialLeiden will be to normal Leiden clustering, while higher values lead to more spatially homogeneous clusters.
74+
75+
The resolution has the same effect as in Leiden clustering (higher resolution will lead to more clusters) and can be defined for each of the layers (but for now is left at its default value).
76+
77+
```{code-cell} ipython3
78+
sc.tl.leiden(adata, directed=False, random_state=seed)
79+
80+
sl.spatialleiden(adata, layer_ratio=1.8, directed=(False, True), seed=seed)
81+
82+
sc.pl.embedding(adata, basis="spatial", color=["leiden", "spatialleiden"])
83+
```
84+
85+
We can see how Leiden clustering identifies cell types while SpatialLeiden defines domains of the tissue.
86+
87+
+++
88+
89+
## Resolution search
90+
91+
If you already know how many domains you expect in your sample you can use the {py:func}`spatialleiden.search_resolution` function to identify the resolutions needed to obtain the correct number of clusters.
92+
93+
Conceptually, this function first runs Leiden clustering multiple times while changing the resolution to identify the value leading to the desired number of clusters. Next, this procedure is repeated by running SpatialLeiden, but now the resolution of the latent layer (gene expression) is kept fixed and the resolution of the spatial layer is varied.
94+
95+
```{code-cell} ipython3
96+
n_clusters = adata.obs["domain"].nunique()
97+
98+
latent_resolution, spatial_resolution = sl.search_resolution(
99+
adata,
100+
n_clusters,
101+
latent_kwargs={"seed": seed},
102+
spatial_kwargs={"layer_ratio": 1.8, "seed": seed, "directed": (False, True)},
103+
)
104+
105+
print(f"Latent resolution: {latent_resolution:.3f}")
106+
print(f"Spatial resolution: {spatial_resolution:.3f}")
107+
```
108+
109+
In our case we can compare the resulting clusters to the annotated ground truth regions. If we are not satisfied with the results, we can go back and tweak other parameters such as the underlying neighborhood graphs or the `layer_ratio` to achieve the desired granularity of our results.
110+
111+
```{code-cell} ipython3
112+
sc.pl.embedding(adata, basis="spatial", color=["spatialleiden", "Region"])
113+
```

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ classifiers = [
3434
]
3535

3636
[project.optional-dependencies]
37-
docs = ["sphinx", "sphinx-copybutton", "sphinx-rtd-theme"]
37+
docs = ["sphinx", "sphinx-copybutton", "sphinx-rtd-theme", "squidpy", "myst-nb"]
3838
dev = ["spatialleiden[docs]", "pre-commit"]
3939

4040
[project.urls]

0 commit comments

Comments
 (0)