Skip to content

Gene sets and regulons

Gene set scores, HotSpot gene modules and SCENIC regulons.

Three jobs. Score every cell against gene sets (module scores, AUCell, VISION, ULM / MLM), find gene modules that vary smoothly over the kNN graph (HotSpot), and infer TF regulons and score those (SCENIC).

Start with aucell for gene sets; vision takes signed signatures, lm_activity a weighted TF-target network. For modules call hotspot_autocor, then hotspot_gene_cor on the genes that score, then generate_hotspot_membership. For regulons run scenic_grn, identify_tf_to_genes, tf_to_genes_correlations, optionally tf_to_genes_motif_enrichment, then build_regulons and score them with aucell. Each SCENIC step takes the ScenicGrn of the last and returns an updated copy; the input is never modified.

What lands where. Nothing here writes to obs, var, sc.map or sc.cache. Scores come back as an ScMatrixRes (cells by gene sets) and get_data turns one into an obs frame for sc.add_obs. The HotSpot, VISION autocorrelation and SCENIC functions return their own result objects and data frames. All of them take a SingleCells, a SingleCellsSubset or a MetaCells (the meta cells compute on their in-memory counts), except module_scores, which takes no meta cells.

genes = sc.gene_ids().tolist()
gene_sets = {"set_a": genes[:20], "set_b": genes[20:50]}
res = bv.pathways.aucell(sc, gene_sets)
sc.add_obs(bv.pathways.get_data(res))

HotSpot reads the PCA and, by default, the cached kNN graph:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
autocor = bv.pathways.hotspot_autocor(sc)
top = autocor.sort("z_score", descending=True)["gene_id"].head(100).to_list()
hs = bv.pathways.hotspot_gene_cor(sc, genes_to_take=top)
hs = bv.pathways.generate_hotspot_membership(hs, min_size=5)
modules = bv.pathways.get_hotspot_membership(hs)

The SCENIC chain, without the motif step:

tf_ids = genes[:30]  # your TF list, as gene ids
grn = bv.pathways.scenic_grn(sc, tf_ids)
grn = bv.pathways.identify_tf_to_genes(grn, n_sd=1.5)
grn = bv.pathways.tf_to_genes_correlations(grn, sc)
regulons = bv.pathways.build_regulons(grn, use_leading_edge=False, min_genes=5)
auc = bv.pathways.aucell(sc, regulons)
on_off = bv.pathways.binarise_regulon_activity(auc)

Gotchas. Gene sets, TFs and networks use the gene ids of var, not symbols. Unknown ids drop; for the TFs in scenic_grn you only hear about it with verbose on. hotspot_autocor and hotspot_gene_cor raise if the embedding or the cached kNN is stale after a change of the cell filter, and the gene by gene output of hotspot_gene_cor grows with the square of genes_to_take, so cut it down by autocorrelation first. cells_to_take drops the cached kNN and searches again. The motif ranking database and the motif-to-TF annotation are yours to supply: run_cistarget and tf_to_genes_motif_enrichment take the ranks as a genes by motifs integer matrix and the annotation as a frame with motif, TF and annotationSource, and build_regulons keeps only links with motif support unless you pass use_leading_edge=False. build_regulons and lm_activity return None with a warning when nothing survives their size filters.

Worked through in Gene set analysis and GRN inference on PBMCs.

Gene set scores

Gene set scores, HotSpot gene modules and SCENIC regulons.

Three jobs. Score every cell against gene sets (module scores, AUCell, VISION, ULM / MLM), find gene modules that vary smoothly over the kNN graph (HotSpot), and infer TF regulons and score those (SCENIC).

Start with aucell for gene sets; vision takes signed signatures, lm_activity a weighted TF-target network. For modules call hotspot_autocor, then hotspot_gene_cor on the genes that score, then generate_hotspot_membership. For regulons run scenic_grn, identify_tf_to_genes, tf_to_genes_correlations, optionally tf_to_genes_motif_enrichment, then build_regulons and score them with aucell. Each SCENIC step takes the ScenicGrn of the last and returns an updated copy; the input is never modified.

What lands where. Nothing here writes to obs, var, sc.map or sc.cache. Scores come back as an ScMatrixRes (cells by gene sets) and get_data turns one into an obs frame for sc.add_obs. The HotSpot, VISION autocorrelation and SCENIC functions return their own result objects and data frames. All of them take a SingleCells, a SingleCellsSubset or a MetaCells (the meta cells compute on their in-memory counts), except module_scores, which takes no meta cells.

genes = sc.gene_ids().tolist()
gene_sets = {"set_a": genes[:20], "set_b": genes[20:50]}
res = bv.pathways.aucell(sc, gene_sets)
sc.add_obs(bv.pathways.get_data(res))

HotSpot reads the PCA and, by default, the cached kNN graph:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
autocor = bv.pathways.hotspot_autocor(sc)
top = autocor.sort("z_score", descending=True)["gene_id"].head(100).to_list()
hs = bv.pathways.hotspot_gene_cor(sc, genes_to_take=top)
hs = bv.pathways.generate_hotspot_membership(hs, min_size=5)
modules = bv.pathways.get_hotspot_membership(hs)

The SCENIC chain, without the motif step:

tf_ids = genes[:30]  # your TF list, as gene ids
grn = bv.pathways.scenic_grn(sc, tf_ids)
grn = bv.pathways.identify_tf_to_genes(grn, n_sd=1.5)
grn = bv.pathways.tf_to_genes_correlations(grn, sc)
regulons = bv.pathways.build_regulons(grn, use_leading_edge=False, min_genes=5)
auc = bv.pathways.aucell(sc, regulons)
on_off = bv.pathways.binarise_regulon_activity(auc)

Gotchas. Gene sets, TFs and networks use the gene ids of var, not symbols. Unknown ids drop; for the TFs in scenic_grn you only hear about it with verbose on. hotspot_autocor and hotspot_gene_cor raise if the embedding or the cached kNN is stale after a change of the cell filter, and the gene by gene output of hotspot_gene_cor grows with the square of genes_to_take, so cut it down by autocorrelation first. cells_to_take drops the cached kNN and searches again. The motif ranking database and the motif-to-TF annotation are yours to supply: run_cistarget and tf_to_genes_motif_enrichment take the ranks as a genes by motifs integer matrix and the annotation as a frame with motif, TF and annotationSource, and build_regulons keeps only links with motif support unless you pass use_leading_edge=False. build_regulons and lm_activity return None with a warning when nothing survives their size filters.

ScMatrixRes dataclass

ScMatrixRes(
    values: ndarray,
    columns: tuple[str, ...],
    cell_ids: ndarray,
    cell_indices: ndarray,
    index_col: str,
)

Cells x gene sets scores, for cells and meta cells alike.

The row index names which obs it joins onto.

Attributes:

Name Type Description
values ndarray

(n_cells, n_sets) float64 scores.

columns tuple[str, ...]

The gene set names.

cell_ids ndarray

The cell (or meta cell) ids, row order.

cell_indices ndarray

0-based store index (or meta cell row) of each row.

index_col str

"cell_idx" for cells, "meta_cell_idx" for meta cells.

shape property

shape: tuple[int, int]

(n_cells, n_sets).

frame

frame() -> DataFrame

cell_id and one column per gene set.

aucell

aucell(
    sc: ScOrMc,
    gs_list: GeneSets,
    *,
    aucell_params: AucellParams | None = None,
    streaming: bool | None = None,
    verbose: Verbose = True,
) -> ScMatrixRes

AUCell scores.

Ranks the genes within each cell and scores how high a gene set sits; see AucellParams for the three statistics. Meta cells rank their raw counts.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells.

required
gs_list GeneSets

Gene set name to gene ids. Unknown ids warn and drop.

required
aucell_params AucellParams | None

The parameters. None uses the defaults.

None
streaming bool | None

Read the cells in chunks. None decides by size; unused for meta cells.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
ScMatrixRes

The ScMatrixRes.

References

Aibar, et al., Nat. Methods, 2017.

Examples:

>>> res = bv.pathways.aucell(sc, gene_sets)
>>> sc.add_obs(bv.pathways.get_data(res))

module_scores

module_scores(
    sc: ScOrScSubset,
    gs_list: GeneSets,
    *,
    n_bins: int = 24,
    n_ctrl: int = 100,
    seed: int = 42,
    streaming: bool | None = None,
    verbose: Verbose = True,
) -> ScMatrixRes

Module activity scores.

Seurat's AddModuleScore: per gene set the mean expression of its genes minus that of control genes drawn from the same expression bins.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment or a subset.

required
gs_list GeneSets

Gene set name to gene ids. Unknown ids warn and drop.

required
n_bins int

Expression bins.

24
n_ctrl int

Control genes per gene set gene.

100
seed int

Seed for the control draws.

42
streaming bool | None

Read the cells in chunks. None decides by size.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
ScMatrixRes

The ScMatrixRes over the kept cells.

References

Tirosh, et al., Science, 2016.

Examples:

>>> res = bv.pathways.module_scores(sc, gene_sets, n_ctrl=50)

get_data

get_data(
    res: ScMatrixRes,
    *,
    columns: Sequence[str] | None = None,
) -> DataFrame

The scores as an obs frame for add_obs.

One column per gene set plus the 0-based cell_idx (meta_cell_idx for meta cells).

Parameters:

Name Type Description Default
res ScMatrixRes

The scores.

required
columns Sequence[str] | None

Gene sets to keep. None keeps all.

None

Raises:

Type Description
ValueError

On an unknown gene set.

VISION signatures

Gene set scores, HotSpot gene modules and SCENIC regulons.

Three jobs. Score every cell against gene sets (module scores, AUCell, VISION, ULM / MLM), find gene modules that vary smoothly over the kNN graph (HotSpot), and infer TF regulons and score those (SCENIC).

Start with aucell for gene sets; vision takes signed signatures, lm_activity a weighted TF-target network. For modules call hotspot_autocor, then hotspot_gene_cor on the genes that score, then generate_hotspot_membership. For regulons run scenic_grn, identify_tf_to_genes, tf_to_genes_correlations, optionally tf_to_genes_motif_enrichment, then build_regulons and score them with aucell. Each SCENIC step takes the ScenicGrn of the last and returns an updated copy; the input is never modified.

What lands where. Nothing here writes to obs, var, sc.map or sc.cache. Scores come back as an ScMatrixRes (cells by gene sets) and get_data turns one into an obs frame for sc.add_obs. The HotSpot, VISION autocorrelation and SCENIC functions return their own result objects and data frames. All of them take a SingleCells, a SingleCellsSubset or a MetaCells (the meta cells compute on their in-memory counts), except module_scores, which takes no meta cells.

genes = sc.gene_ids().tolist()
gene_sets = {"set_a": genes[:20], "set_b": genes[20:50]}
res = bv.pathways.aucell(sc, gene_sets)
sc.add_obs(bv.pathways.get_data(res))

HotSpot reads the PCA and, by default, the cached kNN graph:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
autocor = bv.pathways.hotspot_autocor(sc)
top = autocor.sort("z_score", descending=True)["gene_id"].head(100).to_list()
hs = bv.pathways.hotspot_gene_cor(sc, genes_to_take=top)
hs = bv.pathways.generate_hotspot_membership(hs, min_size=5)
modules = bv.pathways.get_hotspot_membership(hs)

The SCENIC chain, without the motif step:

tf_ids = genes[:30]  # your TF list, as gene ids
grn = bv.pathways.scenic_grn(sc, tf_ids)
grn = bv.pathways.identify_tf_to_genes(grn, n_sd=1.5)
grn = bv.pathways.tf_to_genes_correlations(grn, sc)
regulons = bv.pathways.build_regulons(grn, use_leading_edge=False, min_genes=5)
auc = bv.pathways.aucell(sc, regulons)
on_off = bv.pathways.binarise_regulon_activity(auc)

Gotchas. Gene sets, TFs and networks use the gene ids of var, not symbols. Unknown ids drop; for the TFs in scenic_grn you only hear about it with verbose on. hotspot_autocor and hotspot_gene_cor raise if the embedding or the cached kNN is stale after a change of the cell filter, and the gene by gene output of hotspot_gene_cor grows with the square of genes_to_take, so cut it down by autocorrelation first. cells_to_take drops the cached kNN and searches again. The motif ranking database and the motif-to-TF annotation are yours to supply: run_cistarget and tf_to_genes_motif_enrichment take the ranks as a genes by motifs integer matrix and the annotation as a frame with motif, TF and annotationSource, and build_regulons keeps only links with motif support unless you pass use_leading_edge=False. build_regulons and lm_activity return None with a warning when nothing survives their size filters.

VisionAutocorRes dataclass

VisionAutocorRes(
    vision_matrix: ScMatrixRes, auto_cor: DataFrame
)

VISION scores with their autocorrelation.

Attributes:

Name Type Description
vision_matrix ScMatrixRes

The scores.

auto_cor DataFrame

gene_set_name, auto_cor (1 - Geary's C), p_val (against the permuted sets of the same size and balance cluster) and fdr.

vision

vision(
    sc: ScOrMc,
    gs_list: Signatures,
    *,
    streaming: bool | None = None,
    verbose: Verbose = True,
) -> ScMatrixRes

VISION signature scores.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells.

required
gs_list Signatures

Signature name to {"pos": [...], "neg": [...]} gene ids; "neg" may be left out. Unknown ids warn and drop.

required
streaming bool | None

Read the cells in chunks. None decides by size; unused for meta cells.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
ScMatrixRes

The ScMatrixRes.

References

DeTomaso, et al., Nat. Commun., 2019.

Examples:

>>> res = bv.pathways.vision(sc, signatures)

vision_w_autocor

vision_w_autocor(
    sc: ScOrMc,
    gs_list: Signatures,
    embd_to_use: str,
    *,
    no_embd_to_use: int | None = None,
    use_knn: bool = True,
    vision_params: VisionParams | None = None,
    streaming: bool | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> VisionAutocorRes

VISION scores with their local autocorrelation.

Scores the signatures, then tests each for spatial structure: Geary's C over the kNN graph, against random signatures of similar size and balance (generate_null_perm_gs).

The random signatures come from numpy's generator.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells, with the embedding.

required
gs_list Signatures

Signature name to {"pos": [...], "neg": [...]} gene ids.

required
embd_to_use str

The embedding for the kNN search, e.g. "pca".

required
no_embd_to_use int | None

Leading embedding dimensions to use. None for all.

None
use_knn bool

Take the cached kNN rather than searching the embedding.

True
vision_params VisionParams | None

The null and kNN parameters. None uses the defaults.

None
streaming bool | None

Read the cells in chunks. None decides by size; unused for meta cells.

None
seed int

Seed for the null signatures and the kNN search.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
VisionAutocorRes

The VisionAutocorRes.

Raises:

Type Description
ValueError

If the embedding or the cached kNN is missing or stale.

References

DeTomaso, et al., Nat. Commun., 2019.

Examples:

>>> res = bv.pathways.vision_w_autocor(
...     sc, signatures, "pca", no_embd_to_use=15
... )
>>> res.auto_cor

generate_null_perm_gs

generate_null_perm_gs(
    gs_list: Signatures,
    expr_genes: Sequence[str],
    *,
    n_perm: int = 500,
    n_comp: int = 5,
    seed: int = 42,
) -> tuple[list[list[dict[str, list[str]]]], ndarray]

Random signatures for the VISION autocorrelation null.

Signatures are clustered by log10 size and share of positive genes; per cluster centre n_perm random signatures of that size and balance are drawn from expr_genes. With no more signatures than n_comp, each is its own cluster.

Parameters:

Name Type Description Default
gs_list Signatures

The signatures, as for vision.

required
expr_genes Sequence[str]

The gene ids to draw from.

required
n_perm int

Random signatures per cluster.

500
n_comp int

Number of clusters.

5
seed int

Seed for the clustering and the draws.

42

Returns:

Type Description
list[list[dict[str, list[str]]]]

(random_signatures, clusters): per cluster a list of

ndarray

{"pos": [...], "neg": [...]}, and the 0-based cluster of each

tuple[list[list[dict[str, list[str]]]], ndarray]

signature.

Examples:

>>> random_sigs, clusters = bv.pathways.generate_null_perm_gs(
...     signatures, genes, n_perm=100
... )

TF activity from a network

Gene set scores, HotSpot gene modules and SCENIC regulons.

Three jobs. Score every cell against gene sets (module scores, AUCell, VISION, ULM / MLM), find gene modules that vary smoothly over the kNN graph (HotSpot), and infer TF regulons and score those (SCENIC).

Start with aucell for gene sets; vision takes signed signatures, lm_activity a weighted TF-target network. For modules call hotspot_autocor, then hotspot_gene_cor on the genes that score, then generate_hotspot_membership. For regulons run scenic_grn, identify_tf_to_genes, tf_to_genes_correlations, optionally tf_to_genes_motif_enrichment, then build_regulons and score them with aucell. Each SCENIC step takes the ScenicGrn of the last and returns an updated copy; the input is never modified.

What lands where. Nothing here writes to obs, var, sc.map or sc.cache. Scores come back as an ScMatrixRes (cells by gene sets) and get_data turns one into an obs frame for sc.add_obs. The HotSpot, VISION autocorrelation and SCENIC functions return their own result objects and data frames. All of them take a SingleCells, a SingleCellsSubset or a MetaCells (the meta cells compute on their in-memory counts), except module_scores, which takes no meta cells.

genes = sc.gene_ids().tolist()
gene_sets = {"set_a": genes[:20], "set_b": genes[20:50]}
res = bv.pathways.aucell(sc, gene_sets)
sc.add_obs(bv.pathways.get_data(res))

HotSpot reads the PCA and, by default, the cached kNN graph:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
autocor = bv.pathways.hotspot_autocor(sc)
top = autocor.sort("z_score", descending=True)["gene_id"].head(100).to_list()
hs = bv.pathways.hotspot_gene_cor(sc, genes_to_take=top)
hs = bv.pathways.generate_hotspot_membership(hs, min_size=5)
modules = bv.pathways.get_hotspot_membership(hs)

The SCENIC chain, without the motif step:

tf_ids = genes[:30]  # your TF list, as gene ids
grn = bv.pathways.scenic_grn(sc, tf_ids)
grn = bv.pathways.identify_tf_to_genes(grn, n_sd=1.5)
grn = bv.pathways.tf_to_genes_correlations(grn, sc)
regulons = bv.pathways.build_regulons(grn, use_leading_edge=False, min_genes=5)
auc = bv.pathways.aucell(sc, regulons)
on_off = bv.pathways.binarise_regulon_activity(auc)

Gotchas. Gene sets, TFs and networks use the gene ids of var, not symbols. Unknown ids drop; for the TFs in scenic_grn you only hear about it with verbose on. hotspot_autocor and hotspot_gene_cor raise if the embedding or the cached kNN is stale after a change of the cell filter, and the gene by gene output of hotspot_gene_cor grows with the square of genes_to_take, so cut it down by autocorrelation first. cells_to_take drops the cached kNN and searches again. The motif ranking database and the motif-to-TF annotation are yours to supply: run_cistarget and tf_to_genes_motif_enrichment take the ranks as a genes by motifs integer matrix and the annotation as a frame with motif, TF and annotationSource, and build_regulons keeps only links with motif support unless you pass use_leading_edge=False. build_regulons and lm_activity return None with a warning when nothing survives their size filters.

LmActivityRes dataclass

LmActivityRes(
    es: ScMatrixRes, pvals: ScMatrixRes, fdr: ScMatrixRes
)

ULM / MLM scores with p-values.

Attributes:

Name Type Description
es ScMatrixRes

The activity scores.

pvals ScMatrixRes

Two-sided p-values.

fdr ScMatrixRes

Benjamini-Hochberg adjusted per cell across the sources, as decoupler does.

lm_activity

lm_activity(
    sc: ScOrMc,
    net: DataFrame,
    *,
    lm_params: LmActivityParams | None = None,
    verbose: Verbose = True,
) -> ScMatrixRes | LmActivityRes | None

ULM / MLM activity scores (decoupler style).

Per cell the normalised expression of every gene is regressed on the weights of each source's targets (ULM: one model per source, MLM: all sources jointly); the t value (or the slope) is the activity.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells.

required
net DataFrame

source, target and optionally weight, see prep_lm_network.

required
lm_params LmActivityParams | None

The parameters. None uses the defaults.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
ScMatrixRes | LmActivityRes | None

The scores as a ScMatrixRes, or with p_values an LmActivityRes;

ScMatrixRes | LmActivityRes | None

None with a warning if no source keeps tmin targets. Sources

ScMatrixRes | LmActivityRes | None

come in sorted order.

References

Badia-i-Mompel, et al., Bioinform. Adv., 2022.

Examples:

>>> res = bv.pathways.lm_activity(sc, net)
>>> sc.add_obs(bv.pathways.get_data(res))

prep_lm_network

prep_lm_network(
    net: DataFrame, features: Sequence[str], tmin: int
) -> dict[str, tuple[ndarray, ndarray]] | None

A source-target network as weighted gene sets.

Targets outside features are dropped, then sources with fewer than tmin targets; duplicated source-target pairs keep the first with a warning. A missing weight column means weight 1.

Parameters:

Name Type Description Default
net DataFrame

source, target and optionally weight.

required
features Sequence[str]

The gene ids, in index order.

required
tmin int

Minimum targets per source.

required

Returns:

Type Description
dict[str, tuple[ndarray, ndarray]] | None

Source (sorted) to (0-based indices, weights), or None with a

dict[str, tuple[ndarray, ndarray]] | None

warning if no source survives.

Raises:

Type Description
ValueError

On missing columns or non-finite weights.

Examples:

>>> sets = bv.pathways.prep_lm_network(net, genes, tmin=5)

HotSpot gene modules

Gene set scores, HotSpot gene modules and SCENIC regulons.

Three jobs. Score every cell against gene sets (module scores, AUCell, VISION, ULM / MLM), find gene modules that vary smoothly over the kNN graph (HotSpot), and infer TF regulons and score those (SCENIC).

Start with aucell for gene sets; vision takes signed signatures, lm_activity a weighted TF-target network. For modules call hotspot_autocor, then hotspot_gene_cor on the genes that score, then generate_hotspot_membership. For regulons run scenic_grn, identify_tf_to_genes, tf_to_genes_correlations, optionally tf_to_genes_motif_enrichment, then build_regulons and score them with aucell. Each SCENIC step takes the ScenicGrn of the last and returns an updated copy; the input is never modified.

What lands where. Nothing here writes to obs, var, sc.map or sc.cache. Scores come back as an ScMatrixRes (cells by gene sets) and get_data turns one into an obs frame for sc.add_obs. The HotSpot, VISION autocorrelation and SCENIC functions return their own result objects and data frames. All of them take a SingleCells, a SingleCellsSubset or a MetaCells (the meta cells compute on their in-memory counts), except module_scores, which takes no meta cells.

genes = sc.gene_ids().tolist()
gene_sets = {"set_a": genes[:20], "set_b": genes[20:50]}
res = bv.pathways.aucell(sc, gene_sets)
sc.add_obs(bv.pathways.get_data(res))

HotSpot reads the PCA and, by default, the cached kNN graph:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
autocor = bv.pathways.hotspot_autocor(sc)
top = autocor.sort("z_score", descending=True)["gene_id"].head(100).to_list()
hs = bv.pathways.hotspot_gene_cor(sc, genes_to_take=top)
hs = bv.pathways.generate_hotspot_membership(hs, min_size=5)
modules = bv.pathways.get_hotspot_membership(hs)

The SCENIC chain, without the motif step:

tf_ids = genes[:30]  # your TF list, as gene ids
grn = bv.pathways.scenic_grn(sc, tf_ids)
grn = bv.pathways.identify_tf_to_genes(grn, n_sd=1.5)
grn = bv.pathways.tf_to_genes_correlations(grn, sc)
regulons = bv.pathways.build_regulons(grn, use_leading_edge=False, min_genes=5)
auc = bv.pathways.aucell(sc, regulons)
on_off = bv.pathways.binarise_regulon_activity(auc)

Gotchas. Gene sets, TFs and networks use the gene ids of var, not symbols. Unknown ids drop; for the TFs in scenic_grn you only hear about it with verbose on. hotspot_autocor and hotspot_gene_cor raise if the embedding or the cached kNN is stale after a change of the cell filter, and the gene by gene output of hotspot_gene_cor grows with the square of genes_to_take, so cut it down by autocorrelation first. cells_to_take drops the cached kNN and searches again. The motif ranking database and the motif-to-TF annotation are yours to supply: run_cistarget and tf_to_genes_motif_enrichment take the ranks as a genes by motifs integer matrix and the annotation as a frame with motif, TF and annotationSource, and build_regulons keeps only links with motif support unless you pass use_leading_edge=False. build_regulons and lm_activity return None with a warning when nothing survives their size filters.

Hotspot dataclass

Hotspot(
    z: ndarray,
    cor: ndarray,
    genes: tuple[str, ...],
    params: dict[str, object],
    module_membership: DataFrame | None = None,
)

HotSpot gene-gene local correlations.

Attributes:

Name Type Description
z ndarray

(n_genes, n_genes) float64 pair Z-scores, rows and columns in genes order.

cor ndarray

The local correlation coefficients, same layout.

genes tuple[str, ...]

The gene ids.

params dict[str, object]

used_cells, the cell ids the graph was built over.

module_membership DataFrame | None

gene_id and cluster_member (0-based module, null if unassigned), once generate_hotspot_membership ran.

hotspot_autocor

hotspot_autocor(
    sc: ScOrMc,
    *,
    embd_to_use: str = "pca",
    use_knn: bool = True,
    hotspot_params: HotspotParams | None = None,
    no_embd_to_use: int | None = None,
    cells_to_take: Sequence[str] | None = None,
    genes_to_take: Sequence[str] | None = None,
    streaming: bool | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> DataFrame

HotSpot gene autocorrelation.

How much each gene's expression varies smoothly over the kNN graph of the embedding. Meta cells model their raw counts.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells, with the embedding.

required
embd_to_use str

The embedding for the kNN, e.g. "pca".

'pca'
use_knn bool

Take the cached kNN rather than searching the embedding. Ignored when cells_to_take is given.

True
hotspot_params HotspotParams | None

The parameters. None uses the defaults.

None
no_embd_to_use int | None

Leading embedding dimensions to use. None for all.

None
cells_to_take Sequence[str] | None

Cell (meta cell) ids to use. None for all.

None
genes_to_take Sequence[str] | None

Gene ids to test. None for all.

None
streaming bool | None

Stream the genes. None decides by size; unused for meta cells.

None
seed int

Seed for the kNN search.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
DataFrame

gene_id, gearys_c, z_score, pval and fdr.

Raises:

Type Description
ValueError

If the embedding or the cached kNN is missing or stale.

References

DeTomaso, et al., Cell Syst., 2021.

Examples:

>>> autocor = bv.pathways.hotspot_autocor(sc)
>>> autocor = bv.pathways.hotspot_autocor(sc, genes_to_take=genes[:200])

hotspot_gene_cor

hotspot_gene_cor(
    sc: ScOrMc,
    *,
    embd_to_use: str = "pca",
    use_knn: bool = True,
    hotspot_params: HotspotParams | None = None,
    no_embd_to_use: int | None = None,
    cells_to_take: Sequence[str] | None = None,
    genes_to_take: Sequence[str] | None = None,
    streaming: bool | None = None,
    working_mem_gb: float = 4.0,
    seed: int = 42,
    verbose: Verbose = True,
) -> Hotspot

HotSpot gene-gene local correlations.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells, with the embedding.

required
embd_to_use str

The embedding for the kNN, e.g. "pca".

'pca'
use_knn bool

Take the cached kNN rather than searching the embedding. Ignored when cells_to_take is given.

True
hotspot_params HotspotParams | None

The parameters. None uses the defaults.

None
no_embd_to_use int | None

Leading embedding dimensions to use. None for all.

None
cells_to_take Sequence[str] | None

Cell (meta cell) ids to use. None for all.

None
genes_to_take Sequence[str] | None

Gene ids to correlate. None for all; the output is genes by genes, so pick the autocorrelated ones first.

None
streaming bool | None

Stream the genes. None decides by size; unused for meta cells.

None
working_mem_gb float

Memory for the resident gene panels of the streaming path, excluding the two output matrices.

4.0
seed int

Seed for the kNN search.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
Hotspot

The Hotspot result.

Raises:

Type Description
ValueError

If the embedding or the cached kNN is missing or stale.

References

DeTomaso, et al., Cell Syst., 2021.

Examples:

>>> hs = bv.pathways.hotspot_gene_cor(sc, genes_to_take=top)

generate_hotspot_membership

generate_hotspot_membership(
    x: Hotspot,
    *,
    fdr_threshold: float = 0.05,
    min_size: int = 10,
) -> Hotspot

Gene modules from the pair Z-scores.

Average-linkage clustering of the Z-scores, cut as HotSpot's compute_modules does.

Parameters:

Name Type Description Default
x Hotspot

The hotspot_gene_cor result.

required
fdr_threshold float

BH level at which a pair counts as significant.

0.05
min_size int

Minimum genes per module.

10

Returns:

Type Description
Hotspot

A copy with module_membership set.

Raises:

Type Description
ValueError

If fdr_threshold is outside [0, 1].

Examples:

>>> hs = bv.pathways.generate_hotspot_membership(hs, min_size=5)

get_hotspot_membership

get_hotspot_membership(x: Hotspot) -> DataFrame | None

The module membership.

Parameters:

Name Type Description Default
x Hotspot

The HotSpot result.

required

Returns:

Type Description
DataFrame | None

gene_id and cluster_member, or None before

DataFrame | None

generate_hotspot_membership.

SCENIC network inference

Gene set scores, HotSpot gene modules and SCENIC regulons.

Three jobs. Score every cell against gene sets (module scores, AUCell, VISION, ULM / MLM), find gene modules that vary smoothly over the kNN graph (HotSpot), and infer TF regulons and score those (SCENIC).

Start with aucell for gene sets; vision takes signed signatures, lm_activity a weighted TF-target network. For modules call hotspot_autocor, then hotspot_gene_cor on the genes that score, then generate_hotspot_membership. For regulons run scenic_grn, identify_tf_to_genes, tf_to_genes_correlations, optionally tf_to_genes_motif_enrichment, then build_regulons and score them with aucell. Each SCENIC step takes the ScenicGrn of the last and returns an updated copy; the input is never modified.

What lands where. Nothing here writes to obs, var, sc.map or sc.cache. Scores come back as an ScMatrixRes (cells by gene sets) and get_data turns one into an obs frame for sc.add_obs. The HotSpot, VISION autocorrelation and SCENIC functions return their own result objects and data frames. All of them take a SingleCells, a SingleCellsSubset or a MetaCells (the meta cells compute on their in-memory counts), except module_scores, which takes no meta cells.

genes = sc.gene_ids().tolist()
gene_sets = {"set_a": genes[:20], "set_b": genes[20:50]}
res = bv.pathways.aucell(sc, gene_sets)
sc.add_obs(bv.pathways.get_data(res))

HotSpot reads the PCA and, by default, the cached kNN graph:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
autocor = bv.pathways.hotspot_autocor(sc)
top = autocor.sort("z_score", descending=True)["gene_id"].head(100).to_list()
hs = bv.pathways.hotspot_gene_cor(sc, genes_to_take=top)
hs = bv.pathways.generate_hotspot_membership(hs, min_size=5)
modules = bv.pathways.get_hotspot_membership(hs)

The SCENIC chain, without the motif step:

tf_ids = genes[:30]  # your TF list, as gene ids
grn = bv.pathways.scenic_grn(sc, tf_ids)
grn = bv.pathways.identify_tf_to_genes(grn, n_sd=1.5)
grn = bv.pathways.tf_to_genes_correlations(grn, sc)
regulons = bv.pathways.build_regulons(grn, use_leading_edge=False, min_genes=5)
auc = bv.pathways.aucell(sc, regulons)
on_off = bv.pathways.binarise_regulon_activity(auc)

Gotchas. Gene sets, TFs and networks use the gene ids of var, not symbols. Unknown ids drop; for the TFs in scenic_grn you only hear about it with verbose on. hotspot_autocor and hotspot_gene_cor raise if the embedding or the cached kNN is stale after a change of the cell filter, and the gene by gene output of hotspot_gene_cor grows with the square of genes_to_take, so cut it down by autocorrelation first. cells_to_take drops the cached kNN and searches again. The motif ranking database and the motif-to-TF annotation are yours to supply: run_cistarget and tf_to_genes_motif_enrichment take the ranks as a genes by motifs integer matrix and the annotation as a frame with motif, TF and annotationSource, and build_regulons keeps only links with motif support unless you pass use_leading_edge=False. build_regulons and lm_activity return None with a warning when nothing survives their size filters.

ScenicGrn dataclass

ScenicGrn(
    importance_matrix: ndarray,
    gene_ids: tuple[str, ...],
    tf_ids: tuple[str, ...],
    params: ScenicParams,
    tf_to_gene_results: DataFrame = DataFrame(),
    cis_targets_results: DataFrame = DataFrame(),
)

SCENIC GRN inference results.

Attributes:

Name Type Description
importance_matrix ndarray

(n_genes, n_tfs) float64 importances.

gene_ids tuple[str, ...]

The target genes, the rows.

tf_ids tuple[str, ...]

The TFs, the columns.

params ScenicParams

The parameters of the run.

tf_to_gene_results DataFrame

The TF to gene links once identify_tf_to_genes ran, later extended by the correlation and motif steps.

cis_targets_results DataFrame

The CisTarget motif enrichment once tf_to_genes_motif_enrichment ran.

frame

frame() -> DataFrame

The importances as gene_id and one column per TF.

scenic_gene_filter

scenic_gene_filter(
    sc: ScOrMc,
    *,
    scenic_params: ScenicParams | None = None,
    cells_to_take: Sequence[str] | None = None,
    verbose: Verbose = True,
) -> list[str]

Genes with enough counts and enough expressing cells.

A gene passes with at least min_counts total counts and a share of at least min_cells expressing cells. Meta cells are filtered on their raw counts in memory.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells.

required
scenic_params ScenicParams | None

The parameters. None uses the defaults.

None
cells_to_take Sequence[str] | None

Cell (meta cell) ids to use. None for the kept cells.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
list[str]

The passing gene ids, in gene order.

Examples:

>>> keep = bv.pathways.scenic_gene_filter(
...     sc, scenic_params=bv.params.ScenicParams(min_counts=50)
... )

scenic_grn

scenic_grn(
    sc: ScOrMc,
    tf_ids: Sequence[str],
    *,
    scenic_params: ScenicParams | None = None,
    genes_to_take: Sequence[str] | None = None,
    cells_to_take: Sequence[str] | None = None,
    streaming: bool | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> ScenicGrn

GRN inference, the GENIE3 / GRNBoost2 step of SCENIC.

Regresses every target gene on the TFs with tree ensembles and keeps the feature importances. TFs must also pass as targets. On meta cells a min_samples_leaf of 20 or more is lowered to 10.

Parameters:

Name Type Description Default
sc ScOrMc

The experiment, a subset or meta cells.

required
tf_ids Sequence[str]

The TF gene ids; ids not in the object drop, with a warning when verbose is on.

required
scenic_params ScenicParams | None

The parameters. None uses the defaults.

None
genes_to_take Sequence[str] | None

Target gene ids. None runs scenic_gene_filter.

None
cells_to_take Sequence[str] | None

Cell (meta cell) ids. None for the kept cells.

None
streaming bool | None

Stream the targets. None decides by size; unused for meta cells.

None
seed int

Seed for the learners.

42
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
ScenicGrn

The ScenicGrn.

Raises:

Type Description
ValueError

If no TF is in the object or none passes as a target.

References

Aibar, et al., Nat. Methods, 2017; Moerman, et al., Bioinformatics, 2019.

Examples:

>>> grn = bv.pathways.scenic_grn(sc, tf_ids, genes_to_take=keep)

get_params

get_params(
    x: ScenicGrn | Hotspot,
) -> ScenicParams | dict[str, object]

The parameters of the run.

Parameters:

Name Type Description Default
x ScenicGrn | Hotspot

A SCENIC GRN result or a HotSpot result.

required

Returns:

Type Description
ScenicParams | dict[str, object]

The ScenicParams for a GRN, a dict copy for HotSpot.

identify_tf_to_genes

identify_tf_to_genes(
    x: ScenicGrn,
    *,
    method: Literal["threshold", "top_k"] = "threshold",
    k_tfs: int | None = None,
    k_genes: int | None = None,
    n_sd: float = 2.0,
    min_importance: float | None = None,
    verbose: Verbose = True,
) -> ScenicGrn

TF to gene links from the importances.

"threshold" keeps, per target gene, the TFs at or above mean + n_sd * sd of its importances. "top_k" keeps the k_tfs strongest regulators per gene and / or the k_genes strongest targets per TF. Duplicate links are dropped, the first kept.

Parameters:

Name Type Description Default
x ScenicGrn

The scenic_grn result.

required
method Literal['threshold', 'top_k']

"threshold" or "top_k".

'threshold'
k_tfs int | None

Regulators per gene for "top_k".

None
k_genes int | None

Targets per TF for "top_k".

None
n_sd float

Standard deviations above the mean for "threshold".

2.0
min_importance float | None

Optional floor on the importance, in [0, 1].

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
ScenicGrn

A copy with tf_to_gene_results set: tf, gene, importance.

Raises:

Type Description
ValueError

On "top_k" without k_tfs or k_genes, or a value out of range.

Examples:

>>> grn = bv.pathways.identify_tf_to_genes(grn, n_sd=1.5)
>>> grn_topk = bv.pathways.identify_tf_to_genes(grn, method="top_k", k_tfs=3)

tf_to_genes_correlations

tf_to_genes_correlations(
    x: ScenicGrn,
    sc: ScOrMc,
    *,
    rho_threshold: float = 0.03,
    mode: Mode = "activating",
    remove_self: bool = True,
    spearman: bool = True,
    verbose: Verbose = True,
) -> ScenicGrn

Sign the TF to gene links by correlation.

Correlates each TF with its target over the kept cells (the normalised counts on meta cells), signs the link +1 above rho_threshold, -1 below its negative and 0 between, and keeps the signs mode asks for.

Parameters:

Name Type Description Default
x ScenicGrn

The result with TF to gene links.

required
sc ScOrMc

The object the GRN ran on.

required
rho_threshold float

Correlation band around zero counted as unsigned.

0.03
mode Mode

Which links to keep.

'activating'
remove_self bool

Drop TF to itself links.

True
spearman bool

Spearman rather than Pearson.

True
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
ScenicGrn

A copy whose links gain pairwise_cor and cor_sign, filtered; x

ScenicGrn

itself with a warning if there are no links.

Raises:

Type Description
ValueError

If rho_threshold is outside [0, 1].

Examples:

>>> grn = bv.pathways.tf_to_genes_correlations(grn, sc)
>>> grn_both = bv.pathways.tf_to_genes_correlations(grn, sc, mode="both")

get_tf_to_gene

get_tf_to_gene(x: ScenicGrn) -> DataFrame

The TF to gene links; empty with a warning before identify_tf_to_genes.

Parameters:

Name Type Description Default
x ScenicGrn

The SCENIC GRN result.

required

Motif enrichment

Gene set scores, HotSpot gene modules and SCENIC regulons.

Three jobs. Score every cell against gene sets (module scores, AUCell, VISION, ULM / MLM), find gene modules that vary smoothly over the kNN graph (HotSpot), and infer TF regulons and score those (SCENIC).

Start with aucell for gene sets; vision takes signed signatures, lm_activity a weighted TF-target network. For modules call hotspot_autocor, then hotspot_gene_cor on the genes that score, then generate_hotspot_membership. For regulons run scenic_grn, identify_tf_to_genes, tf_to_genes_correlations, optionally tf_to_genes_motif_enrichment, then build_regulons and score them with aucell. Each SCENIC step takes the ScenicGrn of the last and returns an updated copy; the input is never modified.

What lands where. Nothing here writes to obs, var, sc.map or sc.cache. Scores come back as an ScMatrixRes (cells by gene sets) and get_data turns one into an obs frame for sc.add_obs. The HotSpot, VISION autocorrelation and SCENIC functions return their own result objects and data frames. All of them take a SingleCells, a SingleCellsSubset or a MetaCells (the meta cells compute on their in-memory counts), except module_scores, which takes no meta cells.

genes = sc.gene_ids().tolist()
gene_sets = {"set_a": genes[:20], "set_b": genes[20:50]}
res = bv.pathways.aucell(sc, gene_sets)
sc.add_obs(bv.pathways.get_data(res))

HotSpot reads the PCA and, by default, the cached kNN graph:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
autocor = bv.pathways.hotspot_autocor(sc)
top = autocor.sort("z_score", descending=True)["gene_id"].head(100).to_list()
hs = bv.pathways.hotspot_gene_cor(sc, genes_to_take=top)
hs = bv.pathways.generate_hotspot_membership(hs, min_size=5)
modules = bv.pathways.get_hotspot_membership(hs)

The SCENIC chain, without the motif step:

tf_ids = genes[:30]  # your TF list, as gene ids
grn = bv.pathways.scenic_grn(sc, tf_ids)
grn = bv.pathways.identify_tf_to_genes(grn, n_sd=1.5)
grn = bv.pathways.tf_to_genes_correlations(grn, sc)
regulons = bv.pathways.build_regulons(grn, use_leading_edge=False, min_genes=5)
auc = bv.pathways.aucell(sc, regulons)
on_off = bv.pathways.binarise_regulon_activity(auc)

Gotchas. Gene sets, TFs and networks use the gene ids of var, not symbols. Unknown ids drop; for the TFs in scenic_grn you only hear about it with verbose on. hotspot_autocor and hotspot_gene_cor raise if the embedding or the cached kNN is stale after a change of the cell filter, and the gene by gene output of hotspot_gene_cor grows with the square of genes_to_take, so cut it down by autocorrelation first. cells_to_take drops the cached kNN and searches again. The motif ranking database and the motif-to-TF annotation are yours to supply: run_cistarget and tf_to_genes_motif_enrichment take the ranks as a genes by motifs integer matrix and the annotation as a frame with motif, TF and annotationSource, and build_regulons keeps only links with motif support unless you pass use_leading_edge=False. build_regulons and lm_activity return None with a warning when nothing survives their size filters.

run_cistarget

run_cistarget(
    gs_list: Mapping[str, Sequence[str]],
    rankings: ndarray,
    rank_genes: Sequence[str],
    rank_motifs: Sequence[str],
    annot_data: DataFrame,
    *,
    cis_target_params: CistargetParams | None = None,
    verbose: Verbose = True,
) -> DataFrame

CisTarget motif enrichment of gene sets.

Parameters:

Name Type Description Default
gs_list Mapping[str, Sequence[str]]

Gene set name to gene ids.

required
rankings ndarray

(n_genes, n_motifs) integer motif ranks, the database.

required
rank_genes Sequence[str]

The genes of the rows.

required
rank_motifs Sequence[str]

The motifs of the columns.

required
annot_data DataFrame

motif, TF and annotationSource, the motif to TF annotation.

required
cis_target_params CistargetParams | None

The parameters. None uses the defaults.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
DataFrame

motif, gs_name, nes, auc, rank_at_max, n_enriched,

DataFrame

leading_edge_genes (; separated), TF_highConf and TF_lowConf,

DataFrame

sorted by gene set and descending NES. The TF lists are sorted in C

DataFrame

order.

Raises:

Type Description
ValueError

On a malformed ranking or annotation.

References

Aibar, et al., Nat. Methods, 2017.

Examples:

>>> cis = bv.pathways.run_cistarget(
...     tf_targets, rankings, rank_genes, rank_motifs, annot
... )

tf_to_genes_motif_enrichment

tf_to_genes_motif_enrichment(
    x: ScenicGrn,
    rankings: ndarray,
    rank_genes: Sequence[str],
    rank_motifs: Sequence[str],
    annot_data: DataFrame,
    *,
    cis_target_params: CistargetParams | None = None,
    gene_id_to_symbol: Mapping[str, str] | None = None,
    only_high_conf_tf: bool = True,
    verbose: Verbose = True,
) -> ScenicGrn

Motif support for the TF to gene links.

Runs run_cistarget on each TF's targets and flags a link in_leading_edge when a motif annotated to that TF (high confidence, or also low with only_high_conf_tf = False) has the gene in its leading edge.

Parameters:

Name Type Description Default
x ScenicGrn

The result with TF to gene links.

required
rankings ndarray

(n_genes, n_motifs) integer motif ranks.

required
rank_genes Sequence[str]

The genes of the rows.

required
rank_motifs Sequence[str]

The motifs of the columns.

required
annot_data DataFrame

motif, TF and annotationSource.

required
cis_target_params CistargetParams | None

The parameters. None uses the defaults.

None
gene_id_to_symbol Mapping[str, str] | None

Gene id to the symbol the database uses; links without a symbol are left out of the enrichment.

None
only_high_conf_tf bool

Count only high confidence annotations.

True
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
ScenicGrn

A copy with cis_targets_results set and the links gaining

ScenicGrn

in_leading_edge, sorted by TF.

Examples:

>>> grn = bv.pathways.tf_to_genes_motif_enrichment(
...     grn, rankings, rank_genes, rank_motifs, annot
... )
>>> motif_hits = bv.pathways.get_cistarget_res(grn)

get_cistarget_res

get_cistarget_res(x: ScenicGrn) -> DataFrame

The motif enrichment; empty with a warning before tf_to_genes_motif_enrichment.

Parameters:

Name Type Description Default
x ScenicGrn

The SCENIC GRN result.

required

Regulons

Gene set scores, HotSpot gene modules and SCENIC regulons.

Three jobs. Score every cell against gene sets (module scores, AUCell, VISION, ULM / MLM), find gene modules that vary smoothly over the kNN graph (HotSpot), and infer TF regulons and score those (SCENIC).

Start with aucell for gene sets; vision takes signed signatures, lm_activity a weighted TF-target network. For modules call hotspot_autocor, then hotspot_gene_cor on the genes that score, then generate_hotspot_membership. For regulons run scenic_grn, identify_tf_to_genes, tf_to_genes_correlations, optionally tf_to_genes_motif_enrichment, then build_regulons and score them with aucell. Each SCENIC step takes the ScenicGrn of the last and returns an updated copy; the input is never modified.

What lands where. Nothing here writes to obs, var, sc.map or sc.cache. Scores come back as an ScMatrixRes (cells by gene sets) and get_data turns one into an obs frame for sc.add_obs. The HotSpot, VISION autocorrelation and SCENIC functions return their own result objects and data frames. All of them take a SingleCells, a SingleCellsSubset or a MetaCells (the meta cells compute on their in-memory counts), except module_scores, which takes no meta cells.

genes = sc.gene_ids().tolist()
gene_sets = {"set_a": genes[:20], "set_b": genes[20:50]}
res = bv.pathways.aucell(sc, gene_sets)
sc.add_obs(bv.pathways.get_data(res))

HotSpot reads the PCA and, by default, the cached kNN graph:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)
autocor = bv.pathways.hotspot_autocor(sc)
top = autocor.sort("z_score", descending=True)["gene_id"].head(100).to_list()
hs = bv.pathways.hotspot_gene_cor(sc, genes_to_take=top)
hs = bv.pathways.generate_hotspot_membership(hs, min_size=5)
modules = bv.pathways.get_hotspot_membership(hs)

The SCENIC chain, without the motif step:

tf_ids = genes[:30]  # your TF list, as gene ids
grn = bv.pathways.scenic_grn(sc, tf_ids)
grn = bv.pathways.identify_tf_to_genes(grn, n_sd=1.5)
grn = bv.pathways.tf_to_genes_correlations(grn, sc)
regulons = bv.pathways.build_regulons(grn, use_leading_edge=False, min_genes=5)
auc = bv.pathways.aucell(sc, regulons)
on_off = bv.pathways.binarise_regulon_activity(auc)

Gotchas. Gene sets, TFs and networks use the gene ids of var, not symbols. Unknown ids drop; for the TFs in scenic_grn you only hear about it with verbose on. hotspot_autocor and hotspot_gene_cor raise if the embedding or the cached kNN is stale after a change of the cell filter, and the gene by gene output of hotspot_gene_cor grows with the square of genes_to_take, so cut it down by autocorrelation first. cells_to_take drops the cached kNN and searches again. The motif ranking database and the motif-to-TF annotation are yours to supply: run_cistarget and tf_to_genes_motif_enrichment take the ranks as a genes by motifs integer matrix and the annotation as a frame with motif, TF and annotationSource, and build_regulons keeps only links with motif support unless you pass use_leading_edge=False. build_regulons and lm_activity return None with a warning when nothing survives their size filters.

RegulonBinarisation dataclass

RegulonBinarisation(
    binary: DataFrame, thresholds: DataFrame
)

On/off regulon calls.

Attributes:

Name Type Description
binary DataFrame

cell_id and one boolean column per regulon, True where the score sits strictly above the threshold.

thresholds DataFrame

regulon, threshold, bimodal and n_cells_on.

build_regulons

build_regulons(
    x: ScenicGrn,
    *,
    use_leading_edge: bool = True,
    add_tf: bool = True,
    min_genes: int = 10,
    mode: Mode = "activating",
    verbose: Verbose = True,
) -> dict[str, list[str]] | None

Regulons from the TF to gene links.

Parameters:

Name Type Description Default
x ScenicGrn

The result with TF to gene links.

required
use_leading_edge bool

Keep only links with motif support; skipped with a warning before tf_to_genes_motif_enrichment.

True
add_tf bool

Put the TF itself first in its regulon.

True
min_genes int

Minimum regulon size.

10
mode Mode

Which correlation signs to keep, if the links are signed. With "both" the regulons are named <tf>_pos and <tf>_neg.

'activating'
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
dict[str, list[str]] | None

Regulon name (sorted) to gene ids, or None with a warning when

dict[str, list[str]] | None

nothing survives.

Raises:

Type Description
ValueError

If min_genes is below 1.

Examples:

>>> regulons = bv.pathways.build_regulons(grn, min_genes=3)
>>> regulons = bv.pathways.build_regulons(
...     grn, use_leading_edge=False, min_genes=5
... )

binarise_regulon_activity

binarise_regulon_activity(
    auc: ScMatrixRes,
    *,
    binarise_params: ScenicBinariseParams | None = None,
    verbose: Verbose = True,
) -> RegulonBinarisation

On/off calls per regulon.

Per regulon a two-component Gaussian mixture is compared against one Gaussian by BIC; if the mixture wins the threshold is the density trough between the means, else mean + 2 * sd. A cell is on strictly above it.

Parameters:

Name Type Description Default
auc ScMatrixRes

The AUCell scores of the regulons, at least two cells.

required
binarise_params ScenicBinariseParams | None

The parameters. None uses the defaults.

None
verbose Verbose

0 (False) silent, 1 (True) progress, 2 extra detail where the method has it.

True

Returns:

Type Description
RegulonBinarisation

The RegulonBinarisation.

Raises:

Type Description
ValueError

With fewer than two cells.

References

Aibar, et al., Nat. Methods, 2017.

Examples:

>>> auc = bv.pathways.aucell(sc, regulons)
>>> on_off = bv.pathways.binarise_regulon_activity(auc)