Compute statistics that CyteArc does not provide from a store’s neighbor graph or count matrix, and export cells to tools that need another format. This page computes two statistics for 3,948 human peripheral blood mononuclear cells (PBMCs): each cell’s graph strength (the total weight of its edges in the saved neighbor graph) and the number of highly variable genes (HVGs) that the cell detects, counted by streaming the count matrix in blocks. The page saves both as cell columns, selects cells by graph strength, and exports the selection to AnnData and to a new CyteArc store.
Graph strength barely differs between the four major cell types: its mean lies between 8.59 and 8.92 in each, and a cutoff at its lowest quarter keeps 74.7% to 76.0% of each. Detected HVGs differ more between the types than their RNA content does: monocytes detect 199.6 of the 500 HVGs on average, twice the 99.0 of T cells, from a median of 10,436 counts per cell, only about a third more than the 7,882 of T cells.
Open the saved PBMC analysis¶
The example store holds the counts of the 10x Genomics dataset “5k Peripheral blood mononuclear cells (PBMCs) from a healthy donor (v3 chemistry)”, released under CC BY 4.0, and the saved RNA analysis whose clusters the PBMC analysis names.
from pathlib import Path
from tempfile import TemporaryDirectory
import numpy as np
import pandas as pd
import cytearc
from cytearc.plotting import CategoricalScale, CellField
# 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
)Started: 2026-11-18T00:15:56.043394Z | Wall time: 5.851 s
Open the downloaded store and reopen its saved analysis with ds.pipeline.open(label="rna"). CyteArc saves each result of an analysis in the store as an artifact, and the returned pipeline run maps each output name to a reference to the artifact that the run saved under it: run["connectivity_map"] refers to the neighbor graph and run["umap"] to the UMAP. run.cells reads the cell fields that the run recorded, such as its clusters.
Each statistic on this page holds one value per analyzed cell. ds.cells.insert(..., key="I") writes such values to the store’s active cells, the cells flagged True in its I column, in store order, so the values land on the right cells only if the active cells are the analyzed cells. Check that they are:
# Open the store and its saved RNA run.
ds = cytearc.DataStore(f"{dataset}/data.zarr", nthreads=4)
run = ds.pipeline.open(label="rna")
# Check that the store's active cells, its I column, are the cells that the run analyzed.
analyzed = run.cells.fetch_all("I")
{
"stored cells": ds.cells.N,
"analyzed cells": int(analyzed.sum()),
"active cells are the analyzed cells": bool(
np.array_equal(ds.cells.fetch_all("I"), analyzed)
),
"genes": ds.RNA.feats.N,
}{'stored cells': 5025,
'analyzed cells': 3948,
'active cells are the analyzed cells': True,
'genes': 33538}Started: 2026-11-18T00:16:01.897731Z | Wall time: 3.342 s
The run analyzed the 3,948 of the 5,025 stored cells that passed its quality filters, and these are the store’s active cells. The store holds 33,538 genes. The PBMC analysis names the run’s 12 clusters from their marker genes. Save its names as the cell column cellType, joining its CD14 monocytes (cluster 2) and CD16 monocytes (cluster 10) as monocytes, to read each statistic by cell type:
# Name the run's clusters with the cell types of the PBMC analysis, joining its two monocyte clusters.
broad_types = {
"T cells": [1, 3, 4, 8],
"NK cells": [5, 9],
"B cells": [6, 7],
"monocytes": [2, 10],
"pDC-like cells": [11],
"platelets": [12],
}
type_of_cluster = {
cluster: name for name, clusters in broad_types.items() for cluster in clusters
}
# Save the names as a categorical column of the analyzed cells, keyed by cell ID, and count each type.
analyzed_ids = run.cells.fetch("ids")
cell_types = pd.Categorical(
[type_of_cluster[cluster] for cluster in run.cells.fetch("clusters")],
categories=list(broad_types),
)
ds.cells.insert("cellType", pd.Series(cell_types, index=analyzed_ids), key="I", overwrite=True)
pd.Series(cell_types).value_counts(sort=False).rename_axis("cell type").to_frame("cells")| cells | |
|---|---|
| cell type | |
| T cells | 2385 |
| NK cells | 312 |
| B cells | 495 |
| monocytes | 729 |
| pDC-like cells | 15 |
| platelets | 12 |
Started: 2026-11-18T00:16:05.242767Z | Wall time: 0.084 s
T cells make up 2,385 of the 3,948 analyzed cells; the pDC-like cells and platelets, with 15 and 12 cells, are the two smallest groups.
Sum each cell’s edge weights in the graph¶
ds.graph.load returns a saved graph as a SciPy sparse matrix with one row and one column for each analyzed cell, in store order. With symmetric=True, two cells share an edge when either chose the other as a neighbor, and upper_only=False stores each edge in both directions; the graph construction tutorial shows how the run built the edges and their weights. The sum of a row is the cell’s graph strength, also called its weighted degree:
# Load the run's graph with each edge stored in both directions.
graph = ds.graph.load(graph=run["connectivity_map"], symmetric=True, upper_only=False)
# Sum the weights of each cell's edges, whose rows follow the analyzed cells, and save the sums.
graph_strength = np.asarray(graph.sum(axis=1)).ravel()
ds.cells.insert(
column_name="customGraphStrength",
values=pd.Series(graph_strength, index=analyzed_ids),
key="I",
overwrite=True,
)
# Summarize the graph, with the neighbor count saved in the run's provenance.
edges_per_cell = np.diff(graph.indptr)
{
"cells": graph.shape[0],
"neighbors chosen per cell": ds.artifacts.inspect(run["neighbors"]).parameters["k"],
"edges per cell (min, median, max)": (
int(edges_per_cell.min()),
int(np.median(edges_per_cell)),
int(edges_per_cell.max()),
),
"nonzero entries": graph.nnz,
"graph strength (min, mean, max)": (
round(float(graph_strength.min()), 2),
round(float(graph_strength.mean()), 2),
round(float(graph_strength.max()), 2),
),
}{'cells': 3948,
'neighbors chosen per cell': 11,
'edges per cell (min, median, max)': (11, 15, 53),
'nonzero entries': 64858,
'graph strength (min, mean, max)': (5.38, 8.82, 27.03)}Started: 2026-11-18T00:16:05.329519Z | Wall time: 0.163 s
The run chose 11 neighbors for each cell, and edges also join each cell to the cells that chose it, so the analyzed cells have 11 to 53 edges. The run scales the weights from each cell to its own 11 neighbors so that they add up to the same total for every cell, and graph strength rises above that total only through the cells that chose the cell as a neighbor. Graph strength runs from 5.38 to 27.03, with a mean of 8.82; a high value marks a cell that many other cells chose. Plot the cell types beside graph strength on the run’s UMAP:
# Show the cell types beside graph strength on the run's UMAP.
ds.plots.embedding(
layout=run["umap"],
color_by=[
CellField("cellType", label="Cell type"),
CellField("customGraphStrength", label="Graph strength (sum of edge weights)"),
],
categorical_scale=CategoricalScale(order=tuple(broad_types)),
n_columns=2,
)
Started: 2026-11-18T00:16:05.495504Z | Wall time: 1.314 s
High graph strength marks no single population: the brightest cells lie among the T cells, NK cells, B cells and monocytes alike. The column customGraphStrength keeps no record of the graph it came from, so after building another graph, such as one with more neighbors, compute the column again from that graph.
Count detected HVGs block by block¶
ds.RNA.rawData is the RNA assay’s count matrix, cells by genes, as a chunked array: indexing it selects cells and genes without reading counts. Select the run’s analyzed cells and its 500 HVGs:
# Locate the run's cells and highly variable genes on the axes of the stored counts.
cell_index = np.flatnonzero(run.cells.fetch_all("I"))
feature_index = np.flatnonzero(run.features.fetch_all("highly_variable_features"))
# Select those cells and genes; the view reads no counts until it is streamed.
selected_counts = ds.RNA.rawData[:, feature_index][cell_index, :]
selected_counts.shape(3948, 500)Started: 2026-11-18T00:16:06.812747Z | Wall time: 0.169 s
A cell detects an HVG when it has at least one count of that gene. stream_blocks yields the selection one block of cells at a time, in row order, and reads ahead only as many blocks as the memory budget allows; selected_counts.compute() would instead load the whole selection at once. Each block holds at most as many cells as one shard, the stored object that holds a range of rows of the count matrix. This small store keeps all 5,025 cells in one shard, so the 3,948 selected cells arrive in one block. On a store of millions of cells, the loop below runs once for each shard’s worth of selected cells and keeps only a short vector from each block:
# Count the HVGs that each cell detects, one block of cells at a time.
detected_blocks = []
for count_block in selected_counts.stream_blocks(
nthreads=4, msg="Counting detected HVGs"
):
detected_blocks.append(np.count_nonzero(count_block, axis=1))
# Join the block results, which arrive in the order of the analyzed cells, and save them.
detected_hvgs = np.concatenate(detected_blocks)
ds.cells.insert(
column_name="customDetectedHVGs",
values=pd.Series(detected_hvgs, index=analyzed_ids),
key="I",
overwrite=True,
)
# Summarize the result, and check it against the matrix's own nonzero count.
{
"blocks": len(detected_blocks),
"cells": detected_hvgs.size,
"detected HVGs (min, mean, max)": (
int(detected_hvgs.min()),
round(float(detected_hvgs.mean()), 1),
int(detected_hvgs.max()),
),
"equal to count_nonzero(axis=1)": bool(
np.array_equal(detected_hvgs, selected_counts.count_nonzero(axis=1).compute())
),
}{'blocks': 1,
'cells': 3948,
'detected HVGs (min, mean, max)': (24, 123.5, 250),
'equal to count_nonzero(axis=1)': True}Started: 2026-11-18T00:16:06.984826Z | Wall time: 0.661 s
Each cell detects 24 to 250 of the 500 HVGs, 123.5 on average, the same counts that selected_counts.count_nonzero(axis=1) returns. A chunked array provides count_nonzero, sum, mean and var as reductions that read the same blocks; a loop over stream_blocks handles any calculation they do not cover.
Select cells with a custom column¶
A Boolean cell column selects cells wherever CyteArc takes a cell key: the export and the subset writer below take it as cell_key, and a pipeline recipe takes it as cells. As an example, select the cells above the lowest quarter of graph strength. The values cover the analyzed cells, and fill_value=False writes False for the other stored cells, so every stored cell holds a Boolean rather than a missing value:
# Select the cells above the lowest quarter of graph strength.
cutoff = np.quantile(graph_strength, 0.25)
well_connected = graph_strength >= cutoff
# Save the selection for every stored cell, with False for the cells outside the run.
ds.cells.insert(
column_name="wellConnected",
values=pd.Series(well_connected, index=analyzed_ids),
fill_value=False,
key="I",
overwrite=True,
)
# Count the saved values among all stored cells.
saved = ds.cells.fetch_all("wellConnected")
{
"graph strength cutoff": round(float(cutoff), 2),
"True": int(saved.sum()),
"False, analyzed cells": int((~saved & analyzed).sum()),
"False, cells outside the run": int((~saved & ~analyzed).sum()),
}{'graph strength cutoff': 6.65,
'True': 2961,
'False, analyzed cells': 987,
'False, cells outside the run': 1077}Started: 2026-11-18T00:16:07.648230Z | Wall time: 0.040 s
The cutoff falls at a graph strength of 6.65. The saved column holds True for the 2,961 cells above it, and False for the 987 analyzed cells below it and for the 1,077 cells outside the run.
Compare the statistics across cell types¶
Plot the detected HVGs beside the selection, with the cells that the selection drops in black. Then read the custom columns back from the store with ds.cells.to_pandas_dataframe and summarize them by cell type:
# Show the streamed statistic beside the selection, with the dropped cells in black.
ds.plots.embedding(
layout=run["umap"],
color_by=[
CellField("customDetectedHVGs", label="Detected HVGs per cell"),
CellField("wellConnected", label="Selected"),
],
categorical_scale=CategoricalScale(
order=(True, False), palette={True: "#bdbdbd", False: "#202020"}
),
n_columns=2,
)
Started: 2026-11-18T00:16:07.690807Z | Wall time: 0.608 s
# Read the custom columns of the analyzed cells back from the store, with their total counts.
columns = ["cellType", "customDetectedHVGs", "customGraphStrength", "wellConnected"]
custom = ds.cells.to_pandas_dataframe(columns, key="I")
custom["totalCounts"] = run.cells.fetch("RNA_nCounts")
# Summarize each column by cell type.
summary = custom.groupby("cellType").agg(
**{
"cells": ("wellConnected", "size"),
"median total counts": ("totalCounts", "median"),
"mean detected HVGs": ("customDetectedHVGs", "mean"),
"mean graph strength": ("customGraphStrength", "mean"),
"selected (%)": ("wellConnected", "mean"),
}
)
summary = summary.reindex(list(broad_types)).rename_axis("cell type")
summary["median total counts"] = summary["median total counts"].round().astype(int)
summary["selected (%)"] *= 100
summary.round({"mean detected HVGs": 1, "mean graph strength": 2, "selected (%)": 1})| cells | median total counts | mean detected HVGs | mean graph strength | selected (%) | |
|---|---|---|---|---|---|
| cell type | |||||
| T cells | 2385 | 7882 | 99.0 | 8.92 | 74.7 |
| NK cells | 312 | 6354 | 135.4 | 8.59 | 74.7 |
| B cells | 495 | 7238 | 120.5 | 8.68 | 74.9 |
| monocytes | 729 | 10436 | 199.6 | 8.72 | 76.0 |
| pDC-like cells | 15 | 11778 | 160.7 | 8.07 | 73.3 |
| platelets | 12 | 2664 | 127.9 | 7.30 | 91.7 |
Started: 2026-11-18T00:16:08.302497Z | Wall time: 0.074 s
The monocytes, brightest in the left panel, detect twice as many HVGs as T cells from about a third more counts. B cells and NK cells detect more HVGs than T cells from fewer counts: 120.5 and 135.4 HVGs from medians of 7,238 and 6,354 counts, against 99.0 from 7,882. The platelets hold about a third of the T cells’ counts, a median of 2,664, and still detect more HVGs, 127.9. Counts per cell therefore do not set the order: the statistic is the number of the 500 selected genes that a cell detects, so the statistic depends on which genes the selection holds.
The selection keeps a similar share of each major type, so the 2,961 selected cells have nearly the cell-type composition of the 3,948 analyzed cells. The platelets keep 91.7% of their 12 cells; in a group that small, one cell moves the share by 8 points.
Export the selection to AnnData¶
to_anndata builds an in-memory AnnData object for Scanpy and other Python tools, with the counts in X, the cell table in obs and the feature table in var. Choose the cells and genes before exporting, so the object holds only what the next tool needs. Export the selected cells with six markers of the main lineages:
# Export the raw counts of six lineage markers for the selected cells.
panel_genes = ["CD3D", "MS4A1", "CD14", "LYZ", "NKG7", "GNLY"]
adata = ds.to_anndata(cell_key="wellConnected", feature_names=panel_genes)
# List the exported tables, then the gene IDs that index var beside the gene names.
print(adata)
adata.var[["names"]]AnnData object with n_obs × n_vars = 2961 × 6
obs: 'I', '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', 'cellType', 'customDetectedHVGs', 'customGraphStrength', 'wellConnected'
var: 'I', 'names', 'dropOuts', 'feature_type', 'genome', 'nCells'
layers: None (.X)
| names | |
|---|---|
| gene_ids | |
| ENSG00000167286 | CD3D |
| ENSG00000156738 | MS4A1 |
| ENSG00000170458 | CD14 |
| ENSG00000090382 | LYZ |
| ENSG00000105374 | NKG7 |
| ENSG00000115523 | GNLY |
Started: 2026-11-18T00:16:08.379570Z | Wall time: 0.947 s
The export holds the 2,961 selected cells and the 6 genes. obs carries the whole cell table, including cellType and the three custom columns, so Scanpy can group and color the cells by the custom statistics. var is indexed by the genes’ Ensembl IDs, such as ENSG00000167286 for CD3D, so adata.var_names lists IDs rather than the symbols passed as feature_names; the symbols stay in var["names"]. Omit feature_names to export every gene, if the object fits in memory. The import and export tutorial shows how to write H5AD files without building the object in memory, and how to export saved results such as a PCA, a UMAP and clusters beside the counts.
Write the selection to a new store¶
SubsetZarr writes the selected cells to a new CyteArc store with every gene of the assays it is given, so the next analysis can choose its own genes. Write the store to a temporary directory:
# Write the selected cells with every RNA gene to a new store in a temporary directory.
export_directory = TemporaryDirectory()
subset_path = Path(export_directory.name) / "well_connected.zarr"
cytearc.SubsetZarr(
zarr_loc=str(subset_path), assays=[ds.RNA], cell_key="wellConnected"
).dump()
# Open the new store and check its cells, genes, custom columns and saved runs.
subset = cytearc.DataStore(str(subset_path))
{
"cells": subset.cells.N,
"genes": subset.RNA.feats.N,
"custom columns": [name for name in subset.cells.columns if name in columns],
"saved pipeline runs": len(subset.pipeline.list_runs()),
}{'cells': 2961,
'genes': 33538,
'custom columns': ['cellType',
'customDetectedHVGs',
'customGraphStrength',
'wellConnected'],
'saved pipeline runs': 0}Started: 2026-11-18T00:16:09.329150Z | Wall time: 3.272 s
The new store holds the 2,961 selected cells with all 33,538 genes, and its cell table keeps cellType and the custom columns. The store holds no saved pipeline run of the source store, so an analysis of the subset starts from its counts. Python deletes the temporary directory when the session ends; write to a lasting path to keep the store.
Return results through public calls¶
Write results through public calls, as this page does with ds.cells.insert and SubsetZarr, rather than into the store’s Zarr groups, such as ds.z and ds.zw, whose layout is internal and can change between CyteArc releases. A column written with ds.cells.insert holds only its values, with no record of how they were computed. Coordinates computed by another tool, such as a latent space from scVI, come back as an artifact through ds.reduction.import_coordinates, which records the tool, version and parameters passed as its source; a graph, a UMAP and clusters can then build on the imported coordinates, as the import and export tutorial shows.