Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Build a neighbor graph stage by stage

Build the neighbor graph of 3,948 human peripheral blood mononuclear cells (PBMCs) from the 10x Genomics dataset “5k Peripheral blood mononuclear cells (PBMCs) from a healthy donor (v3 chemistry)” one stage at a time, check it, and branch it to compare 11 and 21 neighbors per cell. UMAP, clustering, imputation and trajectory methods all start from this graph. With the default 11 neighbors per cell, every cell has 11 to 53 edges, a number that barely depends on its RNA content, and Leiden clustering finds 12 clusters. The 15 pDC-like cells form a connected component of their own, with no edge to any other cell. With 21 neighbors per cell, the graph has nearly twice as many edges and forms a single component, and Leiden finds 11 clusters: the two NK-cell clusters merge and the boundary between two T-cell clusters moves, while the monocyte, B-cell, pDC-like and platelet clusters keep every cell.

ds.pipeline.rna() runs the same stages in one call, as the quick start shows, and continues through UMAP, clustering, doublet scoring and marker search. Calling the stages one by one lets you check each result before the next stage uses it, as this page does with the graph, and branch the analysis at the stage you choose.

Repeat the saved run’s graph stages

The prepared PBMC store, which the PBMC analysis also opens, holds a completed RNA pipeline run labeled rna. The run analyzed the 3,948 of the store’s 5,025 cells that passed quality control, with 15 principal components, 11 neighbors per cell and Leiden resolution 0.5. This page starts from the run’s cell and gene selections and repeats its graph stages with the same settings.

DataStore has 3948 (5025) cells with 1 assays: RNA Cell metadata: 'I', 'ids', 'names', 'RNA_G2M_score', 'RNA_S_score', 'RNA_UMAP1', 'RNA_UMAP2', 'RNA_cell_cycle_phase', 'RNA_clusters', 'RNA_doublet_score', 'RNA_leiden_cluster', 'RNA_nCounts', 'RNA_nFeatures', 'RNA_paris_cluster', 'RNA_percentMito', 'RNA_percentRibo' RNA assay has 33538 features and following metadata: 'I', 'ids', 'names', 'dropOuts', 'feature_type', 'genome', 'nCells'

Started: 2026-11-14T15:42:28.507841Z | Wall time: 8.813 s

Each stage of the run saved its result as an artifact, an immutable result stored with the operation, parameters and inputs that produced it. Indexing the run by an output name, one of the names that list(run) gives, returns an artifact reference, the handle that later calls take as input. The cell selection is the frozen set of cells that the run analyzed, and the feature selection holds its variable genes:

{'cells': ArtifactRef(datastore, kind='cell_selection', artifact_id='0cab0b95541d...'), 'genes': ArtifactRef(assay='RNA', kind='feature_selection', artifact_id='5373487c5d38...')}

Started: 2026-11-14T15:42:37.324125Z | Wall time: 0.131 s

Each stage takes the reference of the stage before and returns a reference to its own result. features.normalize scales each cell’s counts of the selected genes to a common total and log-transforms them. reduction.pca standardizes each gene and projects the cells onto principal components, 15 as in the saved run instead of the default 21:

ArtifactRef(assay='RNA', kind='reduction', artifact_id='fe36a97ebd24...')

Started: 2026-11-14T15:42:37.458834Z | Wall time: 0.201 s

Three stages turn the PCA coordinates into a graph. graph.ann_index builds a hierarchical navigable small world (HNSW) index, a layered search structure over the cells that finds approximate nearest neighbors without comparing every pair of cells. graph.neighbors queries the index for each cell’s k nearest cells, 11 by default. graph.connectivity turns each cell’s neighbor distances into edge weights between 0 and 1: the nearest neighbor gets weight 1, and the weight of a farther neighbor falls with its distance, on a scale set by the cell’s own neighbor distances, so that cells in dense and sparse regions get comparable weights:

True

Started: 2026-11-14T15:42:37.662541Z | Wall time: 0.259 s

The graph is the saved run’s own graph. Each call repeated a stage of the run with the same inputs and parameters, so CyteArc reused the run’s saved result instead of computing it again. A call with a changed input or parameter computes a new result, and the earlier one stays saved.

Check the graph before using it

graph.load returns the graph as a sparse cell-by-cell matrix. Each cell chose its 11 neighbors, but the cells that chose a cell are not always the ones it chose, so symmetric=True joins two cells when either chose the other and combines their directed weights a and b into a + b - ab. A cell’s degree, its number of edges in this matrix, is therefore at least 11, and the matrix stores each edge twice, once in each direction:

((3948, 3948), 64858)

Started: 2026-11-14T15:42:37.924534Z | Wall time: 0.087 s

Two panels for the symmetric 11-neighbor graph. Left, a bar chart of the number of cells at each node degree: degrees start at 11, with about 480 cells at each of 11, 12 and 13, and fall off steeply into a tail that reaches 53 edges beyond the clipped axis. Right, a histogram of edge weights from 0 to 1: most weights lie between 0.2 and 0.5 with a peak near 0.35, fewer run up to 0.95, and a spike of about 7,300 entries sits at weight 1.

Started: 2026-11-14T15:42:38.013922Z | Wall time: 0.534 s

The matrix has 3,948 rows, one per cell, and 64,858 nonzero entries. In the left panel, degree starts at 11 and falls off steeply, with a tail of cells that many other cells chose. In the right panel, most weights lie well below 1, and the spike at weight 1 holds each cell’s edge to its nearest neighbor.

Count the isolated cells, which have no edge and cannot join a cluster, and the connected components, groups of linked cells with no edge to any other group. Then check whether degree follows a cell’s RNA content:

cells 3948 isolated cells 0 connected components 2 cells in the largest component 3933 median degree 15.0 min degree 11 max degree 53 Name: k=11 graph, dtype: object

Started: 2026-11-14T15:42:38.550559Z | Wall time: 0.010 s

RNA_nCounts 0.08 RNA_nFeatures 0.02 Name: Pearson r with degree, dtype: float64

Started: 2026-11-14T15:42:38.562359Z | Wall time: 0.032 s

No cell is isolated, and the median cell has 15 edges. The graph has 2 connected components: one holds 3,933 cells, and the other 15 cells have no edge to it. Degree barely tracks RNA content, with a Pearson correlation of 0.08 with total counts and 0.02 with detected genes. A strong correlation can mean that cells with more counts sit in denser parts of the graph for technical rather than biological reasons, a cue to revisit the normalization, the variable genes or the number of principal components.

Use the graph for a layout and clustering

embeddings.umap lays the graph out in two dimensions, starting from coordinates that embeddings.initialization computes from the PCA. clusters.leiden partitions the graph with the Leiden algorithm Traag et al., 2019 into clusters of cells that connect more strongly to one another than to the rest. Resolution 0.5 matches the saved run; Leiden’s default is 1.0. Each call returns an artifact reference rather than a new cell column, and ds.artifacts.load_values reads the saved labels, one per analyzed cell:

UMAP of the 3,948 PBMCs colored by the 12 Leiden clusters of the 11-neighbor graph, with each cluster's number on its cells. T-cell clusters 1, 3, 4 and 8 and NK-cell clusters 5 and 9 form the large region on the left: cluster 1 at the top with cluster 8 at its left edge, clusters 4 and 3 below it, cluster 5 at the bottom and cluster 9 a small satellite at the lower left. Monocyte cluster 2 forms the group on the right, with cluster 10 at its right tip, and B-cell clusters 6 and 7 a group at the top. The 15 pDC-like cells of cluster 11 and the 12 platelets of cluster 12 form two small islands to the right of the B cells.

Started: 2026-11-14T15:42:38.596106Z | Wall time: 0.526 s

cluster 11 15 Name: count, dtype: int64

Started: 2026-11-14T15:42:39.124714Z | Wall time: 0.007 s

The PBMC analysis names these clusters from marker genes: 1, 3, 4 and 8 are T cells, 5 and 9 are NK cells and 6 and 7 are B cells, while cluster 2 holds CD14 monocytes, cluster 10 CD16 monocytes, cluster 11 pDC-like cells and cluster 12 platelets. In the UMAP, the T and NK cells form the large region on the left, the monocytes a group on the right, and the B cells a group at the top. The 15 cells outside the graph’s largest component are all in cluster 11, the pDC-like cells: none of them chose a neighbor outside the group, and no other cell chose one of them. trajectory.pseudotime scores only the largest component by default, so on this graph these 15 cells would get no pseudotime. The 12 platelets also sit apart in the UMAP, but edges join them to the rest of the graph.

Branch the graph to 21 neighbors

A branch reruns one stage with another setting, along with the stages after it, and keeps both results. To compare two neighbor counts, query the same index with another k: the normalization, PCA and index are reused, and only the neighbor and connectivity stages compute new results:

True

Started: 2026-11-14T15:42:39.133955Z | Wall time: 25.885 s

The 21-neighbor graph is a new artifact beside the 11-neighbor graph, and each later call works on the reference it receives. Compare the two graphs:

nonzero entriesconnected componentsmedian degreemax degreemedian edge weight
k=1164858215.0530.456
k=21121876128.0930.272

Started: 2026-11-14T15:43:05.021323Z | Wall time: 0.104 s

The same two panels for the symmetric 21-neighbor graph. Left, node degrees start at 21, peak at 23 with about 300 cells, and tail off to a maximum of 93 beyond the clipped axis. Right, most edge weights lie between 0.1 and 0.3 with a peak near 0.18, lower than in the 11-neighbor graph, and the spike at weight 1 keeps about 7,200 entries.

Started: 2026-11-14T15:43:05.128384Z | Wall time: 0.356 s

With 21 neighbors per cell, the matrix holds 121,876 nonzero entries, nearly twice the 64,858 of the 11-neighbor graph, and the median degree rises from 15 to 28. The median edge weight falls from 0.456 to 0.272. Each cell’s weights are scaled to a total that grows only with the logarithm of k, so 21 edges share a total only slightly larger than 11 edges did. The spike at weight 1 stays about the same height, since each cell still has one nearest neighbor.

The 21-neighbor graph forms a single connected component: a group of 15 cells cannot supply 21 neighbors to each of its cells, so every pDC-like cell now links to cells outside its group.

Cluster the 21-neighbor graph at the same resolution by passing its reference:

k=11 12 k=21 11 Name: Leiden clusters, dtype: int64

Started: 2026-11-14T15:43:05.486552Z | Wall time: 38.132 s

The 21-neighbor graph gives 11 clusters instead of 12. Leiden numbers each clustering’s clusters by decreasing size, so the same number can name different cells in the two clusterings. As on the dimensionality reduction page, clusters.relabel_by_overlap names each 21-neighbor cluster after its main source, the 11-neighbor cluster that holds most of its cells, with a letter that tells apart clusters of the same source. An 11-neighbor cluster that is the main source of no 21-neighbor cluster is added after a hyphen to the name of the cluster that holds most of its cells, as in 5-9a. Draw both clusterings on the 11-neighbor UMAP, then count the cells that each pair of clusters shares:

Two UMAPs of the 3,948 PBMCs in the 11-neighbor layout, with each cluster's name on its cells. Left, the 12 Leiden clusters of the 11-neighbor graph. Right, the 11 Leiden clusters of the 21-neighbor graph, each named after the 11-neighbor cluster that holds most of its cells. NK-cell clusters 5 and 9 merge into one green cluster, 5-9a, that covers cluster 5 at the bottom and the small satellite of cluster 9. The light orange cluster 4a covers cluster 4 and the upper part of cluster 3, leaving the lower part of cluster 3 to the orange cluster 3a. Cluster 1a also takes cells along its borders with clusters 4 and 8, and the monocyte, B-cell, pDC-like and platelet clusters 2a, 6a, 7a, 10a, 11a and 12a cover the same cells as clusters 2, 6, 7, 10, 11 and 12.

Started: 2026-11-14T15:43:43.621480Z | Wall time: 0.607 s

k=211a2a3a4a5-9a6a7a8a10a11a12atotal
k=11
1121521217
2704704
32842368528
460414474
5283283
6256256
7239239
824142166
92929
102525
111515
121212
total12997042846503202562391442515123948

Started: 2026-11-14T15:43:44.230517Z | Wall time: 0.054 s

The clusterings differ only among the T and NK cells. NK-cell clusters 5 and 9 merge into cluster 5-9a of 320 cells, which also takes 8 cells of T-cell cluster 3. The PBMC analysis finds cluster 3 expressing NKG7, part of a cytotoxic program that T cells share with NK cells. The boundary between T-cell clusters 3 and 4 moves into cluster 3: cluster 4a takes 414 cells of cluster 4 and 236 of cluster 3, and cluster 3a keeps the other 284 cells of cluster 3. Cluster 1a holds 1,215 of the 1,217 cells of cluster 1, plus 60 cells of cluster 4 and 24 of cluster 8. The monocyte, B-cell, pDC-like and platelet clusters 2, 6, 7, 10, 11 and 12 keep every cell.

With 21 neighbors, the boundaries move only inside the continuous region of T and NK cells, while the separate populations stay intact. A boundary inside such a region depends on the neighbor count, so check it with marker genes before naming the cells on either side.

HNSW search is approximate: a query examines a list of candidate cells, whose length is the query depth, rather than every cell. By default the depth is max(ann_ef, 2 * k), where ann_ef=200 is recorded with the index, and graph.neighbors(ann_ef=...) sets the depth of one query without rebuilding the index. Two settings of graph.ann_index change the index itself, so changing either builds a new one: ann_m=24, the links per cell, which cost memory, and ann_efc=200, the candidate list while cells are added, which costs build time. Each query saves its self-hit rate, selfHitRate: the percentage of cells that find themselves among the k + 1 cells their query returns, before each cell’s edge to itself is dropped. Compare a shallow query depth of 40 with the default 200, for the same 11 neighbors per cell:

search depthself-hit percentneighbors shared with default, %cells with a different neighbor
shallow40100.099.9933
default200100.0100.0000

Started: 2026-11-14T15:43:44.286749Z | Wall time: 0.313 s

A depth of 40 returns 99.993% of the default search’s neighbors: 3 of the 3,948 cells get a different neighbor. Both searches have a self-hit rate of 100%, so the rate cannot reveal differences this small. A query that misses a cell when it searches from that cell’s own coordinates likely misses true neighbors of other cells too, so a rate below 99.5% gives a warning each time the query is computed or reused; raise ann_ef, or rebuild the index with a larger ann_efc or ann_m. Cells with identical coordinates also lower the rate. ds.artifacts.inspect(ref).diagnostics returns the rate of any neighbor query, and neighbor search reports how often the defaults find the exact neighbors in million-cell atlases.

Add batch correction to the chain

reduction.harmony corrects the PCA coordinates for the batches named in a cell column, and the corrected coordinates need their own index, neighbors and graph, while the normalization and PCA are reused. Name only technical batches, since correcting for a biological condition removes the differences under study; batch correction compares an analysis with and without Harmony. With a cell column technical_batch that names each cell’s batch, the chain reads:

# Correct the PCA for batch, then build the graph on the corrected coordinates.
corrected = ds.reduction.harmony(pca, ["technical_batch"])
corrected_index = ds.graph.ann_index(corrected)
corrected_neighbors = ds.graph.neighbors(corrected_index)
corrected_graph = ds.graph.connectivity(corrected_neighbors)

The clustering page compares Leiden resolutions and Paris on the 11-neighbor graph, and analysis reuse branches a Tabula Sapiens analysis the same way and traces which results the branches share.

References
  1. Traag, V. A., Waltman, L., & van Eck, N. J. (2019). From Louvain to Leiden: guaranteeing well-connected communities. Scientific Reports, 9(1). 10.1038/s41598-019-41695-z