Gene set analysis and GRN inference on PBMCs¶
Python port of the R vignette Gene set analysis and GRN inference on PBMCs. Original author: Gregor Lueg.
Intro¶
This vignette demonstrates the gene set scoring, spatial autocorrelation and
gene regulatory network (GRN) inference methods available in bixverse. It
picks up where the PBMC vignette left off: QC,
normalisation, PCA, nearest neighbours, clustering and UMAP are all assumed
to be done already. If you have not read the
design choices and the
introductory vignette, please do so first.
The methods fall into three broad categories:
- The first, module scores, AUCell and VISION, takes pre-defined gene sets and scores them per cell. ULM and MLM do the same for signed networks and show up after SCENIC, scoring its TF-to-gene links.
- The second, Hotspot and SCENIC, discovers gene programmes and regulatory relationships from the data itself.
- The third, NMF, also discovers gene programmes, via matrix factorisation, which is a different angle from SCENIC and Hotspot.
The LDA topic models over the binarised regulons are not ported to Python yet, so that part of the story is missing here.
We use the PBMC3k dataset throughout. At 2,700 cells this is likely too small for the GRN methods to produce biologically meaningful results, but it is large enough to show the API and the workflow end to end. On real datasets with tens of thousands of cells the same code applies unchanged.
import tempfile
import urllib.request
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import polars as pl
import bixverse as bv
import bixverse.embed
from bixverse.params import (
AucellParams,
LmActivityParams,
NeighboursParams,
NmfConsensusParams,
ScenicParams,
VisionParams,
)
Rebuilding the processed object¶
We reconstruct the processed SingleCells object from the PBMC vignette: it
downloads the data, runs QC, HVG selection, PCA, neighbour computation,
Leiden clustering and UMAP.
pbmc3k_path = bv.io.download_pbmc3k()
tempdir_pbmc = tempfile.TemporaryDirectory()
sc = bv.io.load_mtx(
Path(tempdir_pbmc.name) / "pbmc3k",
bv.io.get_cell_ranger_params(pbmc3k_path),
)
sc.rename_var_col("column1", "gene_symbol")
var = sc.var()
ensembl_to_symbol = dict(zip(var["gene_id"], var["gene_symbol"], strict=True))
symbol_to_ensembl = dict(zip(var["gene_symbol"], var["gene_id"], strict=True))
# gene set proportions for QC
gs_of_interest = {
"MT": var.filter(pl.col("gene_symbol").str.contains("^MT-"))["gene_id"].to_list(),
"Ribo": var.filter(pl.col("gene_symbol").str.contains("^RP[SL]"))[
"gene_id"
].to_list(),
}
bv.qc.gene_set_proportions(sc, gs_of_interest, streaming=False)
# MAD QC
qc_df = sc.obs(cols=["cell_id", "lib_size", "nnz", "MT"])
qc = bv.qc.run_cell_qc(
{
"log10_lib_size": np.log10(qc_df["lib_size"].to_numpy()),
"log10_nnz": np.log10(qc_df["nnz"].to_numpy()),
"MT": qc_df["MT"].to_numpy(),
},
sc.cells_to_keep,
directions={"log10_lib_size": "twosided", "log10_nnz": "twosided", "MT": "above"},
threshold=3.0,
)
sc.add_obs(pl.DataFrame({"cell_idx": qc.cell_idx, "outlier": qc.combined}))
sc.set_cells_to_keep(qc.cell_idx[~qc.combined])
# HVG, PCA, neighbours, clustering, UMAP
bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30, sparse_svd=True)
bv.graph.find_neighbours(
sc, neighbours_params=NeighboursParams(knn_method="exhaustive")
)
bv.graph.find_clusters(sc, res=1.5, name="leiden_clusters")
bv.embed.umap(sc)
# UMAP coordinates for reuse
umap_df = bv.pl.extract_embedding_data(sc, "umap").rename(
{"dim_1": "umap_1", "dim_2": "umap_2"}
)
sc
Text pass (real): 1 buckets, ~2700 cells/bucket Text pass done: 30.15ms (cell-major order) Genes passing QC: 11_139 / 32_738 Cells passing QC: 2_700 / 2_700 Writing pass: 1 buckets, no sort Wrote bucket 1/1 (100%) Writing pass done: 11.98ms Converting the cell-based data into the gene-based format.
Counted 2_269_399 non-zeros over 11_139 genes in 1.27ms; converting in 1 phase(s). Phase 1/1: genes 0-11139, scatter 2.02ms, compress + write 6.30ms Conversion into gene-friendly format done: 10.32ms
Load in data: 3.11ms Finished the gene set proportion calculations: 700.12µs
HVG (VST): 11_139 genes, 1 batches, 1 disk block(s) HVG (VST): Calculated gene statistics in 3.61ms HVG (VST): Fitted Loess in 399.62µs HVG (VST): Standardised variance in 816.50µs (1_174 gene(s) re-read for the clip) HVG (VST): Total run time -> 4.86ms Using sparse SVD solving on scaled data on 2000 HVG.
Sparse PCA: Loaded in data in 6.56ms Sparse PCA: finished the data preparations in 828.62µs
Sparse PCA: finished calculations in 163.14ms Sparse PCA: total run time -> 170.58ms Generating kNN data with exhaustive method.
Building Exhaustive index ... ... built Exhaustive index in 121.38µs Generated Exhaustive index: 127.75µs Querying Exhaustive index (self) ... ... queried Exhaustive index (self) in 3.66ms Queried Exhaustive index: 3.69ms Generating the snn graph.
Added 0 edges to reconnect components that pruning cut off.
Built the Snn { similarity: Jaccard, prune: 0.0625, rescue: true } graph: 8.43ms
SingleCells( dir='/var/folders/l0/d50zd8812jg94mhtl8t2swfc0000gn/T/tmp5ozijpge/pbmc3k', cells=2700 (kept 2490), genes=11139, hvg=True, pca=True, embeddings=['umap'], knn=True, graph=True, magic=False, residuals=False, stale=none )
The scores below come back as a cells x gene sets matrix. To look at several of them on the UMAP at once, a small facet helper:
def plot_scores_on_umap(scores, label, scale=False, ncol=2):
"""Facet the columns of an `ScMatrixRes` on the UMAP."""
df = scores.frame().join(umap_df, on="cell_id")
n = len(scores.columns)
nrow = int(np.ceil(n / ncol))
fig, axes = plt.subplots(nrow, ncol, figsize=(4.5 * ncol, 4 * nrow), squeeze=False)
for ax, col in zip(axes.flat, scores.columns, strict=False):
v = df[col].to_numpy()
if scale:
v = (v - v.min()) / (v.max() - v.min())
pts = ax.scatter(df["umap_1"], df["umap_2"], c=v, s=1, cmap="viridis")
ax.set_title(col)
ax.set_xticks([])
ax.set_yticks([])
fig.colorbar(pts, ax=ax, label=label)
for ax in axes.flat[n:]:
ax.set_visible(False)
fig.tight_layout()
Gene set scoring¶
Module scores¶
The simplest approach to gene set activity is the module score from Tirosh et al. (2016): for each cell, compute the mean expression of the gene set and subtract the mean expression of a size-matched control set drawn from the same expression bins. We will just use some lineage-specific genes to have pretty visualisations.
lineage_symbols = {
"T cell": [
"CD3D", "CD3E", "CD3G", "CD2", "IL7R", "CD7", "LEF1", "TCF7", "LTB", "TRAC",
],
"Cytotoxic NK": [
"NKG7", "GNLY", "GZMA", "GZMB", "GZMH", "PRF1", "CST7", "KLRD1", "KLRB1",
"FGFBP2",
],
"B cell": [
"CD79A", "CD79B", "MS4A1", "BANK1", "IGHM", "IGHD", "CD74", "HLA-DQA1",
"TCL1A", "VPREB3",
],
"Monocyte": [
"CD14", "LYZ", "S100A8", "S100A9", "S100A12", "CST3", "FCN1", "VCAN",
"MNDA", "TYROBP",
],
} # fmt: skip
# drop the symbols not in the data
lineage_sets = {
name: [symbol_to_ensembl[s] for s in genes if s in symbol_to_ensembl]
for name, genes in lineage_symbols.items()
}
module_scores = bv.pathways.module_scores(sc, lineage_sets)
module_scores
Calculating the average expression across the cells. Finished the calculation of the avg gene expression in 9.98ms Calculating the module scores now. Finished the calculation of the modules in 12.67ms Total runtime: 22.67ms
ScMatrixRes(n_cells=2490, n_sets=4, index_col='cell_idx')
# scale the scores to make them more comparable across sets
plot_scores_on_umap(module_scores, "Module score (scaled)", scale=True)
plt.show()
Let's imagine you want to add the scores to the internal DB. There are
helpers for this, too: get_data() turns the scores into an obs frame keyed
on cell_idx, which add_obs() takes as is.
sc.add_obs(bv.pathways.get_data(module_scores))
sc.obs(filtered=True).head()
| cell_idx | cell_id | nnz | lib_size | to_keep | MT | Ribo | outlier | leiden_clusters | T cell | Cytotoxic NK | B cell | Monocyte |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
| u32 | str | f64 | f64 | bool | f64 | f64 | bool | i32 | f64 | f64 | f64 | f64 |
| 0 | "AAACATACAACCAC-1" | 778.0 | 2418.0 | true | 0.03019 | 0.437138 | false | 0 | 0.420012 | -0.218353 | -0.255588 | -0.710299 |
| 1 | "AAACATTGAGCTAC-1" | 1346.0 | 4896.0 | true | 0.03799 | 0.424632 | false | 2 | -0.606512 | -0.418591 | 1.358866 | -0.64836 |
| 2 | "AAACATTGATCAGC-1" | 1126.0 | 3144.0 | true | 0.008906 | 0.317112 | false | 0 | 0.362747 | -0.334271 | -0.33318 | -0.630501 |
| 3 | "AAACCGTGCTTCCG-1" | 953.0 | 2632.0 | true | 0.017477 | 0.243161 | false | 3 | -1.020487 | -0.21785 | 0.126866 | 1.298537 |
| 4 | "AAACCGTGTATGCG-1" | 520.0 | 979.0 | true | 0.012257 | 0.149132 | false | 6 | -0.545306 | 1.86181 | -0.123337 | -0.432933 |
As we can appreciate, this has now added the new columns.
AUCell¶
AUCell ranks genes within each
cell by expression and summarises where the gene set lands in that ranking.
More robust to outliers than a simple mean. bixverse gives you three
statistics via AucellParams, all reading the same ranking but weighting it
differently:
"recovery", the default, is the recovery-curve AUC under a rank cutoff, i.e. what Aibar et al. published. Top-heavy: only genes inside the topmax_rankcontribute, so it is the sharper instrument for marker sets and the one to use for SCENIC."wilcox"is the AUC from the Mann-Whitney U statistic over the full ranking. Its null sits at 0.5 whatever the gene set size, which makes it a safe pick for pathway activity, but the flatter score splits less cleanly into on/off populations than"recovery"(the four lineage scores below still binarise as bimodal)."ap"is average precision. Most top-heavy of the three, but its null tracks gene set prevalence, so don't compare raw values across sets of different size unless you switchstandardiseon.
We use the "wilcox" here.
auc_scores = bv.pathways.aucell(
sc, lineage_sets, aucell_params=AucellParams(auc_type="wilcox")
)
plot_scores_on_umap(auc_scores, "AUC")
plt.show()
Loaded in data: 1.94ms Ranked within cells and calculated AUCs 2.23ms
VISION with spatial autocorrelation¶
Scoring gene sets is useful, but a natural follow-up question is: are these scores spatially structured on the cell neighbourhood graph, or just noise? VISION provides a permutation-based test of spatial autocorrelation (Geary's C) on the kNN graph. Gene sets with significant autocorrelation are those whose activity varies smoothly across cell neighbourhoods, a strong indication that the signal is biologically meaningful rather than random.
VISION expects gene sets in a signed format with pos and (optionally) neg
components. In the case of our cell lineage genes, we could use the other
cell type's markers as negatives, but we will just leave it blank here.
vision_gs = {name: {"pos": genes} for name, genes in lineage_sets.items()}
vision_res = bv.pathways.vision_w_autocor(
sc, vision_gs, "pca", vision_params=VisionParams(n_perm=500)
)
vision_res.auto_cor
Generating 5 random gene set clusters with a total of 500 permutations.
Using provided kNN graph.
Calculating the VISION scores of the actual gene sets. Loaded in data: 1.98ms Calculated VISION scores: 1.51ms Calculating the VISION scores of the permuted gene sets. Loaded in data: 1.93ms Calculated VISION scores: 2.08ms Completed random signatures for cluster 1 / 4 Loaded in data: 1.89ms Calculated VISION scores: 1.98ms Completed random signatures for cluster 2 / 4 Loaded in data: 1.78ms Calculated VISION scores: 2.03ms Completed random signatures for cluster 3 / 4 Loaded in data: 1.83ms Calculated VISION scores: 1.86ms Completed random signatures for cluster 4 / 4 Computed KNN weights: 118.71µs Calculated pathway consistency: 265.17µs Calculated p-values: 35.51ms
| gene_set_name | auto_cor | p_val | fdr |
|---|---|---|---|
| str | f64 | f64 | f64 |
| "T cell" | 0.772286 | 0.001996 | 0.002661 |
| "Cytotoxic NK" | 0.460568 | 0.015968 | 0.015968 |
| "B cell" | 0.607958 | 0.001996 | 0.002661 |
| "Monocyte" | 0.60744 | 0.001996 | 0.002661 |
Unsurprisingly, all of these gene sets show highly significant spatial correlation.
Hotspot¶
Where the methods above test pre-defined gene sets, Hotspot (DeTomaso & Yosef, 2021) discovers gene programmes de novo by testing each gene for spatial autocorrelation on the kNN graph and then grouping the significant genes by their local correlation structure.
Gene autocorrelation¶
The first step computes Geary's C for every gene against the neighbour graph. Genes with significant autocorrelation are those whose expression varies smoothly across neighbouring cells, i.e., genes that mark spatially coherent programmes.
hotspot_autocor = bv.pathways.hotspot_autocor(sc).with_columns(
gene_symbol=pl.col("gene_id").replace_strict(ensembl_to_symbol)
)
hotspot_autocor.sort("fdr").head(25)
Using provided kNN graph. Loaded in data: 8.50ms Finished the calculations: 50.44ms
| gene_id | gearys_c | z_score | pval | fdr | gene_symbol |
|---|---|---|---|---|---|
| str | f64 | f64 | f64 | f64 | str |
| "ENSG00000162444" | 0.283677 | 43.792576 | 0.0 | 0.0 | "RBP7" |
| "ENSG00000142676" | 0.225966 | 45.558983 | 0.0 | 0.0 | "RPL11" |
| "ENSG00000126709" | 0.279073 | 41.438103 | 0.0 | 0.0 | "IFI6" |
| "ENSG00000119535" | 0.305277 | 54.669071 | 0.0 | 0.0 | "CSF3R" |
| "ENSG00000234184" | 0.28997 | 46.083492 | 0.0 | 0.0 | "RP5-887A10.1" |
| … | … | … | … | … | … |
| "ENSG00000116667" | 0.197774 | 42.426453 | 0.0 | 0.0 | "C1orf21" |
| "ENSG00000143947" | 0.369905 | 66.667587 | 0.0 | 0.0 | "RPS27A" |
| "ENSG00000115523" | 0.602019 | 156.346664 | 0.0 | 0.0 | "GNLY" |
| "ENSG00000153563" | 0.245235 | 51.12196 | 0.0 | 0.0 | "CD8A" |
| "ENSG00000172116" | 0.29926 | 59.668419 | 0.0 | 0.0 | "CD8B" |
You should get a set of well known cell type markers here...
Gene-gene local correlations and modules¶
Taking the significant genes forward, we compute pairwise local correlations and cluster them into modules. Each module represents a group of genes that are not only individually autocorrelated but also co-vary locally, a much stronger signal than global correlation alone.
sig_genes = hotspot_autocor.filter(pl.col("fdr") <= 0.05)["gene_id"].to_list()
hotspot_cor = bv.pathways.hotspot_gene_cor(sc, genes_to_take=sig_genes, verbose=True)
hotspot_cor
Using provided kNN graph. Loading 2786 genes... Loaded data in 3.30ms Centering gene expression... Centered in 3.06ms Computing wy, eg2 and per-gene max values... Computed wy/eg2/maxs in 10.66ms Computing pairwise correlations (GEMM)... Computed GEMM in 24.81ms
Done!
Hotspot(n_genes=2786, n_cells=2490, n_modules=None, n_assigned=None)
This returns a Hotspot result. Let's add the membership.
Not ported to Python yet: the module heatmap (plot() on a Hotspot).
hotspot_cor = bv.pathways.generate_hotspot_membership(hotspot_cor)
hotspot_cor
Hotspot(n_genes=2786, n_cells=2490, n_modules=57, n_assigned=1441)
Let's pull out the genes:
hotspot_membership = bv.pathways.get_hotspot_membership(hotspot_cor)
assert hotspot_membership is not None
membership = hotspot_membership.with_columns(
gene_symbol=pl.col("gene_id").replace_strict(ensembl_to_symbol)
).drop_nulls("cluster_member")
membership.sort("cluster_member").head(20)
| gene_id | cluster_member | gene_symbol |
|---|---|---|
| str | i64 | str |
| "ENSG00000197530" | 0 | "MIB2" |
| "ENSG00000189409" | 0 | "MMP23B" |
| "ENSG00000116663" | 0 | "FBXO6" |
| "ENSG00000160050" | 0 | "CCDC28B" |
| "ENSG00000143119" | 0 | "CD53" |
| … | … | … |
| "ENSG00000116667" | 0 | "C1orf21" |
| "ENSG00000134308" | 0 | "YWHAQ" |
| "ENSG00000115956" | 0 | "PLEK" |
| "ENSG00000115523" | 0 | "GNLY" |
| "ENSG00000171596" | 0 | "NMUR1" |
The resulting modules should roughly correspond to the major cell-type programmes in PBMCs (T cell, monocyte, B cell, NK cell signatures, etc.). Let's score the six largest modules with VISION and put them on the UMAP.
hotspot_top_k = 6
# largest by gene count, ties broken by id
top_modules = (
membership.group_by("cluster_member")
.len()
.sort(["len", "cluster_member"], descending=[True, False])
.head(hotspot_top_k)["cluster_member"]
.to_list()
)
hotspot_gene_sets = {
f"module {m}": {
"pos": membership.filter(pl.col("cluster_member") == m)["gene_id"].to_list()
}
for m in top_modules
}
vision_scores_hotspot = bv.pathways.vision(sc, hotspot_gene_sets)
# min max individually for prettier visualisations
plot_scores_on_umap(vision_scores_hotspot, "Vision (scaled)", scale=True, ncol=3)
plt.show()
Loaded in data: 1.77ms Calculated VISION scores: 1.52ms
SCENIC¶
SCENIC infers gene regulatory networks by asking: for each gene, which transcription factors (TFs) best predict its expression? The original implementation uses either random forests or GRNBoost2 (gradient boosted trees) to regress each target gene on all TFs, then extracts feature importances as a proxy for regulatory strength.
The bixverse implementation re-implements this in Rust with several
optimisations that make the RF and ExtraTrees paths substantially faster
than the single-target-at-a-time approach used by GRNBoost2:
- Quantisation: TF expression values are discretised into 256 bins (u8), so histogram construction during tree building operates on single bytes and fits comfortably in L1 cache.
- Multi-output batching: up to 64 target genes share a single tree structure. The histogram construction cost is paid once per node per feature, but the split score aggregates variance reduction across all targets in the batch. This amortises the dominant cost of tree building across targets.
- Correlated gene batching: rather than assigning genes to batches randomly, an optional SVD + k-means step groups co-expressed genes together so that the shared tree structure is more informative for each target in the batch.
- GRNBoost2 with histogram subtraction: for the gradient boosted path (single-target), the code builds full-feature histograms at each node and derives the larger child via parent-minus-smaller subtraction, avoiding a redundant scan of the larger child's samples. OOB early stopping prevents overfitting and is the main source of speedup.
On the 2,700-cell PBMC3k dataset these optimisations are not that noticeable... The data is too small for any method to take long. On datasets with tens of thousands of cells and thousands of TFs, the RF/ET multi-output path comfortably outperforms GRNBoost2. You need to just decide if you are okay with the batching of genes. The big signals get recovered again and again (from empirical testing).
Gene filtering¶
SCENIC first filters genes by minimum total counts and minimum proportion of expressing cells to remove uninformative targets.
scenic_genes = bv.pathways.scenic_gene_filter(
sc, scenic_params=ScenicParams(min_counts=50)
)
len(scenic_genes)
Processed chunk 1 out of 11 for SCENIC inclusion criteria. Processed chunk 2 out of 11 for SCENIC inclusion criteria. Processed chunk 3 out of 11 for SCENIC inclusion criteria. Processed chunk 4 out of 11 for SCENIC inclusion criteria. Processed chunk 5 out of 11 for SCENIC inclusion criteria. Processed chunk 6 out of 11 for SCENIC inclusion criteria. Processed chunk 7 out of 11 for SCENIC inclusion criteria. Processed chunk 8 out of 11 for SCENIC inclusion criteria. Processed chunk 9 out of 11 for SCENIC inclusion criteria. Processed chunk 10 out of 11 for SCENIC inclusion criteria. Processed chunk 11 out of 11 for SCENIC inclusion criteria.
5494
Transcription factor list¶
We need a list of known TFs. The Aerts lab provides a curated list for human
(allTFs_hg38.txt from their
cisTarget resources).
The Python package does not ship a copy yet, so we fetch it from there and
map it to Ensembl IDs.
tf_url = "https://resources.aertslab.org/cistarget/tf_lists/allTFs_hg38.txt"
with urllib.request.urlopen(tf_url) as f:
tf_symbols = f.read().decode().split()
tf_ids = [symbol_to_ensembl[tf] for tf in tf_symbols if tf in symbol_to_ensembl]
len(tf_ids)
1100
GRN inference¶
With genes and TFs in hand, we run the GRN inference step. Here we use random forests with a batch size of 64 to illustrate the multi-output path.
scenic_res = bv.pathways.scenic_grn(
sc,
tf_ids,
genes_to_take=scenic_genes,
scenic_params=ScenicParams(learner_type="randomforest", gene_batch_size=64),
verbose=True,
)
scenic_res
SCENIC: 5494 target genes, 482 TFs, 2490 cells
Loaded, filtered and quantised TF data (n: 482) in: 1.93ms Computing gene loadings: 5494 genes, 2490 subsampled cells, 50 components PCA (streaming): Scaling batch 1/6 (1024 genes each) PCA (streaming): Scaling batch 2/6 (1024 genes each) PCA (streaming): Scaling batch 3/6 (1024 genes each) PCA (streaming): Scaling batch 4/6 (1024 genes each) PCA (streaming): Scaling batch 5/6 (1024 genes each) PCA (streaming): Scaling batch 6/6 (1024 genes each) PCA (streaming): finished scaling in 13.95ms PCA (streaming): finished calculations in 125.85ms PCA (streaming): total run time -> 152.67ms Clustering 5494 genes into 86 groups Read and filtered 5494 target genes in 7.62ms Running SCENIC (RandomForest) on 5494 genes (482 TFs, 2490 cells, 134 batches of up to 64)
Progress: 10% (14 / 134 batches, 1.87s)
Progress: 20% (27 / 134 batches, 3.19s)
Progress: 30% (41 / 134 batches, 4.51s)
Progress: 40% (54 / 134 batches, 6.02s)
Progress: 50% (67 / 134 batches, 7.36s)
Progress: 60% (81 / 134 batches, 8.73s)
Progress: 70% (94 / 134 batches, 9.54s)
Progress: 80% (108 / 134 batches, 10.82s)
Progress: 90% (121 / 134 batches, 12.06s)
Progress: 100% (134 / 134 batches, 13.44s) SCENIC (RandomForest) GRN inference complete in 13.62s
ScenicGrn( n_genes=5494, n_tfs=482, learner='randomforest', tf_to_gene=False, cis_targets=False, )
If you are bored, you can run both methods (learner_type="grnboost2") and
compare the importance scores. You will see very high correlations here (and
can explore the speed differences...)
TF-to-gene refinement¶
The raw importance matrix is large and noisy. The next steps winnow it down
to a candidate regulatory network by keeping only the top TF-gene pairs and
filtering by pairwise expression correlation. Per gene only the TFs with an
importance score >= mean(importance_score) + n_sd * sd(importance_score)
for that gene are kept. Note that n_sd should be adjusted depending on the
learner: RF and ExtraTrees spread importance more evenly across TFs than
GRNBoost2, so a lower threshold keeps more TFs per gene, whereas
GRNBoost2 concentrates importance onto fewer TFs and tolerates n_sd=1.5 or
even n_sd=2. Below we use the strict n_sd=2.0 on the random forest too,
which keeps only the strongest TFs per gene.
scenic_res = bv.pathways.identify_tf_to_genes(scenic_res, n_sd=2.0, verbose=True)
scenic_res = bv.pathways.tf_to_genes_correlations(scenic_res, sc, verbose=True)
tf_gene_df = bv.pathways.get_tf_to_gene(scenic_res).with_columns(
tf_symbol=pl.col("tf").replace_strict(ensembl_to_symbol),
gene_symbol=pl.col("gene").replace_strict(ensembl_to_symbol),
)
tf_gene_df.sort("importance", descending=True).head(5)
Extracting TF to gene associations via per-gene threshold (mean + 2.0 * SD).
Calculating the pairwise correlations between the TFs and genes
Calculating pairwise correlations between the genes of interest. Calculated pairwise correlations in 18.70ms Keeping activating TF <> gene links at |rho| > 0.030
| tf | gene | importance | pairwise_cor | cor_sign | tf_symbol | gene_symbol |
|---|---|---|---|---|---|---|
| str | str | f64 | f64 | i32 | str | str |
| "ENSG00000170345" | "ENSG00000120129" | 0.271169 | 0.341476 | 1 | "FOS" | "DUSP1" |
| "ENSG00000066336" | "ENSG00000114013" | 0.238352 | 0.344213 | 1 | "SPI1" | "CD86" |
| "ENSG00000139187" | "ENSG00000113088" | 0.228556 | 0.258208 | 1 | "KLRG1" | "GZMK" |
| "ENSG00000066336" | "ENSG00000124357" | 0.220842 | 0.285586 | 1 | "SPI1" | "NAGK" |
| "ENSG00000140968" | "ENSG00000226777" | 0.217221 | 0.190514 | 1 | "IRF8" | "KIAA0125" |
CisTarget motif enrichment¶
The final (and optional) step in the SCENIC pipeline validates the predicted
TF-gene links against known motif binding sites. This requires the CisTarget
motif ranking database and motif-to-TF annotation files from the
Aerts lab resources, which
together are roughly 400 MB. The Python package has no downloader or reader
for them yet: tf_to_genes_motif_enrichment() takes the ranking as an
integer matrix (genes x motifs) plus its gene and motif names, and the
annotation as a polars frame with motif, TF and annotationSource. Load
them however you like and the rest looks like this:
scenic_res = bv.pathways.tf_to_genes_motif_enrichment(
scenic_res,
rankings,
rank_genes,
rank_motifs,
annotations,
# we store everything as Ensembl... The SCENIC data has gene symbols,
# hence the need to provide a conversion
gene_id_to_symbol=ensembl_to_symbol,
cis_target_params=CistargetParams(),
only_high_conf_tf=False,
verbose=True,
)
# CisTarget results per TF
bv.pathways.get_cistarget_res(scenic_res).sort("nes", descending=True).head()
# The TF-to-gene table now has an in_leading_edge column indicating which
# genes fall within the motif recovery curve
(
bv.pathways.get_tf_to_gene(scenic_res)
.filter(pl.col("in_leading_edge"))
.sort("importance", descending=True)
.head()
)
CisTarget is not a pass/fail filter on the module. Per enriched motif it
builds a recovery curve, compares it against the mean + 2 SD curve across
every motif in the database, and keeps only the genes above the point of
maximum separation. So expect the regulons coming out of build_regulons()
to be a good deal smaller than the modules going in.
build_regulons() applies that filter, adds the TF back to its own set and
drops anything too small. Since we skipped CisTarget above, we pass
use_leading_edge=False and it carries on without the motif filter. The
regulons that come out are a lot bigger and noisier than a proper SCENIC run
would give you, so read the biology below with that in mind. The API is
identical either way.
regulons = bv.pathways.build_regulons(scenic_res, use_leading_edge=False)
assert regulons is not None
regulon_sizes = pl.Series("size", [len(g) for g in regulons.values()])
print(f"{len(regulons)} regulons")
regulon_sizes.describe()
Built 224 regulons (192 dropped below 10 genes). Median size: 22
224 regulons
| statistic | value |
|---|---|
| str | f64 |
| "count" | 224.0 |
| "null_count" | 0.0 |
| "mean" | 165.276786 |
| "std" | 338.079732 |
| "min" | 10.0 |
| "25%" | 14.0 |
| "50%" | 22.0 |
| "75%" | 121.0 |
| "max" | 2066.0 |
That is what you hand to aucell(), which scores every regulon in every
cell.
auc_regulons = bv.pathways.aucell(sc, regulons, aucell_params=AucellParams())
auc_regulons.shape
Loaded in data: 2.17ms Ranked within cells and calculated AUCs 32.23ms
(2490, 224)
The AUC scores are continuous, and for most downstream purposes you want an
on/off call instead. binarise_regulon_activity() fits a two-component
Gaussian mixture per regulon, compares it against a single Gaussian by BIC,
and puts the threshold at the trough between the two component means.
Regulons that are not bimodal fall back to mean + 2 * sd.
binarised_regulons = bv.pathways.binarise_regulon_activity(auc_regulons)
binary_df = binarised_regulons.binary.rename(
{c: ensembl_to_symbol[c] for c in binarised_regulons.binary.columns[1:]}
)
binarised_regulons.thresholds.with_columns(
regulon=pl.col("regulon").replace_strict(ensembl_to_symbol)
).sort("n_cells_on", descending=True).head()
Binarised 224 regulons, 81 of which were bimodal.
| regulon | threshold | bimodal | n_cells_on |
|---|---|---|---|
| str | f64 | bool | i64 |
| "YEATS4" | 0.03377 | true | 1763 |
| "JUN" | 0.035258 | true | 1748 |
| "RPS4X" | 0.107531 | true | 1711 |
| "RPS10" | 0.102358 | true | 1706 |
| "JUNB" | 0.090377 | true | 1677 |
sc.add_obs(
pl.DataFrame(
{
"cell_idx": auc_regulons.cell_indices.astype(np.uint32),
"SPI1_active": binary_df["SPI1"],
}
)
)
bv.pl.embedding_plot(sc, "umap", "SPI1_active", label_by="SPI1_active")
plt.show()
Not ported to Python yet: the binary regulon heatmap
(extract_binary_heatmap_data() and bixverse.plots::plot_binary_heatmap()).
ULM and MLM on the TF-to-gene links¶
AUCell only looks at whether the targets rank high in a cell. The TF-to-gene
table carries more than that: tf_to_genes_correlations() gave every link a
sign. lm_activity() uses it. It is the
decoupler
ULM/MLM: per cell, regress the normalised counts of all genes on the weights
of a TF's targets and take the t-value as the activity. Activated targets up
and repressed ones down gives a positive score. Normally you would use a
curated network like
CollecTRI here;
the inferred links do for the demo and keep the vignette offline.
lm_net = tf_gene_df.filter(pl.col("cor_sign") != 0).select(
source=pl.col("tf_symbol"), target=pl.col("gene"), weight=pl.col("cor_sign")
)
lm_net.head()
| source | target | weight |
|---|---|---|
| str | str | i32 |
| "CEBPB" | "ENSG00000188290" | 1 |
| "SPI1" | "ENSG00000188290" | 1 |
| "CEBPB" | "ENSG00000187608" | 1 |
| "CEBPD" | "ENSG00000187608" | 1 |
| "SPI1" | "ENSG00000187608" | 1 |
ulm_scores = bv.pathways.lm_activity(
sc, lm_net, lm_params=LmActivityParams(method="ulm")
)
assert isinstance(ulm_scores, bv.pathways.ScMatrixRes)
ulm_scores.shape
Calculated linear model activity scores: 6.53ms
(2490, 307)
sc.add_obs(
bv.pathways.get_data(ulm_scores, columns=["SPI1"]).rename({"SPI1": "SPI1_ulm"})
)
bv.pl.embedding_plot(sc, "umap", "SPI1_ulm", palette="viridis")
plt.show()
method="mlm" fits all TFs in one model, so TFs sharing many targets
compete for the signal instead of both lighting up. It errors on collinear
TFs, i.e., two regulons with identical or proportional target sets. Unlike
decoupler, genes that are zero in every cell stay in the model; on real data
that shifts the scores a little. p_values=True adds p-values and an FDR per
cell, but with thousands of correlated genes in each fit treat them as
descriptive.
mlm_scores = bv.pathways.lm_activity(
sc, lm_net, lm_params=LmActivityParams(method="mlm")
)
assert isinstance(mlm_scores, bv.pathways.ScMatrixRes)
spi1 = ulm_scores.columns.index("SPI1")
np.corrcoef(ulm_scores.values[:, spi1], mlm_scores.values[:, spi1])[0, 1]
Calculated linear model activity scores: 10.45ms
np.float64(0.34555515867066333)
This is how you work with all types of "bag of genes" analyses for single
cell in bixverse.
NMF on single cells¶
The methods so far have all started from either a pre-defined gene set, a
graph-based notion of locality, or a TF-centric regression framework. NMF
(non-negative matrix factorisation) takes yet another angle: it factorises
the expression matrix V ≈ W H into a small number of latent factors, where
W carries non-negative gene loadings and H carries non-negative cell
activations. The non-negativity constraint tends to push the factors into
something interpretable as additive gene programmes rather than abstract
directions of variance like PCA. bixverse implements
HALS (Hierarchical
Alternating Least Squares) in Rust, which converges fast and scales nicely.
A few practical notes before diving in:
- NMF is non-convex: different random initialisations land in different
local optima. The package therefore provides
nmf()for a single run,stabilised_nmf()for multiple restarts, andconsensus_nmf()which takes those restarts and returns the programmes they agree on. The last one is the right default for any serious analysis. - Picking
kis the eternal question. Too small and programmes get smushed together; too large and they fragment into redundant copies.nmf_k_sweep()turns that into something you can actually look at: stability against reconstruction error across a range ofk. It is not a free lunch, but it beats licking your finger and seeing from where the wind comes... (Joke) - NMF on a heterogeneous dataset often just rediscovers the obvious cell-type axis. The interesting use case is running it within a cell type to find finer-grained programmes (activation, exhaustion, cycling, etc.). We will do exactly that here.
We will focus on the T cells as an example. Think of your own use cases in your data set and analyses.
Identifying T cells¶
We will use the AUC scores from earlier to pull out the T cell population. The Python package has no Otsu threshold yet, so we borrow the binariser from the SCENIC section: a two-component Gaussian mixture on the AUC with the threshold at the trough between the two modes, which is just as data-driven for a bimodal distribution.
auc_thresholds = bv.pathways.binarise_regulon_activity(auc_scores).thresholds
t_cell_threshold = auc_thresholds.filter(pl.col("regulon") == "T cell")["threshold"][0]
auc_df = auc_scores.frame()
fig, ax = plt.subplots(figsize=(6, 4))
ax.hist(auc_df["T cell"], bins=13, color="darkgrey")
ax.axvline(t_cell_threshold, color="black")
ax.set_xlabel("T cell signature [AUC]")
ax.set_ylabel("count")
plt.show()
Binarised 4 regulons, 4 of which were bimodal.
With the threshold in hand we grab the T cell IDs and recompute HVGs within this subset. This matters: HVGs computed across all PBMCs are dominated by inter-cell-type variation (T vs B vs monocyte). HVGs within T cells expose the genes that actually vary across T cell states, which is what we want NMF to factorise.
get_hvg_data() is a non-mutating variant of find_hvg(): it returns a
polars frame with the HVG metrics and an is_hvg flag, without overwriting
the HVGs stored on the object. Convenient when you want HVGs for a specific
downstream analysis without disturbing the global state.
t_cell_ids = auc_df.filter(pl.col("T cell") >= t_cell_threshold)["cell_id"].to_list()
hvg_t_cell_data = bv.pp.get_hvg_data(sc, cell_ids=t_cell_ids)
t_cell_hvg = hvg_t_cell_data.filter(pl.col("is_hvg"))["gene_id"].to_list()
print(f"{len(t_cell_ids)} T cells, {len(t_cell_hvg)} HVGs")
HVG (VST): 11_139 genes, 1 batches, 1 disk block(s) HVG (VST): Calculated gene statistics in 3.54ms HVG (VST): Fitted Loess in 416.50µs HVG (VST): Standardised variance in 749.96µs (907 gene(s) re-read for the clip) HVG (VST): Total run time -> 4.74ms 1259 T cells, 3000 HVGs
Running a single NMF run¶
nmf() runs one NMF on the chosen cells and genes. The default
initialisation is NNDSVD, which is deterministic and gives a sensible
starting point.
t_cell_nmf_results = bv.nmf.nmf(sc, 10, cell_ids=t_cell_ids, gene_ids=t_cell_hvg)
t_cell_nmf_results
NMF: Loading data from disk ... ... done in 1.42ms NMF: Running NMF for single cells ... NMF: Iteration 20 out of 250 - current loss: 636466.12 NMF: Iteration 30 out of 250 - current loss: 635777.38 NMF: Iteration 40 out of 250 - current loss: 635487.31 NMF: Iteration 50 out of 250 - current loss: 635336.88 NMF converged successfully after 50 iters ... done in 91.85ms
NmfResult( source_class='SingleCells', n_genes=3000, n_cells=1259, k=10, final_loss=635336.875, n_iter=50, converged=True, preprocessing='none', )
The result is an NmfResult carrying the W gene-loading matrix
(genes x components) and the H cell-activation matrix (components x
cells), plus the parameters and convergence info.
bv.nmf.get_w(t_cell_nmf_results)[:5, :6]
| gene_id | comp_01 | comp_02 | comp_03 | comp_04 | comp_05 |
|---|---|---|---|---|---|
| str | f64 | f64 | f64 | f64 | f64 |
| "ENSG00000188976" | 1.710254 | 1.704022 | 9.9695e-11 | 1.091552 | 9.9989e-11 |
| "ENSG00000188290" | 9.9844e-11 | 1.0022e-10 | 9.9695e-11 | 1.280688 | 9.9989e-11 |
| "ENSG00000187608" | 9.9844e-11 | 0.467409 | 0.260344 | 5.192493 | 9.9989e-11 |
| "ENSG00000186827" | 9.9844e-11 | 1.0022e-10 | 7.167763 | 1.0006e-10 | 9.9989e-11 |
| "ENSG00000242485" | 4.807507 | 0.525354 | 2.890343 | 2.09104 | 1.08173 |
t_cell_h = bv.nmf.get_h(t_cell_nmf_results)
assert isinstance(t_cell_h, np.ndarray)
t_cell_h[:5, :5]
array([[2.86940355e-02, 2.72563528e-02, 2.69759949e-02, 2.52258535e-02,
2.47818008e-02],
[6.27619447e-03, 9.97814192e-11, 9.97814192e-11, 3.23917046e-02,
2.77456697e-02],
[1.49816424e-02, 4.53807078e-02, 4.34179902e-02, 1.29189380e-02,
1.00306416e-10],
[1.21569578e-02, 9.51078662e-04, 2.29290035e-02, 5.68078249e-04,
9.99404587e-11],
[3.52414362e-02, 1.82974879e-02, 2.68121082e-02, 4.03165407e-02,
4.42721695e-02]])
Running multiple NMF runs¶
For anything beyond exploratory work you want multiple restarts.
stabilised_nmf() runs n_runs HALS NMFs with random initialisations
(seeded by seed + i) and column-binds the resulting W matrices. Looking
at this stabilised data allows you to identify components that constantly
show up between random initialisations.
t_cell_nmf_results_stabilised = bv.nmf.stabilised_nmf(
sc, 10, cell_ids=t_cell_ids, gene_ids=t_cell_hvg, n_runs=10
)
NMF: Loading data from disk ... ... done in 1.44ms NMF: Running multiple NMF runs for single cells ...
Finished stabilised NMF run: 6 Finished stabilised NMF run: 9 Finished stabilised NMF run: 3 Finished stabilised NMF run: 1 Finished stabilised NMF run: 8
Finished stabilised NMF run: 7 Finished stabilised NMF run: 10 Finished stabilised NMF run: 4 Finished stabilised NMF run: 5
Finished stabilised NMF run: 2 ... done in 967.29ms
The W matrix here is wide: n_genes x (k * n_runs). Each block of k
columns corresponds to one run. You can then use it for downstream consensus
analyses.
bv.nmf.get_w(t_cell_nmf_results_stabilised)[:5, :6]
| gene_id | run_01.comp_01 | run_01.comp_02 | run_01.comp_03 | run_01.comp_04 | run_01.comp_05 |
|---|---|---|---|---|---|
| str | f64 | f64 | f64 | f64 | f64 |
| "ENSG00000188976" | 1.087731 | 0.040786 | 1.0004e-10 | 2.289901 | 9.9988e-11 |
| "ENSG00000188290" | 9.9933e-11 | 1.0001e-10 | 1.0004e-10 | 1.0003e-10 | 9.9988e-11 |
| "ENSG00000187608" | 9.9933e-11 | 1.0001e-10 | 1.0004e-10 | 1.0003e-10 | 9.9988e-11 |
| "ENSG00000186827" | 9.9933e-11 | 1.0001e-10 | 7.211133 | 1.0003e-10 | 9.9988e-11 |
| "ENSG00000242485" | 1.699127 | 0.206931 | 3.782093 | 2.31604 | 1.342618 |
The H matrices are kept per run, since each random initialisation gives a different cell-activation pattern (components are not aligned across runs without further work).
[h.shape for h in bv.nmf.get_h(t_cell_nmf_results_stabilised)]
[(10, 1259), (10, 1259), (10, 1259), (10, 1259), (10, 1259), (10, 1259), (10, 1259), (10, 1259), (10, 1259), (10, 1259)]
The run with the lowest final reconstruction loss is the most natural
starting point for a single-run analysis. get_best_run() returns it as an
NmfResult, identical in shape to the output of nmf().
best_run = bv.nmf.get_best_run(t_cell_nmf_results_stabilised)
best_run
NmfResult( source_class='SingleCells', n_genes=3000, n_cells=1259, k=10, final_loss=635546.6875, n_iter=None, converged=True, preprocessing='none', )
Consensus NMF¶
Picking the lowest-loss restart is a reasonable default, but it dodges the
question you actually care about: did the restarts agree? Consensus NMF
(cNMF, Kotliar, et al.) answers
it directly. Pool the components of every restart, drop the ones sitting on
their own in the pool, k-means the survivors into k groups, and take the
median of each group. What comes out is the programme structure the
restarts agree on, and the mean silhouette of those clusters says how
strongly they agreed.
Before fitting, though, you need a k. nmf_k_sweep() runs the consensus
step across a range of ranks and reports stability against reconstruction
error, keeping no factors, so a wide sweep stays affordable.
t_cell_k_sweep = bv.nmf.nmf_k_sweep(
sc,
range(2, 13),
cell_ids=t_cell_ids,
gene_ids=t_cell_hvg,
n_runs=10,
nmf_consensus_params=NmfConsensusParams(density_threshold=2.0),
)
t_cell_k_sweep
NMF: Loading data from disk ... ... done in 1.45ms NMF: Running the k sweep for single cells ... Running NMF k sweep: k = 2 (1 of 11)
Running NMF k sweep: k = 3 (2 of 11)
Running NMF k sweep: k = 4 (3 of 11)
Running NMF k sweep: k = 5 (4 of 11)
Running NMF k sweep: k = 6 (5 of 11)
Running NMF k sweep: k = 7 (6 of 11)
Running NMF k sweep: k = 8 (7 of 11)
Running NMF k sweep: k = 9 (8 of 11)
Running NMF k sweep: k = 10 (9 of 11)
Running NMF k sweep: k = 11 (10 of 11)
Running NMF k sweep: k = 12 (11 of 11)
... done in 9.04s
NmfKSweepResult( source_class='SingleCells', k_range=[2, 12], n_runs=10, best_k=2, best_stability=0.9987, )
sweep = t_cell_k_sweep.frame
fig, axes = plt.subplots(1, 2, figsize=(9, 3.5), sharex=True)
axes[0].plot(sweep["k"], sweep["stability"], marker="o", color="black")
axes[0].set_ylabel("stability (silhouette)")
axes[1].plot(sweep["k"], sweep["best_error"], marker="o", color="black")
axes[1].set_ylabel("best reconstruction error")
for ax in axes:
ax.set_xlabel("k")
fig.tight_layout()
plt.show()
Error falls monotonically with k, so it would happily push you to the
largest rank you can afford. Stability is the counterweight: take the last
k before it falls away, while the error curve is still coming down. Here
stability plateaus from 5 to 9 (with a dip at 7) and drops at 10, so that is
9, not the 10 we picked by eye for the runs above. Worth knowing before
writing up ten programmes when the data supports nine. (Identifying two
components is always trivial and unlikely to be the true signal.)
density_threshold=2 turns the outlier filter off, since cosine distance
cannot exceed 2. Left on, components whose neighbours sit too far away get
dropped, and if fewer than k survive the fit errors instead of returning
something degenerate. Sensible on real data with enough restarts; with only a
handful of them it fires more often than it should. get_stability() gives you the
local_density values to pick a real threshold from.
t_cell_nmf_consensus = bv.nmf.consensus_nmf(
sc,
9,
cell_ids=t_cell_ids,
gene_ids=t_cell_hvg,
n_runs=10,
nmf_consensus_params=NmfConsensusParams(density_threshold=2.0),
)
t_cell_nmf_consensus
NMF: Loading data from disk ... ... done in 1.58ms NMF: Running consensus NMF for single cells ...
Finished stabilised NMF run: 8 Finished stabilised NMF run: 1 Finished stabilised NMF run: 7 Finished stabilised NMF run: 9
Finished stabilised NMF run: 3 Finished stabilised NMF run: 2 Finished stabilised NMF run: 5 Finished stabilised NMF run: 4 Finished stabilised NMF run: 6 Finished stabilised NMF run: 10 Consensus NMF (k = 9): 90 of 90 components kept, 3 neighbours per density estimate
... done in 929.92ms
ConsensusNmfResult( source_class='SingleCells', n_genes=3000, n_cells=1259, k=9, n_runs=10, stability=0.6947, rel_error=0.3353, n_dropped=0, n_components=90, preprocessing='none', )
W and H come back in exactly the shape nmf() gives you, so everything
downstream is unchanged. What is new is get_stability().
consensus_diag = bv.nmf.get_stability(t_cell_nmf_consensus)
print(f"stability: {consensus_diag['stability']:.3f}")
consensus_diag["cluster_sizes"]
stability: 0.695
| cluster | n |
|---|---|
| i64 | i64 |
| 0 | 11 |
| 1 | 6 |
| 2 | 12 |
| 3 | 3 |
| 4 | 10 |
| 5 | 20 |
| 6 | 10 |
| 7 | 8 |
| 8 | 10 |
The per-component table records where each restart's components landed.
component_id uses the same run_XX.comp_YY naming as the w_all columns
of a stabilised fit, so at matching k and n_runs the two line up directly
and you can go back to the raw restarts behind any cluster.
consensus_clusters = consensus_diag["clusters"]
assert isinstance(consensus_clusters, pl.DataFrame)
consensus_clusters.head()
| component_id | run | component | pooled_idx | cluster | local_density | silhouette | kept |
|---|---|---|---|---|---|---|---|
| str | i64 | i64 | i64 | i64 | f64 | f64 | bool |
| "run_01.comp_01" | 0 | 0 | 0 | 5 | 0.003256 | 0.92076 | true |
| "run_01.comp_02" | 0 | 1 | 1 | 5 | 0.032114 | 0.857229 | true |
| "run_01.comp_03" | 0 | 2 | 2 | 6 | 0.034165 | 0.85699 | true |
| "run_01.comp_04" | 0 | 3 | 3 | 3 | 0.092816 | 0.879797 | true |
| "run_01.comp_05" | 0 | 4 | 4 | 1 | 0.090723 | 0.226843 | true |
With 10 restarts, a cluster holding 10 components is a programme every run found. A thin one is a programme only some initialisations saw, and that is worth knowing before you write it up.
Memory, not runtime, is what bites here. The restarts are dense and all live
at once, so budget roughly n_cells * k * n_runs floats on top of the
counts. At a few hundred thousand cells with n_runs=50 that adds up fast,
and the honest answer is to run consensus NMF on MetaCells instead. See
the meta cell vignette.
Downstream analysis¶
What you do next depends entirely on what you are after. Some natural directions:
- Inspect the components: rank genes by loading in
Wto read off what each component represents. Components that recover known programmes (cytotoxicity, exhaustion, ribosomal, IFN response, etc.) are a good sign; components that load on uninteresting genes you can ignore or merge. - Score cells:
Hgives you per-cell activations for each programme. Project them onto your UMAP, correlate against existing annotations, or use them as features for downstream clustering. - Add activations to the obs table:
bv.nmf.get_data()on anNmfResultor aConsensusNmfResultreturns a polars frame of cell activations keyed oncell_idxthat goes straight intoadd_obs(), the same way module scores did earlier.
We leave the choice of analysis here to you: the right downstream depends on the biology and your questions to the data, not the API.
Clean up¶
tempdir_pbmc.cleanup()