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.
# Tabulate graph statistics and draw the comparison figures.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy.sparse.csgraph import connected_components
import cytearc
import cytearc.plotting as splt
# Keep routine logs and progress bars out of the page.
cytearc.configure_output(level="WARNING", progress=False)
# Download the prepared PBMC store, which holds a saved RNA run.
dataset = cytearc.datasets.connect("cytearc_docs").download_dataset(
"tenx_5K_pbmc_rnaseq",
destination="cytearc_datasets",
zarr=True,
)
# Open the store and its saved run.
ds = cytearc.DataStore(f"{dataset}/data.zarr", nthreads=4)
run = ds.pipeline.open(label="rna")
dsDataStore 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:
# Start from the cells and the variable genes that the saved run analyzed.
cell_selection = run["analysis_cell_selection"]
hvg_ref = run["highly_variable_features"]
# Keep the QC measures of the analyzed cells, in the order that the graph's rows follow.
run_cells = run.cells
{"cells": cell_selection, "genes": hvg_ref}{'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:
# Repeat the saved run's normalization and its 15-component PCA.
normalized = ds.features.normalize(cell_selection, hvg_ref)
pca = ds.reduction.pca(normalized, dims=15)
pcaArtifactRef(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:
# Index the PCA coordinates, find each cell's 11 nearest neighbors, and weight the edges.
ann_index = ds.graph.ann_index(pca)
neighbors = ds.graph.neighbors(ann_index)
graph = ds.graph.connectivity(neighbors)
# Check that these calls returned the saved run's graph instead of computing a new one.
graph == run["connectivity_map"]TrueStarted: 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:
# Load the graph as a symmetric sparse matrix for the checks below.
loaded_graph = ds.graph.load(graph, symmetric=True)
loaded_graph.shape, loaded_graph.nnz((3948, 3948), 64858)Started: 2026-11-14T15:42:37.924534Z | Wall time: 0.087 s
# Plot the distributions of node degree and edge weight.
splt.graph_qc(loaded_graph)
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:
# Count each cell's edges, its degree, and find the connected components of the graph.
degrees = np.asarray((loaded_graph != 0).sum(axis=0)).ravel()
n_components, component = connected_components(loaded_graph, directed=False)
# Summarize how many cells the graph connects, and how evenly.
pd.Series(
{
"cells": loaded_graph.shape[0],
"isolated cells": int((degrees == 0).sum()),
"connected components": n_components,
"cells in the largest component": int(np.bincount(component).max()),
"median degree": float(np.median(degrees)),
"min degree": int(degrees.min()),
"max degree": int(degrees.max()),
},
name="k=11 graph",
dtype=object,
)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: objectStarted: 2026-11-14T15:42:38.550559Z | Wall time: 0.010 s
# Correlate each cell's degree with its total counts and detected genes.
pd.DataFrame(
{
"degree": degrees,
"RNA_nCounts": run_cells.fetch("RNA_nCounts"),
"RNA_nFeatures": run_cells.fetch("RNA_nFeatures"),
}
).corr()["degree"].drop("degree").rename("Pearson r with degree").round(2)RNA_nCounts 0.08
RNA_nFeatures 0.02
Name: Pearson r with degree, dtype: float64Started: 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:
# Compute UMAP starting coordinates from the PCA, then lay out the graph.
initialization = ds.embeddings.initialization(pca)
umap = ds.embeddings.umap(graph, initialization)
# Cluster the graph at the saved run's Leiden resolution, and read the labels.
clusters = ds.clusters.leiden(graph, resolution=0.5)
cluster_values = ds.artifacts.load_values(clusters, cell_ids=False).values
# Color the UMAP by cluster, with each cluster's number on its cells.
ds.plots.embedding(
layout=umap,
color_by=splt.NamedCellArtifact("Leiden clusters, 11 neighbors", clusters),
legend_loc="on_data",
figsize=(5, 4.5),
)
Started: 2026-11-14T15:42:38.596106Z | Wall time: 0.526 s
# Find the clusters of the cells outside the graph's largest component.
largest_component = np.bincount(component).argmax()
pd.Series(cluster_values[component != largest_component], name="cluster").value_counts()cluster
11 15
Name: count, dtype: int64Started: 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:
# Query the same index for 21 neighbors per cell, and weight the new edges.
neighbors_k21 = ds.graph.neighbors(ann_index, k=21)
graph_k21 = ds.graph.connectivity(neighbors_k21)
# Check that the 21-neighbor graph is a separate artifact.
graph_k21 != graphTrueStarted: 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:
# Load the 21-neighbor graph the same way, and count each cell's edges.
loaded_graph_k21 = ds.graph.load(graph_k21, symmetric=True)
degrees_k21 = np.asarray((loaded_graph_k21 != 0).sum(axis=0)).ravel()
# Compare the two graphs' entries, node degrees and edge weights.
pd.DataFrame(
[
{
"nonzero entries": matrix.nnz,
"connected components": connected_components(matrix, directed=False)[0],
"median degree": np.median(cell_degrees),
"max degree": cell_degrees.max(),
"median edge weight": np.median(matrix.data),
}
for matrix, cell_degrees in (
(loaded_graph, degrees),
(loaded_graph_k21, degrees_k21),
)
],
index=["k=11", "k=21"],
).round(3)| nonzero entries | connected components | median degree | max degree | median edge weight | |
|---|---|---|---|---|---|
| k=11 | 64858 | 2 | 15.0 | 53 | 0.456 |
| k=21 | 121876 | 1 | 28.0 | 93 | 0.272 |
Started: 2026-11-14T15:43:05.021323Z | Wall time: 0.104 s
# Plot the 21-neighbor graph's degree and edge-weight distributions.
splt.graph_qc(loaded_graph_k21)
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:
# Cluster the 21-neighbor graph at the same resolution, and read its labels.
clusters_k21 = ds.clusters.leiden(graph_k21, resolution=0.5)
cluster_values_k21 = ds.artifacts.load_values(clusters_k21, cell_ids=False).values
# Count the clusters that each graph gives.
pd.Series(
{
"k=11": len(np.unique(cluster_values)),
"k=21": len(np.unique(cluster_values_k21)),
},
name="Leiden clusters",
)k=11 12
k=21 11
Name: Leiden clusters, dtype: int64Started: 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:
# Name each 21-neighbor cluster after the 11-neighbor cluster that holds most of its cells.
matched_k21 = ds.clusters.relabel_by_overlap(clusters_k21, clusters)
# Draw both clusterings on the 11-neighbor UMAP, with each cluster's name on its cells.
figure, axes = plt.subplots(1, 2, figsize=(10, 4.5))
for axis, cluster_ref, title in zip(
axes,
(clusters, matched_k21),
("Leiden clusters, 11 neighbors", "Leiden clusters, 21 neighbors"),
strict=True,
):
ds.plots.embedding(
layout=umap,
color_by=cluster_ref,
legend_loc="on_data",
target=axis,
show_titles=False,
show=False,
)
axis.set_title(title)
figure.tight_layout()
plt.show()
Started: 2026-11-14T15:43:43.621480Z | Wall time: 0.607 s
# Count the cells that each pair of clusters shares, with cluster sizes as totals.
matched_values = ds.artifacts.load_values(matched_k21, cell_ids=False).values
overlap = pd.crosstab(
pd.Series(cluster_values, name="k=11"),
pd.Series(matched_values, name="k=21"),
margins=True,
margins_name="total",
)
# Order the 21-neighbor clusters by their main source, and leave empty pairs blank.
main_sources = overlap.drop(index="total", columns="total").idxmax()
overlap[[*main_sources.sort_values(kind="stable").index, "total"]].replace(0, "")| k=21 | 1a | 2a | 3a | 4a | 5-9a | 6a | 7a | 8a | 10a | 11a | 12a | total |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| k=11 | ||||||||||||
| 1 | 1215 | 2 | 1217 | |||||||||
| 2 | 704 | 704 | ||||||||||
| 3 | 284 | 236 | 8 | 528 | ||||||||
| 4 | 60 | 414 | 474 | |||||||||
| 5 | 283 | 283 | ||||||||||
| 6 | 256 | 256 | ||||||||||
| 7 | 239 | 239 | ||||||||||
| 8 | 24 | 142 | 166 | |||||||||
| 9 | 29 | 29 | ||||||||||
| 10 | 25 | 25 | ||||||||||
| 11 | 15 | 15 | ||||||||||
| 12 | 12 | 12 | ||||||||||
| total | 1299 | 704 | 284 | 650 | 320 | 256 | 239 | 144 | 25 | 15 | 12 | 3948 |
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.
Tune the neighbor search¶
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:
# Query the same index for 11 neighbors, searching 40 candidates instead of 200.
shallow_neighbors = ds.graph.neighbors(ann_index, k=11, ann_ef=40)
# Count how many of each cell's default neighbors the shallower search also returns.
default_indices = np.asarray(ds.artifacts.load(neighbors)["indices"][:])
shallow_indices = np.asarray(ds.artifacts.load(shallow_neighbors)["indices"][:])
shared = np.array(
[
np.isin(shallow_row, default_row).sum()
for shallow_row, default_row in zip(
shallow_indices, default_indices, strict=True
)
]
)
# Compare the two searches' self-hit rates and neighbors.
pd.DataFrame(
{
"search depth": [40, 200],
"self-hit percent": [
ds.artifacts.inspect(ref).diagnostics["selfHitRate"]
for ref in (shallow_neighbors, neighbors)
],
"neighbors shared with default, %": [
round(100 * shared.sum() / default_indices.size, 3),
100.0,
],
"cells with a different neighbor": [
int((shared < default_indices.shape[1]).sum()),
0,
],
},
index=["shallow", "default"],
)| search depth | self-hit percent | neighbors shared with default, % | cells with a different neighbor | |
|---|---|---|---|---|
| shallow | 40 | 100.0 | 99.993 | 3 |
| default | 200 | 100.0 | 100.000 | 0 |
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.
- 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