Smooth the sparse RNA signal of one gene over the neighbor graph of a saved analysis, and check whether the smoothed signal stays in the populations that express the gene. The data are the 3,948 human peripheral blood mononuclear cells (PBMCs) that pass quality control in the 10x Genomics 5k PBMC dataset from a healthy donor (tenx_5K_pbmc_rnaseq), and the saved RNA analysis whose clusters the PBMC analysis names. The gene is CD4, which CD4 T cells and monocytes express and CD8 T cells lack. A zero count can mean that a cell does not express a gene or that its transcripts were not captured, and only 36% of the 3,948 cells have a CD4 count, fewer than half of the cells in each T-cell cluster.
Graph diffusion, the smoothing step of MAGIC Dijk et al., 2018, replaces each cell’s value with a weighted average over its neighbors in the graph. Two diffusion steps give 97% of the cells a CD4 value above zero and leave the mean of every cluster almost unchanged. The smoothed map shows CD4 highest in the CD14 monocytes, at a lower, even level in the T cells without CD8 transcripts, low in the T cells with CD8 transcripts, and near zero in the B cells and NK cells. Where a cluster mixes CD8 T cells with other T cells, smoothing roughly triples the low CD4 of the CD8 T cells with signal from the cells beside them, an exchange that the cluster mean hides. One and three steps change how smooth the map is and barely move the cluster means.
Open the saved analysis and its graph¶
import pandas as pd
import cytearc
from cytearc.plotting import CellField, ColorScale, FeatureRef
# Keep routine logs and progress bars out of the page.
cytearc.configure_output(level="WARNING", progress=False)
# Download the prepared PBMC store, which holds the counts and a saved RNA analysis.
dataset = cytearc.datasets.connect("cytearc_docs").download_dataset(
"tenx_5K_pbmc_rnaseq",
destination="cytearc_datasets",
zarr=True,
)
# Open the store, its saved RNA run, and the neighbor graph that the run built.
ds = cytearc.DataStore(f"{dataset}/data.zarr")
run = ds.pipeline.open(label="rna")
graph = run["connectivity_map"]
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-18T00:16:01.627555Z | Wall time: 9.928 s
ds holds 5,025 cells, and plots and analyses use the 3,948 that the saved analysis kept. ds.pipeline.open(label="rna") reopens that analysis as a pipeline run, and run["connectivity_map"] is an ArtifactRef to the weighted neighbor graph that the run built, which links each cell to the cells with the most similar expression profiles. The run computed its UMAP and its Leiden clusters from the same graph.
Locate the cell populations¶
Number the run’s clusters on its UMAP, so that the CD4 maps below can be read by population:
# Print each cluster's number on its cells instead of in a legend.
ds.plots.embedding(
run=run,
color_by=CellField("clusters", label="Leiden cluster"),
legend_loc="on_data",
)
Started: 2026-11-18T00:16:11.561756Z | Wall time: 1.793 s
The PBMC analysis names the clusters from marker genes: T cells in clusters 1, 3, 4, and 8 on the left, NK cells in clusters 5 and 9 at the lower end of that region, B cells in clusters 6 and 7 at the top, and CD14 monocytes in cluster 2 on the right. The CD16 monocytes of cluster 10 form the upper tip of cluster 2, and pDC-like cells and platelets form the small clusters 11 and 12 above cluster 2. The cell type annotation tutorial finds CD8 transcripts in most cells of cluster 8 and in the lower part of cluster 3, and almost none in clusters 1 and 4.
Smooth CD4 with two diffusion steps¶
ds.imputation.diffusion turns the graph into a diffusion operator of t steps, two by default. One step replaces each cell’s value with the average of its neighbors’ values, weighted by the graph’s edge weights, and t steps repeat that average, so that signal reaches cells up to t edges away. The operator is saved in the store, and a repeated call with the same graph and t reuses it. ds.imputation.compute_imputed applies the operator to one gene’s normalized expression, its counts per 1,000 counts in each cell, and returns one value per analyzed cell. key="I" in ds.cells.insert places those values on the rows of the 3,948 analyzed cells for plotting, and ds.get_cell_vals reads the observed values in the same units:
# Build the diffusion operator with the default two steps.
diffusion = ds.imputation.diffusion(graph)
# Smooth normalized CD4 over the graph, and save the values of the active cells as a cell column, keyed by cell ID.
smoothed = ds.imputation.compute_imputed(feature_name="CD4", diffusion=diffusion)
analyzed_ids = ds.cells.fetch("ids", key="I")
ds.cells.insert(
"CD4_smoothed_t2", pd.Series(smoothed, index=analyzed_ids), key="I", overwrite=True
)
# Collect observed and smoothed CD4 for the analyzed cells, in the store's cell order.
cd4 = pd.DataFrame(
{"observed": ds.get_cell_vals(from_assay="RNA", cell_key="I", k="CD4"), "t=2": smoothed}
)
# Summarize each column of CD4 values: the fraction of cells above 0, the mean, and the maximum.
def summarize(values):
summary = pd.DataFrame(
{"fraction above 0": values.gt(0).mean(), "mean": values.mean(), "maximum": values.max()}
)
return summary.rename_axis(f"CD4 per {ds.RNA.sf:,} counts").round(3)
summarize(cd4)| fraction above 0 | mean | maximum | |
|---|---|---|---|
| CD4 per 1,000 counts | |||
| observed | 0.359 | 0.07 | 0.816 |
| t=2 | 0.966 | 0.07 | 0.303 |
Started: 2026-11-18T00:16:13.359323Z | Wall time: 1.929 s
Observed CD4 is above zero in 35.9% of the cells, the cells with at least one CD4 count. After two steps, 96.6% of the cells have a value above zero and the mean stays at 0.07. A smoothed value above zero means that some cell within two edges has a CD4 count, not necessarily the cell itself.
A plot with run=run colors cells only by the run’s own cell fields, such as clusters, so the plots below take the UMAP coordinates from the run with layout=run["umap"] and color the cells by the gene and by the new smoothed columns. Draw the observed and smoothed values on that UMAP, each panel on its own color scale, because smoothing lowers the maximum from 0.816 to 0.303:
# Draw observed and smoothed CD4, each on its own color scale, with the highest values on top.
ds.plots.embedding(
layout=run["umap"],
color_by=[
FeatureRef("CD4", label="Observed CD4"),
CellField("CD4_smoothed_t2", kind="continuous", label="Smoothed CD4, t=2"),
],
n_columns=2,
sort_values=True,
)
Started: 2026-11-18T00:16:15.292407Z | Wall time: 0.687 s
Observed CD4 is speckled: in the T-cell region on the left and in the monocytes on the right, cells with CD4 counts sit among cells without. The smoothed map replaces the speckles with regional levels. On its own scale, from 0 to 0.3, smoothed CD4 is brightest in the CD14 monocytes of cluster 2, most of all at their upper end next to cluster 10, where the observed panel also has more of its brightest cells. T-cell clusters 1 and 4 are an even blue. Cluster 3 splits in two: its upper part, next to cluster 4, is as blue as clusters 1 and 4, and its lower part, which holds the CD8 transcripts, is as dark as cluster 8 at the left edge, the B cells at the top, and the NK cells at the bottom.
Compare one, two, and three steps¶
Smooth CD4 with one and with three steps, and summarize the three results beside the observed values:
# Smooth CD4 with one and with three steps, and save each result as a cell column.
for t in (1, 3):
operator = ds.imputation.diffusion(graph, t=t)
values = ds.imputation.compute_imputed(feature_name="CD4", diffusion=operator)
ds.cells.insert(
f"CD4_smoothed_t{t}", pd.Series(values, index=analyzed_ids), key="I", overwrite=True
)
cd4[f"t={t}"] = values
# Summarize the observed values beside the results of one, two, and three steps.
cd4 = cd4[["observed", "t=1", "t=2", "t=3"]]
summarize(cd4)| fraction above 0 | mean | maximum | |
|---|---|---|---|
| CD4 per 1,000 counts | |||
| observed | 0.359 | 0.07 | 0.816 |
| t=1 | 0.766 | 0.07 | 0.370 |
| t=2 | 0.966 | 0.07 | 0.303 |
| t=3 | 0.998 | 0.07 | 0.277 |
Started: 2026-11-18T00:16:15.983514Z | Wall time: 1.695 s
Each step gives more cells a value above zero: 76.6% after one step and 99.8% after three, which includes nearly all B cells and NK cells although they have almost no CD4 counts. Only the level of a smoothed value then separates the populations. The maximum falls from 0.370 after one step to 0.277 after three. Draw the three results on one shared color scale, so that their colors compare directly:
# Draw the three results on one shared color scale, with the highest values on top.
ds.plots.embedding(
layout=run["umap"],
color_by=[
CellField(f"CD4_smoothed_t{t}", kind="continuous", label=f"Smoothed CD4, t={t}")
for t in (1, 2, 3)
],
n_columns=3,
color_scale=ColorScale(scope="shared"),
sort_values=True,
)
Started: 2026-11-18T00:16:17.681668Z | Wall time: 0.709 s
After one step the map is still speckled: single monocytes in cluster 2 reach the top of the scale, and the T-cell region is mottled. Two steps remove most of the speckle, and a third changes little more: it raises the cells above zero from 96.6% to 99.8% and dims the brightest monocytes. After two and after three steps, cluster 2 keeps its gradient from green at its upper end next to cluster 10 to blue at its lower end, and T-cell clusters 1 and 4 are an even dark blue. The default of two steps already shows the regional pattern.
Check whether smoothing moves CD4 between populations¶
Wherever the graph links two populations, diffusion mixes their values. Average CD4 within each cluster, observed and after one, two, and three steps, beside the fraction of the cluster’s cells with at least one CD4 count:
# Name each cluster with its broad cell type from the PBMC analysis.
cell_types = {
"1": "T cells",
"2": "CD14 monocytes",
"3": "T cells",
"4": "T cells",
"5": "NK cells",
"6": "B cells",
"7": "B cells",
"8": "T cells",
"9": "NK cells",
"10": "CD16 monocytes",
"11": "pDC-like cells",
"12": "platelets",
}
# Compare each cluster's mean CD4 before and after smoothing, with its size and CD4 detection.
clusters = pd.Series(run.cells.fetch("clusters").astype(str), name="cluster")
by_cluster = cd4.groupby(clusters)
table = by_cluster.mean().add_prefix("mean ")
table.insert(0, "fraction detected", cd4["observed"].gt(0).groupby(clusters).mean().round(2))
table.insert(0, "cells", by_cluster.size())
table.insert(0, "cell type", pd.Series(cell_types))
table.reindex(list(cell_types)).round(3)| cell type | cells | fraction detected | mean observed | mean t=1 | mean t=2 | mean t=3 | |
|---|---|---|---|---|---|---|---|
| cluster | |||||||
| 1 | T cells | 1217 | 0.39 | 0.067 | 0.067 | 0.067 | 0.067 |
| 2 | CD14 monocytes | 704 | 0.76 | 0.181 | 0.180 | 0.179 | 0.179 |
| 3 | T cells | 528 | 0.23 | 0.038 | 0.037 | 0.037 | 0.038 |
| 4 | T cells | 474 | 0.49 | 0.083 | 0.085 | 0.085 | 0.084 |
| 5 | NK cells | 283 | 0.02 | 0.002 | 0.002 | 0.002 | 0.002 |
| 6 | B cells | 256 | 0.03 | 0.003 | 0.002 | 0.002 | 0.002 |
| 7 | B cells | 239 | 0.01 | 0.001 | 0.001 | 0.001 | 0.001 |
| 8 | T cells | 166 | 0.05 | 0.014 | 0.014 | 0.015 | 0.016 |
| 9 | NK cells | 29 | 0.03 | 0.008 | 0.008 | 0.007 | 0.007 |
| 10 | CD16 monocytes | 25 | 0.80 | 0.119 | 0.113 | 0.120 | 0.124 |
| 11 | pDC-like cells | 15 | 0.40 | 0.043 | 0.042 | 0.043 | 0.043 |
| 12 | platelets | 12 | 0.00 | 0.000 | 0.001 | 0.001 | 0.002 |
Started: 2026-11-18T00:16:18.393874Z | Wall time: 0.034 s
CD4 counts are most frequent in the monocytes, in 76% of cluster 2 and 80% of the 25 cells of cluster 10, followed by T-cell clusters 1 and 4 (39% and 49%) and the 15 pDC-like cells (40%). They are rarer in clusters 3 and 8, the clusters with CD8 transcripts (23% and 5%), and reach at most 3% in the B cells, NK cells, and platelets. The CD14 monocytes average 0.181 CD4 counts per 1,000 counts, more than twice clusters 1 and 4 (0.067 and 0.083), so in these PBMCs CD4 RNA is higher in monocytes than in any T-cell cluster, as the cell type annotation tutorial also finds.
Smoothing leaves the mean of each large cluster nearly where it was: cluster 1 stays at 0.067 in every column, the CD14 monocytes go from 0.181 to 0.179, and the B-cell and NK-cell clusters stay at 0.008 or less. Leiden drew the clusters from the same graph, as groups of cells with many edges among them and few to other groups, so a few steps keep almost all of a large cluster’s CD4 inside it. The smaller clusters show signal crossing between populations. The 12 platelets, none of which has a CD4 count, reach 0.002 after three steps, cluster 8 rises from 0.014 to 0.016, and the 25 cells of cluster 10 rise from 0.113 after one step to 0.124 after three, toward the 0.179 of the CD14 monocytes beside them.
Cluster 3 mixes CD8 T cells with other T cells, so its steady mean can hide an exchange between them. Compare the cluster’s cells with and without a CD8A count:
# Split the cells of cluster 3 by whether they have a CD8A count, which marks CD8 T cells.
cd8a = pd.Series(ds.get_cell_vals(from_assay="RNA", cell_key="I", k="CD8A"))
in_cluster_3 = clusters.eq("3")
has_cd8a = cd8a[in_cluster_3].gt(0).map({True: "yes", False: "no"}).rename("CD8A count")
# Compare the two groups' mean CD4, observed and after one, two, and three steps.
by_cd8a = cd4[in_cluster_3].groupby(has_cd8a)
split = by_cd8a.mean().add_prefix("mean ")
split.insert(0, "cells", by_cd8a.size())
split.round(3)| cells | mean observed | mean t=1 | mean t=2 | mean t=3 | |
|---|---|---|---|---|---|
| CD8A count | |||||
| no | 292 | 0.065 | 0.059 | 0.058 | 0.057 |
| yes | 236 | 0.004 | 0.010 | 0.012 | 0.013 |
Started: 2026-11-18T00:16:18.430290Z | Wall time: 0.253 s
The 236 cells with a CD8A count have little CD4: their mean is 0.004, against 0.065 for the other 292 cells. Smoothing raises their mean to 0.012 after two steps and lowers the mean of the other cells to 0.058, while the cluster mean stays at 0.037 to 0.038: diffusion moves CD4 into the CD8 T cells from the cells beside them. The CD8 T cells still end at a fifth of the level of the other cells, so the smoothed map keeps the split. A cluster’s mean shows exchange with other clusters but not inside the cluster, so before reading a smoothed map, compare the populations that the analysis is about, as the CD8A split does here. The graph decides which cells exchange signal, and the neighbor graph tutorial builds it stage by stage and compares neighbor counts.
Keep smoothed values out of statistical tests¶
Each smoothed value is a weighted average of the normalized CD4 of the cells within t edges, so the smoothed values of neighboring cells are not independent measurements, and a test that counts each cell as one observation overstates its certainty. Use smoothed values to display expression, and test differences in expression on the observed counts, with donors as replicates, as in the donor-level comparisons tutorial.
- van Dijk, D., Sharma, R., Nainys, J., Yim, K., Kathail, P., Carr, A. J., Burdziak, C., Moon, K. R., Chaffer, C. L., Pattabiraman, D., Bierie, B., Mazutis, L., Wolf, G., Krishnaswamy, S., & Pe’er, D. (2018). Recovering Gene Interactions from Single-Cell Data Using Data Diffusion. Cell, 174(3), 716-729.e27. 10.1016/j.cell.2018.05.061