Find the transcription factors that are active in each population of the 10x Genomics multiome sample pbmc_granulocyte_sorted_3k: 2,711 human peripheral blood mononuclear cells (PBMCs), with RNA and ATAC measured in the same cells. From RNA, the analysis infers SCENIC regulons, and the most specific of them include known lineage regulators of B cells, T cells, NK cells and monocytes. Without any factor list, the analysis also groups most of the variable genes into co-regulated gene programs; the T-cell program shares genes with the regulon of a T-cell factor, and its own genes are enriched for a motif annotated to the same factor. From ATAC, chromVAR finds the motifs of lineage regulators most accessible in their own lineages, and the sites where SPI1 (PU.1) is bound in monocytes separate myeloid cells from lymphocytes more sharply than the SPI1 motif does.
A regulon is a transcription factor together with the genes it is predicted to regulate. SCENIC finds regulons in RNA data in two steps Aibar et al., 2017: genes whose expression follows a factor’s expression become candidate targets, and motif enrichment near those genes keeps the targets that the factor can plausibly bind. Chromatin accessibility adds evidence that does not rest on expression: when the peaks that hold a factor’s motif, or the peaks where a CUT&RUN experiment found the factor bound, are more accessible in some cells than those cells’ sequencing depth predicts, the factor is likely active there Schep et al., 2017.
Download the data and reference files¶
The page reads seven public files: the 10x Genomics matrix (CC BY 4.0); the human transcription factor list, a cisTarget motif-ranking database and its motif-to-factor table from the Aerts lab; the JASPAR 2024 vertebrate motifs (CC BY 4.0); the GENCODE release 32 genome; and SPI1 CUT&RUN peaks from ChIP-Atlas. ChIP-Atlas (c) Shinya Oki (Kyoto University) licensed under CC Attribution-Share Alike 4.0 International. The cisTarget v10 motif collection includes motifs derived from TRANSFAC Professional, a commercial database, so check its terms before commercial use. For another dataset, choose a cisTarget database of the same species and gene names, and the genome build that the dataset’s peaks were called against.
Reading the cisTarget database needs the regulons extra: pip install "cytearc[extra,regulons]". The seven downloads take 1.29 GB and the decompressed genome another 3.15 GB, in a regulon_inputs folder that later runs reuse.
# Import the tools for downloading and decompressing the reference files.
import gzip
import shutil
import time
from http.client import HTTPException
from pathlib import Path
from urllib.request import Request, urlopen
# Import the tools for tables and figures.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
# Import CyteArc and its regulon functions.
import cytearc
from cytearc import regulons as rg
# Keep routine logs and progress bars out of the results, and show whole gene lists in tables.
cytearc.configure_output(level="WARNING", progress=False)
pd.set_option("display.max_colwidth", 120)
# Keep the downloaded reference files in one folder.
inputs = Path("regulon_inputs")
inputs.mkdir(exist_ok=True)
# Download a file once and return its local path. Retry a connection that fails
# or ends early, and write to a temporary name, so that an interrupted download
# is never used.
def fetch(url, attempts=4):
path = inputs / url.rsplit("/", 1)[1]
if path.exists():
return path
request = Request(url, headers={"User-Agent": "CyteArc documentation"})
partial = path.with_name(path.name + ".part")
for attempt in range(1, attempts + 1):
try:
with urlopen(request, timeout=120) as response, open(partial, "wb") as target:
expected = response.headers.get("Content-Length")
shutil.copyfileobj(response, target)
if expected is not None and partial.stat().st_size != int(expected):
raise OSError(f"{url} ended after {partial.stat().st_size} of {expected} bytes")
return partial.rename(path)
except (OSError, HTTPException):
if attempt == attempts:
raise
time.sleep(30 * attempt)
# Download the 10x Genomics PBMC multiome sample (Cell Ranger ARC 2.0, GRCh38).
matrix_h5 = fetch(
"https://cf.10xgenomics.com/samples/cell-arc/2.0.0/pbmc_granulocyte_sorted_3k/"
"pbmc_granulocyte_sorted_3k_filtered_feature_bc_matrix.h5"
)
# Download the human transcription factors that the motif annotations cover.
tf_list = fetch("https://resources.aertslab.org/cistarget/tf_lists/allTFs_hg38.txt")
# Download the cisTarget database that ranks human genes by their motif matches.
ranking_db = fetch(
"https://resources.aertslab.org/cistarget/databases/homo_sapiens/hg38/refseq_r80/mc_v10_clust/"
"gene_based/hg38_10kbp_up_10kbp_down_full_tx_v10_clust.genes_vs_motifs.rankings.feather"
)
# Download the table that assigns each cisTarget motif to transcription factors.
motif_table = fetch(
"https://resources.aertslab.org/cistarget/motif2tf/motifs-v10nr_clust-nr.hgnc-m0.001-o0.0.tbl"
)
# Download the JASPAR 2024 vertebrate motifs.
jaspar = fetch(
"https://jaspar.elixir.no/download/data/2024/CORE/"
"JASPAR2024_CORE_vertebrates_non-redundant_pfms_jaspar.txt"
)
# Download the genome of GENCODE release 32, which the 10x peaks were called against.
genome_gz = fetch(
"https://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_32/"
"GRCh38.primary_assembly.genome.fa.gz"
)
# Download SPI1 (PU.1) CUT&RUN peaks from primary human monocytes (GEO GSM8669389).
spi1_cutrun = fetch("https://chip-atlas.dbcls.jp/data/hg38/eachData/bed05/SRX26995709.05.bed")
# Decompress the genome once, because motif scanning reads it at many positions.
genome_fa = inputs / "GRCh38.primary_assembly.genome.fa"
if not genome_fa.exists():
with gzip.open(genome_gz, "rb") as source, open(genome_fa, "wb") as target:
shutil.copyfileobj(source, target)
# Report the disk space that the files take.
downloads = [matrix_h5, tf_list, ranking_db, motif_table, jaspar, genome_gz, spi1_cutrun]
print(
f"{len(downloads)} downloads take {sum(path.stat().st_size for path in downloads) / 1e9:.2f} GB, "
f"and the decompressed genome {genome_fa.stat().st_size / 1e9:.2f} GB"
)7 downloads take 1.29 GB, and the decompressed genome 3.15 GB
Started: 2026-11-28T18:58:12.369325Z | Wall time: 702.233 s
Build the store and name the populations¶
CrToZarr writes the 10x matrix into a CyteArc store, a folder of Zarr arrays that holds the RNA and ATAC peak counts as two assays over the same cells. The RNA recipe, ds.pipeline.rna, then removes outlier cells by their RNA quality metrics, selects highly variable genes, builds the neighbor graph and UMAP, and clusters the cells with Leiden. The recipe returns a pipeline run whose outputs the rest of the page reuses: run["analysis_cell_selection"] is a frozen cell selection, the saved and unchangeable list of the cells that the run analyzed, and run["umap"] is their layout.
# Write the RNA and ATAC peak counts into one store, as two assays over the same cells.
cytearc.CrToZarr(cytearc.CrH5Reader(str(matrix_h5)), zarr_loc="pbmc_multiome.zarr").dump()
# Open the store with every cell, so that the RNA run decides which cells pass quality control.
ds = cytearc.DataStore(
"pbmc_multiome.zarr",
default_assay="RNA",
min_features_per_cell=-1,
nthreads=4,
)
# Run the RNA recipe: quality control, variable genes, neighbor graph, UMAP, and clusters.
run = ds.pipeline.rna(label="baseline")
# Keep the analyzed cells as a frozen selection and as a mask over all cells.
cells = run["analysis_cell_selection"]
analyzed = np.asarray(run.cells.fetch_all("I"), dtype=bool)
print(f"{analyzed.sum():,} of {ds.cells.N:,} cells pass the RNA run's quality control")
# Show the store's assays and cell metadata.
ds2,612 of 2,711 cells pass the RNA run's quality control
DataStore has 2711 (2711) cells with 2 assays: ATAC RNA
Cell metadata:
'I', 'ids', 'names', 'ATAC_nCounts', 'ATAC_nFeatures',
'RNA_nCounts', 'RNA_nFeatures', 'RNA_percentMito', 'RNA_percentRibo', 'sourceRow'
ATAC assay has 98319 features and following metadata:
'I', 'ids', 'names', 'dropOuts', 'feature_type',
'genome', 'interval', 'nCells'
RNA assay has 36601 features and following metadata:
'I', 'ids', 'names', 'dropOuts', 'feature_type',
'genome', 'interval', 'nCells'Started: 2026-11-28T19:09:54.610922Z | Wall time: 109.267 s
The output above counts the cells that pass quality control and the genes and ATAC peaks of the store.
Name each cluster after the marker panel it expresses most strongly: each gene is scaled across clusters, and each cluster takes the panel whose genes have the highest mean scaled expression. The names go into a population cell column, so that the results below read as populations rather than cluster numbers. Cell type annotation shows how to check names like these against marker evidence.
# Define marker panels of the PBMC populations, myeloid first.
panels = {
"CD14 monocyte": ["CD14", "LYZ", "VCAN", "S100A8"],
"CD16 monocyte": ["FCGR3A", "MS4A7", "LST1"],
"Dendritic cell": ["FCER1A", "CD1C", "CLEC10A"],
"Plasmacytoid DC": ["LILRA4", "IL3RA", "CLEC4C"],
"B cell": ["MS4A1", "CD79A", "BANK1", "PAX5"],
"CD4 T cell": ["CD3E", "IL7R", "CD4"],
"CD8 T cell": ["CD3E", "CD8A", "CD8B"],
"NK cell": ["NKG7", "GNLY", "KLRD1"],
}
# Average each gene's normalized expression in each cluster, keeping the gene
# names that select one feature.
means = ds.compare.compute_bulk(run["clusters"], feature_label="name").profiles
means = means.loc[~means.index.duplicated(keep=False)]
# Scale each gene across clusters, and score each panel in each cluster as the
# mean scaled expression of its genes.
scaled = means.sub(means.mean(axis=1), axis=0).div(means.std(axis=1).replace(0, 1), axis=0)
panel_scores = pd.DataFrame({name: scaled.loc[genes].mean() for name, genes in panels.items()})
# Name each cluster after its best-scoring panel and each analyzed cell after its
# cluster, and keep the populations in panel order.
cluster_names = panel_scores.idxmax(axis=1)
cell_type = cluster_names.reindex(run.cells.fetch("clusters")).to_numpy()
populations = [name for name in panels if name in set(cell_type)]
# Store the populations as a cell column of the analyzed cells, keyed by cell ID,
# which plots and specificity scores read.
cell_ids = ds.cells.fetch_all("ids")
ds.cells.insert("analyzed", pd.Series(analyzed, index=cell_ids), overwrite=True)
ds.cells.insert(
"population", pd.Series(cell_type, index=cell_ids[analyzed]), key="analyzed", overwrite=True
)
# Count the clusters and cells of each population.
pd.DataFrame({
"clusters": cluster_names.groupby(cluster_names).apply(lambda group: ", ".join(map(str, group.index))),
"cells": pd.Series(cell_type).value_counts(),
}).loc[populations]| clusters | cells | |
|---|---|---|
| CD14 monocyte | 1, 7 | 733 |
| CD16 monocyte | 8 | 121 |
| Dendritic cell | 10 | 52 |
| Plasmacytoid DC | 11 | 29 |
| B cell | 5 | 192 |
| CD4 T cell | 2, 3 | 849 |
| CD8 T cell | 4, 6 | 534 |
| NK cell | 9 | 102 |
Started: 2026-11-28T19:11:43.880184Z | Wall time: 0.478 s
The table maps each cluster to a population and counts the cells of each population, among them plasmacytoid dendritic cells (DCs).
Infer regulons from RNA¶
GRNBoost2 asks, for every gene, how well each transcription factor’s expression predicts the gene’s expression, using gradient-boosted trees on raw counts Moerman et al., 2018. ds.regulons.grn runs GRNBoost2 with the settings of pySCENIC Sande et al., 2020 and saves the network as an artifact, a stored result that records the inputs and parameters it came from. GRNBoost2 fits a boosted-tree model for every gene, so its run time grows with both the cells and the genes. This page fits the network on 500 sampled cells, the highly variable genes, and every listed transcription factor detected in at least 1% of the analyzed cells. A full analysis fits all expressed genes on all cells, or on a representative sample of a large dataset, and fits again with a second random_seed to keep the regulons and targets that recur, because GRNBoost2 is stochastic. The methods page measures how much the links change between seeds.
# Draw 500 analyzed cells at random, reproducibly, and freeze them as the cells
# that the network models.
rng = np.random.default_rng(0)
sample = np.zeros(ds.cells.N, dtype=bool)
sample[rng.choice(np.flatnonzero(analyzed), size=500, replace=False)] = True
ds.cells.insert("grn_cells", pd.Series(sample, index=cell_ids), overwrite=True)
grn_cells = ds.snapshot_cell_selection("grn_cells")
# Model the highly variable genes and every transcription factor of the list
# that is detected in at least 1% of analyzed cells.
tfs = tf_list.read_text().split()
names = np.asarray(ds.RNA.feats.fetch_all("names")).astype(str)
variable = np.asarray(run.features.fetch_all("highly_variable_features"), dtype=bool)
detected = ds.features.detected(cells, min_cells=int(analyzed.sum() // 100))
expressed = np.asarray(ds.artifacts.load(detected)["values"][:], dtype=bool)
grn_genes = ds.features.snapshot(
from_assay="RNA",
mask=variable | (expressed & np.isin(names, tfs)),
)
# Score every factor-to-gene link with GRNBoost2.
grn = ds.regulons.grn(grn_cells, features=grn_genes, tfs=tfs, random_seed=777)
network = ds.regulons.load_grn(grn)
adjacencies = network.adjacencies
# Count the factors, genes, and links, and show the strongest links.
print(
f"{len(network.regulators):,} factors, {adjacencies['target'].nunique():,} target genes, "
f"{len(adjacencies):,} links"
)
adjacencies.head().round(2)1,212 factors, 2,138 target genes, 387,579 links
| TF | target | importance | correlation | |
|---|---|---|---|---|
| 0 | PAX5 | EBF1 | 95.83 | 0.71 |
| 1 | PAX5 | BANK1 | 82.93 | 0.67 |
| 2 | EBF1 | BANK1 | 73.64 | 0.78 |
| 3 | PAX5 | RALGPS2 | 73.40 | 0.69 |
| 4 | EBF1 | PAX5 | 67.41 | 0.71 |
Started: 2026-11-28T19:11:44.360199Z | Wall time: 54.977 s
GRNBoost2 scores links from factors to target genes, and the output above counts them. Each row of the table is a link: importance measures how much the factor’s expression helps predict the target, and correlation gives the direction. The table lists the strongest links.
pySCENIC turns each factor’s strongest activating links into several candidate modules, then keeps only the module genes that a motif annotated to that factor ranks highly. For each motif, the cisTarget database ranks every gene by the motif’s best match in the region from 10 kb upstream of the gene’s transcription start site to 10 kb past the gene’s end. The genes that remain form the factor’s regulon, named FACTOR(+) for an activating factor.
# Build pySCENIC's candidate modules from each factor's activating links.
modules = rg.modules_from_adjacencies(adjacencies)
# Keep the module targets that an enriched motif of the module's factor ranks
# highly, and merge each factor's remaining targets into one regulon.
database = rg.RankingDatabase(ranking_db)
annotations = rg.read_motif_annotations(motif_table)
enriched = rg.prune_modules(modules, [database], annotations, nthreads=4)
regulons = rg.regulons_from_motifs(enriched)
# Count the modules and regulons, and list the ten largest regulons.
sizes = regulons.groupby("source").size()
print(
f"{modules['source'].nunique():,} modules of {modules['TF'].nunique():,} factors "
f"leave {len(sizes)} regulons with {sizes.median():.0f} genes at the median"
)
sizes.nlargest(10).to_frame("genes").T4,574 modules of 1,212 factors leave 188 regulons with 15 genes at the median
| source | KLF4(+) | KLF6(+) | NR3C1(+) | BACH1(+) | CHD1(+) | RXRA(+) | KLF2(+) | FOXO3(+) | ELF1(+) | BCL6(+) |
|---|---|---|---|---|---|---|---|---|---|---|
| genes | 204 | 201 | 195 | 173 | 148 | 139 | 115 | 114 | 106 | 96 |
Started: 2026-11-28T19:12:39.339692Z | Wall time: 11.765 s
Motif pruning turns the candidate modules into regulons for a subset of the factors, and the output above counts them and lists the largest.
AUCell scores each regulon in each analyzed cell by how many of its genes rank among the cell’s most strongly expressed genes Aibar et al., 2017. The regulon specificity score (RSS) then measures how concentrated a regulon’s activity is in a population, and reaches 1 when the regulon is active only, and evenly, in that population.
# Score every regulon of at least ten genes in every analyzed cell with AUCell,
# ranking all genes of the RNA assay, the run's feature universe, in each cell.
regulon_auc = ds.scores.aucell(regulons, cells, features=run["feature_universe"], tmin=10)
# Measure each regulon's specificity to each population, reading the scores in blocks of cells.
rss = ds.regulons.specificity(regulon_auc, "population").loc[populations]
# Check, as the text says, that each lineage's known regulator is among the
# three most specific regulons of its populations, and that the most specific
# regulons of the dendritic cells and the plasmacytoid DCs score lower than
# those of the larger half of the populations.
known_regulators = {
"B cell": ["EBF1"],
"CD4 T cell": ["ETS1"],
"CD8 T cell": ["EOMES", "TBX21"],
"NK cell": ["EOMES", "TBX21"],
"CD16 monocyte": ["CEBPA", "CEBPB"],
}
for population, factors in known_regulators.items():
most_specific = rss.loc[population].nlargest(3).index
assert all(f"{factor}(+)" in most_specific for factor in factors), population
population_sizes = pd.Series(cell_type).value_counts()
larger_half = population_sizes.index[population_sizes > population_sizes.median()]
top_specificity = rss.max(axis=1)
dendritic_cells = top_specificity[["Dendritic cell", "Plasmacytoid DC"]]
assert dendritic_cells.max() < top_specificity[larger_half].min()
# List the three most specific regulons of each population with their scores.
print(f"AUCell scored {rss.shape[1]} of the {len(sizes)} regulons")
rss.apply(
lambda scores: ", ".join(f"{name} {value:.2f}" for name, value in scores.nlargest(3).items()),
axis=1,
).to_frame("most specific regulons (RSS)")AUCell scored 126 of the 188 regulons
| most specific regulons (RSS) | |
|---|---|
| group | |
| CD14 monocyte | FOS(+) 0.60, NFIC(+) 0.59, BCL6(+) 0.58 |
| CD16 monocyte | TCF7L2(+) 0.30, CEBPB(+) 0.30, CEBPA(+) 0.28 |
| Dendritic cell | RUNX2(+) 0.24, CEBPG(+) 0.22, NFIC(+) 0.22 |
| Plasmacytoid DC | RUNX2(+) 0.28, ARID3A(+) 0.24, BCL11A(+) 0.23 |
| B cell | EBF1(+) 0.51, BCL11A(+) 0.38, ZNF543(+) 0.35 |
| CD4 T cell | ETS1(+) 0.54, KLF12(+) 0.52, BACH2(+) 0.50 |
| CD8 T cell | EOMES(+) 0.44, MYBL1(+) 0.42, TBX21(+) 0.42 |
| NK cell | TBX21(+) 0.32, EOMES(+) 0.31, MYBL1(+) 0.29 |
Started: 2026-11-28T19:12:51.108831Z | Wall time: 8.493 s
# Pick the most specific regulon of the CD14 monocytes, the B cells, and the NK cells.
shown = rss.loc[["CD14 monocyte", "B cell", "NK cell"]].idxmax(axis=1).unique()
# Read the regulon scores as a cells-by-regulons table, whose index holds each
# cell's row in the cell table, and store the scores of the three regulons as cell
# columns, keyed by cell ID, which the plot colors the cells by.
activity = ds.scores.load(regulon_auc).to_pandas()
for name in shown:
scores = pd.Series(activity[name].to_numpy(), index=cell_ids[activity.index])
ds.cells.insert(f"{name} AUCell", scores, key="analyzed", overwrite=True)
# Color the RNA run's UMAP by population and by the activity of each regulon.
ds.plots.embedding(
layout=run["umap"],
color_by=["population", *[f"{name} AUCell" for name in shown]],
n_columns=2,
sort_values=True,
)
Started: 2026-11-28T19:12:59.603620Z | Wall time: 0.753 s
AUCell scores the regulons with at least ten genes. Several of the most specific regulons belong to known lineage regulators, which the table lists by population. Small populations score lower, because a regulon’s background activity in the many other cells outweighs its activity in a few cells: the most specific regulons of the dendritic cells and the plasmacytoid DCs have lower scores than those of the large populations. On the UMAP, the most specific regulon of the CD14 monocytes is active across them, that of the B cells in the B cells, and that of the NK cells in the NK cells and in part of the CD8 T cells.
Regulons that are active in the same cells may act together. The connection specificity index (CSI) of two regulons is the fraction of all regulons whose correlation with each of the two is more than a margin, 0.05 by default, below the two regulons’ correlation with each other. Clustering the CSI groups co-active regulons into regulon modules, as SCENIC analyses do.
# Score how specifically each pair of regulons is active in the same cells.
csi = ds.regulons.connection_specificity(regulon_auc)
# Cluster the CSI into five regulon modules, and average each module's scores in each population.
regulon_groups = rg.regulon_modules(csi, n_modules=5)
module_activity = activity.T.groupby(regulon_groups).mean().T.groupby(cell_type).mean()
# Check that the module that holds EOMES(+) is most active in NK cells or T
# cells, and the module that holds EBF1(+) in plasmacytoid DCs or B cells, as
# the text says.
most_active = module_activity.idxmax()
assert most_active[regulon_groups["EOMES(+)"]] in {"NK cell", "CD4 T cell", "CD8 T cell"}
assert most_active[regulon_groups["EBF1(+)"]] in {"Plasmacytoid DC", "B cell"}
# Name a module by its regulons with the highest mean CSI with the rest of the module.
def most_connected(members):
return ", ".join(csi.loc[members.index, members.index].mean().nlargest(6).index)
# List each module's size, most connected regulons, and most active population.
pd.DataFrame({
"regulons": regulon_groups.value_counts().sort_index(),
"most connected regulons": regulon_groups.groupby(regulon_groups).apply(most_connected),
"most active in": most_active,
})| regulons | most connected regulons | most active in | |
|---|---|---|---|
| module | |||
| 1 | 45 | RXRA(+), KLF4(+), KLF6(+), BACH1(+), FOXO3(+), BCL6(+) | CD14 monocyte |
| 2 | 38 | STAT6(+), ELK3(+), SREBF1(+), ARID3A(+), ZBTB37(+), BCLAF1(+) | CD14 monocyte |
| 3 | 25 | KLF12(+), CHURC1(+), MYBL1(+), EOMES(+), ZNF43(+), NFATC2(+) | NK cell |
| 4 | 10 | ZNF543(+), BCL11A(+), EBF1(+), RUNX2(+), ZSCAN30(+), IRF4(+) | Plasmacytoid DC |
| 5 | 8 | THRB(+), GABPB1(+), ZNF431(+), ATF1(+), HCFC1(+), TFAP4(+) | B cell |
Started: 2026-11-28T19:13:00.358307Z | Wall time: 0.171 s
The table gives each regulon module’s most active population and its most connected regulons, those with the highest mean CSI within the module. Some modules follow lineages: one joins the regulons of T-cell and NK-cell factors, and one joins those of plasmacytoid DC and B-cell factors. Other modules are most active in a population, such as the CD14 monocytes or the B cells, but most of their most connected regulons are not known regulators of that lineage.
Find co-regulated gene programs¶
A regulon starts from a known factor. A gene program starts from the genes: genes that rise and fall together across many groups of similar cells are likely regulated as a unit, whether or not the factor is known. Programs need no factor list or motif database, so they apply to any scRNA-seq dataset, including species without a cisTarget database.
Pool the analyzed cells into metacells, small groups of similar cells from a fine Leiden clustering, to average out the sampling noise of single cells; ds.regulons.profiles sums each metacell’s RNA counts as log counts per million. rg.gene_programs then links each highly variable gene to the genes it correlates with most across metacells and splits that gene graph into programs with Leiden.
# Pool similar cells into metacells to average out single-cell sampling noise.
metacells = ds.clusters.leiden(run["connectivity_map"], resolution=15)
profiles = ds.regulons.profiles(metacells, from_assay="RNA")
# Find programs among the highly variable genes.
program_genes = [gene for gene in names[variable] if gene in profiles.columns]
programs = rg.gene_programs(profiles[program_genes])
# Count the metacells and the genes in programs, and list each program's size
# and its eight most typical genes.
print(
f"{len(profiles)} metacells; {len(programs):,} of {len(program_genes):,} variable genes "
f"fall into {programs['source'].nunique()} programs"
)
programs.groupby("source", sort=False)["target"].agg(
size="size",
leading_genes=lambda genes: ", ".join(genes.head(8)),
)118 metacells; 745 of 999 variable genes fall into 5 programs
| size | leading_genes | |
|---|---|---|
| source | ||
| P1 | 221 | ABLIM1, CAMK4, TC2N, LEF1, BCL11B, ZEB1, CD96, ITGA6 |
| P2 | 212 | RIN2, GLT1D1, CLEC7A, WDFY3, PLXDC2, SLC8A1, KLF4, SLC24A4 |
| P3 | 137 | LINC02397, COBLL1, CD19, FCRLA, FCRL5, VPREB3, IGHD, KLHL14 |
| P4 | 100 | PTGDR, PPP2R2B, PDGFD, CST7, HOPX, XCL2, JAKMIP2, KLRD1 |
| P5 | 75 | MEF2C, SYK, TBC1D9, KYNU, WDFY4, LRRK2, IRF8, FAM49A |
Started: 2026-11-28T19:13:00.531546Z | Wall time: 2.117 s
Across the metacells, most of the variable genes fall into programs, and the output above counts them; the remaining genes correlate too weakly with the rest of their program, or form groups too small to count as a program. Each program lists its genes by membership, the correlation of a gene with the mean profile of the program’s other genes, so the leading genes are the most typical. The leading genes suggest identities: T-cell, monocyte, B-cell, cytotoxic and antigen-presenting genes. The rest of the page calls the programs the T-cell, monocyte, B-cell, cytotoxic and antigen-presentation programs, and the next table confirms each name by the population where the program is most active. Score each program in every analyzed cell with AUCell, as for the regulons.
# Draw a table of population averages as a heatmap, populations in lineage order.
def heatmap(table, title, xlabel, label, **colors):
table = table.loc[populations]
figure, axis = plt.subplots(figsize=(0.45 * table.shape[1] + 3, 3.8))
image = axis.imshow(table.to_numpy(), aspect="auto", **colors)
axis.set_xticks(range(table.shape[1]), table.columns, rotation=90)
axis.set_yticks(range(table.shape[0]), table.index)
axis.set_xlabel(xlabel)
axis.set_title(title)
figure.colorbar(image, ax=axis, label=label)
figure.tight_layout()
plt.show()
# Score each program in every analyzed cell with AUCell, and average the scores
# within each population.
program_auc = ds.scores.aucell(programs, cells, features=run["feature_universe"], tmin=10)
program_means = ds.scores.load(program_auc).to_pandas().groupby(cell_type).mean()
heatmap(program_means, "Gene program activity", "Program", "mean AUCell", cmap="magma")
# Name each program after the population where it is most active, and check
# that the five programs take the five names that the text uses.
program_names = program_means.idxmax().map({
"CD4 T cell": "T-cell",
"CD8 T cell": "T-cell",
"CD14 monocyte": "monocyte",
"B cell": "B-cell",
"NK cell": "cytotoxic",
"Plasmacytoid DC": "antigen-presentation",
})
assert set(program_names) == {"T-cell", "monocyte", "B-cell", "cytotoxic", "antigen-presentation"}
assert program_names.is_unique
# List each program's name and the population where it is most active, with
# its mean score there.
pd.DataFrame({
"name": program_names,
"most active in": program_means.idxmax(),
"mean AUCell": program_means.max().round(2),
}).T
| P1 | P2 | P3 | P4 | P5 | |
|---|---|---|---|---|---|
| name | T-cell | monocyte | B-cell | cytotoxic | antigen-presentation |
| most active in | CD8 T cell | CD14 monocyte | B cell | NK cell | Plasmacytoid DC |
| mean AUCell | 0.2 | 0.42 | 0.22 | 0.25 | 0.31 |
Started: 2026-11-28T19:13:02.650715Z | Wall time: 0.671 s
Each program is most active in the population that its genes suggest: the monocyte program in CD14 monocytes, the B-cell program in B cells, and the cytotoxic program in NK cells. The T-cell program is active in both CD4 and CD8 T cells, and the antigen-presentation program spans the antigen-presenting cells: plasmacytoid DCs, B cells, monocytes, and dendritic cells.
The programs were found without any factor, so compare them with the regulons: a program that shares many genes with a regulon may be regulated by that regulon’s factor. A hypergeometric test asks whether each program shares more genes with each regulon than chance predicts, counting only the variable genes, and the table lists each program’s three most significant regulons at a Benjamini-Hochberg q-value below 0.05, with the number of shared genes.
# Test every program for overlap with every regulon among the variable genes.
overlaps = rg.set_overlaps(programs, regulons, program_genes)
# List the three regulons that overlap each program most significantly, with
# the number of genes they share.
shared = overlaps[overlaps["q_value"] < 0.05].sort_values("p_value").groupby("query").head(3)
shared = shared.assign(regulon=shared["reference"] + " (" + shared["overlap"].astype(str) + ")")
# Check that the most significant regulon of each lineage program is the regulon
# of its lineage factor, as the text says.
lineage_factors = {
"T-cell": "ETS1(+)",
"monocyte": "KLF4(+)",
"B-cell": "BCL11A(+)",
"cytotoxic": "TBX21(+)",
}
most_significant = shared.groupby("query")["reference"].first().rename(index=program_names)
assert all(most_significant[name] == factor for name, factor in lineage_factors.items())
shared.groupby("query")["regulon"].agg(", ".join).to_frame("overlapping regulons (shared genes)")| overlapping regulons (shared genes) | |
|---|---|
| query | |
| P1 | ETS1(+) (53), BACH2(+) (38), PLAG1(+) (16) |
| P2 | KLF4(+) (79), BACH1(+) (69), KLF6(+) (65) |
| P3 | BCL11A(+) (13), THRB(+) (10) |
| P4 | TBX21(+) (29), EOMES(+) (7), NFATC2(+) (12) |
| P5 | KLF4(+) (24), SP3(+) (10), RXRA(+) (17) |
Started: 2026-11-28T19:13:03.324046Z | Wall time: 0.049 s
The overlaps tie the programs to lineage factors: each lineage program shares genes with the regulon of a known lineage factor, and the table gives the pairs with their numbers of shared genes.
A second route needs no regulons: test each program’s own genes for motif enrichment with the cisTarget database that pruned the regulons, which rates each motif by a normalized enrichment score (NES). Large programs yield many weakly enriched motifs, and one motif can be annotated to several factors, so keep the factors whose own expression follows the program across metacells, with a Pearson correlation above 0.6.
# Test each program's genes for enriched motifs, and correlate each factor with its program.
program_tfs = rg.program_regulators(programs, database, annotations, profiles=profiles)
# Keep each factor's top motif per program (rows come sorted by NES) and the well-correlated factors.
program_tfs = program_tfs.drop_duplicates(["program", "TF"])
supported = program_tfs[program_tfs["correlation"] > 0.6]
# Order each program's factors from the best correlated.
supported = supported.sort_values(["program", "correlation"], ascending=[True, False])
# Check, as the text says, that most programs have a factor that passes the
# filter; that the T-cell program has a factor that both routes nominate; that
# the two routes put different factors first for the antigen-presentation
# program; and that no factor of the B-cell program passes the filter, and one
# of the cytotoxic program does, below a correlation of 0.65.
by_overlap = shared["reference"].str.removesuffix("(+)").groupby(shared["query"]).agg(list)
by_overlap = by_overlap.rename(index=program_names)
by_motif = supported.groupby("program")["TF"].agg(list).rename(index=program_names)
assert len(by_motif) > len(program_names) / 2
assert not set(by_overlap["T-cell"]).isdisjoint(by_motif["T-cell"])
assert by_overlap["antigen-presentation"][0] != by_motif["antigen-presentation"][0]
assert "B-cell" not in by_motif.index
cytotoxic = supported[supported["program"].map(program_names) == "cytotoxic"]
assert len(cytotoxic) == 1 and cytotoxic["correlation"].iloc[0] < 0.65
# List the three best-correlated factors of each program.
supported.groupby("program").head(3)[["program", "TF", "motif", "NES", "correlation"]].round(2).reset_index(drop=True)| program | TF | motif | NES | correlation | |
|---|---|---|---|---|---|
| 0 | P1 | ETS1 | tfdimers__MD00364 | 3.34 | 0.91 |
| 1 | P1 | IKZF3 | metacluster_133.2 | 3.03 | 0.86 |
| 2 | P1 | KLF12 | metacluster_133.2 | 3.03 | 0.78 |
| 3 | P2 | KLF4 | tfdimers__MD00569 | 3.02 | 0.94 |
| 4 | P2 | NFE2 | tfdimers__MD00569 | 3.02 | 0.85 |
| 5 | P2 | RXRA | tfdimers__MD00569 | 3.02 | 0.85 |
| 6 | P4 | GFI1 | tfdimers__MD00264 | 3.12 | 0.61 |
| 7 | P5 | PLAGL1 | metacluster_133.2 | 3.04 | 0.83 |
| 8 | P5 | KLF4 | tfdimers__MD00242 | 3.40 | 0.80 |
| 9 | P5 | SPI1 | metacluster_24.2 | 3.32 | 0.78 |
Started: 2026-11-28T19:13:03.374241Z | Wall time: 0.683 s
Most programs have an enriched motif whose factor’s expression follows the program, and the table shows the best correlated factors of each program. For the T-cell program the two routes agree: a factor that shares genes with the program is also nominated by a motif enriched in the program, and its expression follows the program across metacells. Some factors owe their motif evidence to one shared motif cluster, so only their expression tells these factors apart. For the antigen-presentation program the two routes put different factors first: the motifs nominate some factors, while the most significant shared genes point mostly to others. The B-cell program has no motif factor that passes the filter, and the cytotoxic program has only one, close to the filter, although both programs share genes with their lineage regulons. A factor that both routes nominate is a stronger candidate than one from either route alone, and binding data for that factor near the program’s genes can test the candidate.
Score motif accessibility in the same cells¶
chromVAR asks whether a cell has more ATAC fragments in the peaks that hold a motif than the cell’s sequencing depth and those peaks’ average accessibility predict Schep et al., 2017. chromVAR compares each motif’s peaks with background peaks of similar GC content and accessibility, and reports the difference as a z-score for each cell. First find the peaks that hold each motif and assign them to the factor that the motif is named after; a factor’s set of peaks is its cistrome. To keep the page short, scan the first JASPAR motif of each of 18 factors: immune regulators and the ubiquitous insulator protein CTCF. Scan the whole collection to look for new factors.
# Use every peak with a fragment among the analyzed cells; their ids give their
# coordinates as chrom:start-end.
peaks = ds.features.detected(cells, from_assay="ATAC", min_cells=1)
selected = np.asarray(ds.artifacts.load(peaks)["values"][:], dtype=bool)
peak_ids = np.asarray(ds.ATAC.feats.fetch_all("ids")).astype(str)[selected]
# Take the first JASPAR motif of each factor in a panel of immune regulators and CTCF.
factors = ["SPI1", "CEBPA", "CEBPB", "IRF8", "KLF4", "PAX5", "EBF1", "POU2F2", "TBX21",
"EOMES", "RUNX3", "GATA3", "TCF7", "LEF1", "CTCF", "IRF4", "MEF2C", "NFKB1"]
first_motif = {}
for motif in rg.read_jaspar_motifs(jaspar):
first_motif.setdefault(motif.name.upper(), motif)
motifs = [first_motif[name] for name in factors if name in first_motif]
# Find the peaks that hold a match of each motif on either strand, and assign
# them to the factor that the motif is named after.
with rg.IndexedFasta(genome_fa) as genome:
matches = rg.match_motifs(peak_ids, genome, motifs)
cistromes = rg.cistromes_from_motifs(matches, rg.motif_annotations(motifs))
# Count the peaks with a match of each factor's motif.
print(f"{len(motifs)} motifs scanned over {len(peak_ids):,} peaks")
cistromes["source"].value_counts().to_frame("peaks with a match").T18 motifs scanned over 98,316 peaks
| source | SPI1 | KLF4 | CTCF | MEF2C | EBF1 | RUNX3 | IRF8 | CEBPA | POU2F2 | EOMES | NFKB1 | IRF4 | TCF7 | GATA3 | TBX21 | LEF1 | CEBPB | PAX5 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| peaks with a match | 43155 | 31982 | 28507 | 26353 | 17695 | 13727 | 12806 | 12461 | 12395 | 11427 | 11343 | 11162 | 10664 | 9868 | 8928 | 8819 | 3293 | 3108 |
Started: 2026-11-28T19:13:04.059684Z | Wall time: 18.028 s
# Score the accessibility of each factor's motif peaks in every analyzed cell with chromVAR.
motif_activity = ds.scores.chromvar(
cistromes,
cells,
from_assay="ATAC",
features=peaks,
genome=genome_fa,
)
# Average each factor's z-scores within each population, and show them on a
# color scale centered on zero.
motif_means = ds.scores.load(motif_activity).to_pandas().groupby(cell_type).mean()
heatmap(
motif_means,
"Motif accessibility",
"Factor of the scanned JASPAR motif",
"mean chromVAR z-score",
cmap="RdBu_r",
vmin=-5,
vmax=5,
)
# Check, as the text says, that the PAX5 and KLF4 motifs stay within 1 of zero
# in every population, and that the EBF1 motif is only weakly positive in B
# cells: above 0, but not among their three most accessible motifs.
assert motif_means[["PAX5", "KLF4"]].abs().max().max() < 1
assert motif_means.loc["B cell", "EBF1"] > 0
assert "EBF1" not in motif_means.loc["B cell"].nlargest(3).index
# List the three most accessible motifs of each population with their mean z-scores.
motif_means.loc[populations].apply(
lambda scores: ", ".join(f"{name} {value:.1f}" for name, value in scores.nlargest(3).items()),
axis=1,
).to_frame("most accessible motifs (mean z-score)")
| most accessible motifs (mean z-score) | |
|---|---|
| CD14 monocyte | CEBPA 8.0, CEBPB 5.1, SPI1 4.4 |
| CD16 monocyte | SPI1 5.7, CEBPA 5.3, CEBPB 3.5 |
| Dendritic cell | SPI1 7.6, CEBPA 2.8, CEBPB 1.6 |
| Plasmacytoid DC | SPI1 4.0, IRF8 2.4, IRF4 2.2 |
| B cell | POU2F2 4.0, IRF4 2.5, IRF8 2.3 |
| CD4 T cell | CTCF 2.0, TCF7 1.6, LEF1 1.4 |
| CD8 T cell | CTCF 1.6, RUNX3 1.3, TCF7 1.2 |
| NK cell | TBX21 3.5, EOMES 3.2, RUNX3 1.4 |
Started: 2026-11-28T19:13:22.090576Z | Wall time: 19.593 s
Outside the T cells, each population’s most accessible motifs belong to regulators of its lineage. The CEBPA and CEBPB motifs are most accessible in monocytes, and the most specific regulons of the CD16 monocytes include CEBPA and CEBPB. SPI1 is most accessible in the myeloid populations and plasmacytoid DCs, POU2F2 in B cells, IRF4 and IRF8 in B cells and plasmacytoid DCs, and TBX21 and EOMES in NK cells, where the TBX21 and EOMES regulons are also among the most specific. In T cells no motif stands out: the most accessible, among them the ubiquitous CTCF, have low scores. Related factors share motifs, so each column measures a motif family rather than one factor. A motif can also miss its factor: the PAX5 motif stays near zero in B cells, the EBF1 motif is only weakly positive there although the EBF1 regulon is among the most specific of B cells, and the KLF4 motif stays near zero in every population although the KLF4 regulon shares many genes with the monocyte program. A motif without a deviation therefore says little about its factor’s activity.
Score CUT&RUN binding sites¶
A CUT&RUN experiment for one factor maps where that factor was bound, without relying on a motif. Map the SPI1 peaks from primary human monocytes onto the ATAC peaks and score them with chromVAR in the same way. Any set of regions works: CUT&Tag or ChIP-seq peaks, or the peaks of another dataset.
# Map the SPI1 CUT&RUN peaks onto the ATAC peaks.
binding = rg.binding_cistromes({"SPI1": spi1_cutrun}, peak_ids)
print(f"{len(binding):,} ATAC peaks overlap an SPI1 CUT&RUN peak")
# Score the accessibility of the bound peaks in every analyzed cell with chromVAR.
bound_activity = ds.scores.chromvar(
binding,
cells,
from_assay="ATAC",
features=peaks,
genome=genome_fa,
)
# Compare the mean z-scores of the bound peaks and of the SPI1 motif peaks in each population.
bound_z = ds.scores.load(bound_activity).to_pandas()["SPI1"]
spi1_scores = pd.DataFrame({
"SPI1 CUT&RUN peaks": bound_z.groupby(cell_type).mean(),
"SPI1 motif": motif_means["SPI1"],
}).loc[populations]
# Check, as the text says, that far fewer peaks, under a quarter, overlap an
# SPI1 CUT&RUN peak than hold the SPI1 motif; that the bound peaks score higher
# than the motif in monocytes and dendritic cells and lower in T cells; and
# that they score no higher in plasmacytoid DCs and B cells, where the motif
# scores above 0.
assert len(binding) < (cistromes["source"] == "SPI1").sum() / 4
gain = spi1_scores["SPI1 CUT&RUN peaks"] - spi1_scores["SPI1 motif"]
assert (gain[["CD14 monocyte", "CD16 monocyte", "Dendritic cell"]] > 0).all()
assert (gain[["CD4 T cell", "CD8 T cell"]] < 0).all()
assert (gain[["Plasmacytoid DC", "B cell"]] <= 0).all()
assert (spi1_scores.loc[["Plasmacytoid DC", "B cell"], "SPI1 motif"] > 0).all()
spi1_scores.round(2)2,519 ATAC peaks overlap an SPI1 CUT&RUN peak
| SPI1 CUT&RUN peaks | SPI1 motif | |
|---|---|---|
| CD14 monocyte | 10.70 | 4.38 |
| CD16 monocyte | 10.75 | 5.69 |
| Dendritic cell | 11.30 | 7.62 |
| Plasmacytoid DC | 0.32 | 3.97 |
| B cell | -1.34 | 1.30 |
| CD4 T cell | -6.88 | -3.65 |
| CD8 T cell | -6.82 | -3.66 |
| NK cell | -4.64 | -2.68 |
Started: 2026-11-28T19:13:41.687142Z | Wall time: 16.546 s
Far fewer peaks overlap an SPI1 CUT&RUN peak than hold a match of the SPI1 motif, as the outputs above count. These monocyte binding sites separate myeloid cells from lymphocytes more sharply than the SPI1 motif: their mean z-scores are higher in monocytes and dendritic cells and lower in T cells than the motif’s, which also counts sites that SPI1 does not occupy in monocytes. Plasmacytoid DCs and B cells, where the motif is accessible, show no gain at the monocyte sites. Binding sites differ between cell types, so binding data describe the cell type that was profiled, here monocytes.
The methods page compares these steps with pySCENIC, chromVAR, and Hotspot, and the regulons API reference lists every function.
- Aibar, S., González-Blas, C. B., Moerman, T., Huynh-Thu, V. A., Imrichova, H., Hulselmans, G., Rambow, F., Marine, J.-C., Geurts, P., Aerts, J., van den Oord, J., Atak, Z. K., Wouters, J., & Aerts, S. (2017). SCENIC: single-cell regulatory network inference and clustering. Nature Methods, 14(11), 1083–1086. 10.1038/nmeth.4463
- Schep, A. N., Wu, B., Buenrostro, J. D., & Greenleaf, W. J. (2017). chromVAR: inferring transcription-factor-associated accessibility from single-cell epigenomic data. Nature Methods, 14(10), 975–978. 10.1038/nmeth.4401
- Moerman, T., Aibar Santos, S., Bravo González-Blas, C., Simm, J., Moreau, Y., Aerts, J., & Aerts, S. (2018). GRNBoost2 and Arboreto: efficient and scalable inference of gene regulatory networks. Bioinformatics, 35(12), 2159–2161. 10.1093/bioinformatics/bty916
- Van de Sande, B., Flerin, C., Davie, K., De Waegeneer, M., Hulselmans, G., Aibar, S., Seurinck, R., Saelens, W., Cannoodt, R., Rouchon, Q., Verbeiren, T., De Maeyer, D., Reumers, J., Saeys, Y., & Aerts, S. (2020). A scalable SCENIC workflow for single-cell gene regulatory network analysis. Nature Protocols, 15(7), 2247–2276. 10.1038/s41596-020-0336-2