Skip to content

Differential expression and abundance

Marker genes, donor-aware differential expression and differential abundance.

Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=, the default on ATAC peaks) between two groups (find_markers), one-vs-rest for every group of a column (find_all_markers), or markers that hold up against every rival group separately (find_specific_markers). Expression with donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge, run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods (get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities. Start with find_all_markers to look at clusters, pseudobulk_dge or nebula to compare conditions across donors.

What lands where. Nothing here writes to obs, var or the cache. The marker tests and pseudobulk_dge return polars frames; find_specific_markers, nebula, get_milor_abundances and meld return frozen records (ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying nhoods_info.

Object types. The marker functions, get_pseudobulked, pseudobulk_dge and nebula take a SingleCells or a SingleCellsSubset, so a per cell type comparison is a subset away. get_milor_abundances and meld take a SingleCells only.

markers = bv.de.find_all_markers(sc, "cell_grp")
top = markers.filter(markers["fdr"] < 0.05)

Condition across donors, one pseudobulk sample per donor. cell_list maps the sample names to their cells and the rows of the design follow its order:

import polars as pl

obs = sc.obs(filtered=True)
cell_list = {
    s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
    for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
    {"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")

Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)

design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)

Gotchas. Designs are additive formulas over a frame, "~ condition + age": numeric columns as they are, everything else treatment coded against its first (sorted) level and named <column><level>. Interactions and transformations are not parsed. coef takes a 0-based design column or its name, and the last column is tested if you give neither. Every index is 0-based, Milo's Nhood included. get_milor_abundances and meld raise on a stale embedding or kNN, so rerun those after the cell filter moves, and they warn and return None without a kNN. nebula costs milliseconds to seconds per gene: hand genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and a design with an intercept and at least one more column.

Worked through in Differential expression with donor structure and Differential abundance with Milo and MELD.

Markers

Marker genes, donor-aware differential expression and differential abundance.

Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=, the default on ATAC peaks) between two groups (find_markers), one-vs-rest for every group of a column (find_all_markers), or markers that hold up against every rival group separately (find_specific_markers). Expression with donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge, run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods (get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities. Start with find_all_markers to look at clusters, pseudobulk_dge or nebula to compare conditions across donors.

What lands where. Nothing here writes to obs, var or the cache. The marker tests and pseudobulk_dge return polars frames; find_specific_markers, nebula, get_milor_abundances and meld return frozen records (ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying nhoods_info.

Object types. The marker functions, get_pseudobulked, pseudobulk_dge and nebula take a SingleCells or a SingleCellsSubset, so a per cell type comparison is a subset away. get_milor_abundances and meld take a SingleCells only.

markers = bv.de.find_all_markers(sc, "cell_grp")
top = markers.filter(markers["fdr"] < 0.05)

Condition across donors, one pseudobulk sample per donor. cell_list maps the sample names to their cells and the rows of the design follow its order:

import polars as pl

obs = sc.obs(filtered=True)
cell_list = {
    s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
    for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
    {"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")

Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)

design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)

Gotchas. Designs are additive formulas over a frame, "~ condition + age": numeric columns as they are, everything else treatment coded against its first (sorted) level and named <column><level>. Interactions and transformations are not parsed. coef takes a 0-based design column or its name, and the last column is tested if you give neither. Every index is 0-based, Milo's Nhood included. get_milor_abundances and meld raise on a stale embedding or kNN, so rerun those after the cell filter moves, and they warn and return None without a kNN. nebula costs milliseconds to seconds per gene: hand genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and a design with an intercept and at least one more column.

ScSpecificMarkers dataclass

ScSpecificMarkers(
    summary: DataFrame,
    per_comparison: DataFrame,
    params: dict[str, object],
)

One-vs-many specific markers.

Attributes:

Name Type Description
summary DataFrame

Per reference group and gene, the summaries across every rival: prop_ref, median_auroc, min_auroc, mean_auroc, max_auroc, worst_rival, min_rank, simes_p, simes_fdr, max_p and max_p_fdr.

per_comparison DataFrame

Per reference, rival and gene, auroc, lfc, prop_ref, prop_rival, z_scores, p_values and fdr.

params dict[str, object]

The parameters of the run.

find_all_markers

find_all_markers(
    sc: ScOrScSubset,
    column_of_interest: str,
    *,
    method: Method | None = None,
    alternative: Alternative = "greater",
    min_prop: float = 0.05,
    modality: DeModality = "rna",
    verbose: Verbose = True,
) -> DataFrame

One-vs-rest Wilcoxon or logistic regression DGE for every group.

All groups are tested in one pass over the genes. Cells without a label are left out of every group and of every rest.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
column_of_interest str

The obs column holding the groups.

required
method Method | None

"wilcox", or "lr" for Seurat's logistic regression test (group ~ feature + library size against group ~ library size, a likelihood ratio test), which corrects for the depth difference between the groups. None picks "lr" for modality="atac", "wilcox" otherwise. With "lr", z_scores are the signed roots of the likelihood ratio statistics. Neither test accounts for cells being pseudoreplicates of their sample.

None
alternative Alternative

The test alternative; "greater" asks for genes up in the group.

'greater'
min_prop float

A gene is tested for a group if this share of the group or of the rest expresses it.

0.05
modality DeModality

"rna", or "atac" for the peaks or tiles of a SingleCellsMultiModal; the ids are then in feature_id.

'rna'
verbose Verbose

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

True

Returns:

Type Description
DataFrame

grp, gene_id, lfc, prop1, prop2, z_scores, p_values and

DataFrame

fdr; groups in order of first appearance, genes in gene order.

Examples:

>>> markers = bv.de.find_all_markers(sc, "cell_grp")
>>> top = markers.filter(markers["fdr"] < 0.05)

find_markers

find_markers(
    sc: ScOrScSubset,
    cells_1: Selection,
    cells_2: Selection,
    *,
    method: Method | None = None,
    alternative: Alternative = "twosided",
    min_prop: float = 0.05,
    modality: DeModality = "rna",
    verbose: Verbose = True,
) -> DataFrame

Wilcoxon or logistic regression DGE between two groups of cells.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
cells_1 Selection

0-based cell indices or ids of group 1.

required
cells_2 Selection

0-based cell indices or ids of group 2.

required
method Method | None

"wilcox", or "lr" for Seurat's logistic regression test (group ~ feature + library size against group ~ library size, a likelihood ratio test), which corrects for the depth difference between the groups. None picks "lr" for modality="atac", "wilcox" otherwise. With "lr", z_scores are the signed roots of the likelihood ratio statistics. Neither test accounts for cells being pseudoreplicates of their sample.

None
alternative Alternative

The test alternative.

'twosided'
min_prop float

A gene is tested if this share of either group expresses it.

0.05
modality DeModality

"rna", or "atac" for the peaks or tiles of a SingleCellsMultiModal; the ids are then in feature_id.

'rna'
verbose Verbose

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

True

Returns:

Type Description
DataFrame

gene_id, lfc, prop1, prop2, z_scores, p_values and fdr,

DataFrame

one row per tested gene in gene order.

Examples:

>>> obs = sc.obs(filtered=True)
>>> ct1 = obs.filter(obs["cell_grp"] == "cell_type_1")["cell_id"].to_list()
>>> ct2 = obs.filter(obs["cell_grp"] == "cell_type_2")["cell_id"].to_list()
>>> res = bv.de.find_markers(sc, ct1, ct2, alternative="greater")

find_specific_markers

find_specific_markers(
    sc: ScOrScSubset,
    column_of_interest: str,
    *,
    reference_group: str | None = None,
    method: Method | None = None,
    alternative: Alternative = "greater",
    min_prop: float = 0.05,
    modality: DeModality = "rna",
    verbose: Verbose = True,
) -> ScSpecificMarkers | None

Markers that hold up against every rival group separately.

Each reference is tested against each other group of the column on its own, then summarised per gene across the rivals: a gene marks the reference only if min_auroc stays high against all of them. Every arm comes out of one pass over the genes, and the genes are filtered once, globally, so every comparison's FDR covers the same gene set.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
column_of_interest str

The obs column holding the groups.

required
reference_group str | None

The one reference to report. None runs every group in turn.

None
method Method | None

"wilcox", or "lr" for Seurat's logistic regression test with the library size as the covariate, reference against each rival. Only the per-comparison z_scores, p_values and fdr and the simes_* and max_p* summaries change; the AUROCs are the Wilcoxon ones either way. None picks "lr" for modality="atac", "wilcox" otherwise.

None
alternative Alternative

The test alternative; "greater" asks for genes up in the reference.

'greater'
min_prop float

A gene is tested if this share of any group expresses it.

0.05
modality DeModality

"rna", or "atac" for the peaks or tiles of a SingleCellsMultiModal; the ids are then in feature_id.

'rna'
verbose Verbose

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

True

Returns:

Type Description
ScSpecificMarkers | None

The ScSpecificMarkers, or None with a warning if no gene passed

ScSpecificMarkers | None

min_prop.

Raises:

Type Description
ValueError

If the column is missing, has fewer than two groups, or reference_group is not one of them.

References

Soneson and Robinson, Nat Methods, 2018; Lun, et al., F1000Research, 2016.

Examples:

>>> res = bv.de.find_specific_markers(sc, "cell_grp")
>>> summary = bv.de.get_marker_summary(res)
>>> ranked = summary.sort("min_auroc", descending=True)

get_marker_summary

get_marker_summary(x: ScSpecificMarkers) -> DataFrame

The per-gene summaries across every rival.

Parameters:

Name Type Description Default
x ScSpecificMarkers

The marker result.

required

Returns:

Type Description
DataFrame

A copy of the summary table.

get_marker_comparisons

get_marker_comparisons(x: ScSpecificMarkers) -> DataFrame

The per-rival statistics.

Parameters:

Name Type Description Default
x ScSpecificMarkers

The marker result.

required

Returns:

Type Description
DataFrame

A copy of the per-comparison table.

Pseudobulk edgeR

Marker genes, donor-aware differential expression and differential abundance.

Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=, the default on ATAC peaks) between two groups (find_markers), one-vs-rest for every group of a column (find_all_markers), or markers that hold up against every rival group separately (find_specific_markers). Expression with donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge, run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods (get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities. Start with find_all_markers to look at clusters, pseudobulk_dge or nebula to compare conditions across donors.

What lands where. Nothing here writes to obs, var or the cache. The marker tests and pseudobulk_dge return polars frames; find_specific_markers, nebula, get_milor_abundances and meld return frozen records (ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying nhoods_info.

Object types. The marker functions, get_pseudobulked, pseudobulk_dge and nebula take a SingleCells or a SingleCellsSubset, so a per cell type comparison is a subset away. get_milor_abundances and meld take a SingleCells only.

markers = bv.de.find_all_markers(sc, "cell_grp")
top = markers.filter(markers["fdr"] < 0.05)

Condition across donors, one pseudobulk sample per donor. cell_list maps the sample names to their cells and the rows of the design follow its order:

import polars as pl

obs = sc.obs(filtered=True)
cell_list = {
    s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
    for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
    {"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")

Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)

design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)

Gotchas. Designs are additive formulas over a frame, "~ condition + age": numeric columns as they are, everything else treatment coded against its first (sorted) level and named <column><level>. Interactions and transformations are not parsed. coef takes a 0-based design column or its name, and the last column is tested if you give neither. Every index is 0-based, Milo's Nhood included. get_milor_abundances and meld raise on a stale embedding or kNN, so rerun those after the cell filter moves, and they warn and return None without a kNN. nebula costs milliseconds to seconds per gene: hand genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and a design with an intercept and at least one more column.

PseudoBulked dataclass

PseudoBulked(
    counts: ndarray | CsrMatrix,
    samples: tuple[str, ...],
    gene_ids: ndarray,
)

Pseudobulked counts.

Attributes:

Name Type Description
counts ndarray | CsrMatrix

(n_samples, n_genes), a dense float64 array or a CSR, whose values are float32 as every CsrMatrix's.

samples tuple[str, ...]

The pseudobulk sample names, the rows.

gene_ids ndarray

The gene ids, the columns.

pseudobulk_dge

pseudobulk_dge(
    sc: ScOrScSubset,
    cell_list: Mapping[str, Selection],
    design: ndarray | DataFrame,
    *,
    coef: Coef | None = None,
    contrast: ndarray | Sequence[float] | None = None,
    edger_params: EdgerQlParams | None = None,
    modality: DeModality = "rna",
    verbose: Verbose = True,
) -> DataFrame

edgeR quasi-likelihood DGE on pseudobulked cells.

Sums the raw counts per sample and runs run_edger_ql on the result.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
cell_list Mapping[str, Selection]

Pseudobulk sample name to its 0-based cell indices or ids. The rows of design follow this order.

required
design ndarray | DataFrame

(n_samples, n_coef) design with an intercept.

required
coef Coef | None

See run_edger_ql.

None
contrast ndarray | Sequence[float] | None

See run_edger_ql.

None
edger_params EdgerQlParams | None

See run_edger_ql.

None
modality DeModality

"rna", or "atac" for differential accessibility on the peaks or tiles of a SingleCellsMultiModal.

'rna'
verbose Verbose

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

True

Returns:

Type Description
DataFrame

See run_edger_ql; feature_id holds the gene (or peak) ids.

Raises:

Type Description
ValueError

If the design rows do not match the samples.

References

Squair, et al., Nat Commun, 2021; Chen, Lun and Smyth, F1000Research, 2016.

Examples:

>>> res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")
>>> sig = res.filter(res["fdr"] < 0.05)

get_pseudobulked

get_pseudobulked(
    sc: ScOrScSubset,
    cell_list: Mapping[str, Selection],
    *,
    return_format: Literal["dense", "sparse"] = "dense",
    assay: Literal["raw", "norm"] = "raw",
    modality: DeModality = "rna",
    verbose: Verbose = True,
) -> PseudoBulked

Pseudobulk groups of cells.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
cell_list Mapping[str, Selection]

Pseudobulk sample name to its 0-based cell indices or ids.

required
return_format Literal['dense', 'sparse']

A dense array or a CSR matrix.

'dense'
assay Literal['raw', 'norm']

"raw" sums the raw counts, "norm" averages the normalised counts over the group, zeros included.

'raw'
modality DeModality

"rna", or "atac" for the peaks or tiles of a SingleCellsMultiModal; gene_ids then holds peak ids.

'rna'
verbose Verbose

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

True

Returns:

Type Description
PseudoBulked

The PseudoBulked, samples in cell_list order.

Raises:

Type Description
ValueError

If a group matches no cell.

Examples:

>>> obs = sc.obs(filtered=True)
>>> cell_list = {
...     s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
...     for s in obs["sample_id"].unique().sort()
... }
>>> pb = bv.de.get_pseudobulked(sc, cell_list, return_format="sparse")

run_edger_ql

run_edger_ql(
    counts: ndarray,
    design: ndarray | DataFrame,
    feature_ids: Sequence[str] | ndarray,
    *,
    coef: Coef | None = None,
    contrast: ndarray | Sequence[float] | None = None,
    edger_params: EdgerQlParams | None = None,
) -> DataFrame

edgeR's quasi-likelihood chain.

filterByExpr, calcNormFactors, glmQLFit and glmQLFTest, via edge-rs. The rows do not have to be genes: Milo tests neighbourhoods through here with filter=False.

Parameters:

Name Type Description Default
counts ndarray

(n_features, n_samples) raw counts.

required
design ndarray | DataFrame

(n_samples, n_coef) design with an intercept, at least two columns. A frame's column names can be used in coef.

required
feature_ids Sequence[str] | ndarray

One id per row of counts.

required
coef Coef | None

0-based design column(s) or names to drop from the null model. None tests the last column.

None
contrast ndarray | Sequence[float] | None

Weights over the design columns, a vector or an (n_coef, n_contrasts) matrix. Exclusive with coef.

None
edger_params EdgerQlParams | None

The parameters. None uses the defaults.

None

Returns:

Type Description
DataFrame

feature_id, log_fc (log2), log_cpm, f_stat, p_value and

DataFrame

fdr, one row per feature that survived the filters.

Raises:

Type Description
ValueError

On a design with fewer than two columns or a row count that does not match, negative counts, or both coef and contrast.

References

Chen, Lun and Smyth, F1000Research, 2016.

Examples:

>>> pb = bv.de.get_pseudobulked(sc, cell_list)
>>> res = bv.de.run_edger_ql(pb.counts.T, design, pb.gene_ids, coef="stim")

NEBULA

Marker genes, donor-aware differential expression and differential abundance.

Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=, the default on ATAC peaks) between two groups (find_markers), one-vs-rest for every group of a column (find_all_markers), or markers that hold up against every rival group separately (find_specific_markers). Expression with donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge, run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods (get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities. Start with find_all_markers to look at clusters, pseudobulk_dge or nebula to compare conditions across donors.

What lands where. Nothing here writes to obs, var or the cache. The marker tests and pseudobulk_dge return polars frames; find_specific_markers, nebula, get_milor_abundances and meld return frozen records (ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying nhoods_info.

Object types. The marker functions, get_pseudobulked, pseudobulk_dge and nebula take a SingleCells or a SingleCellsSubset, so a per cell type comparison is a subset away. get_milor_abundances and meld take a SingleCells only.

markers = bv.de.find_all_markers(sc, "cell_grp")
top = markers.filter(markers["fdr"] < 0.05)

Condition across donors, one pseudobulk sample per donor. cell_list maps the sample names to their cells and the rows of the design follow its order:

import polars as pl

obs = sc.obs(filtered=True)
cell_list = {
    s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
    for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
    {"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")

Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)

design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)

Gotchas. Designs are additive formulas over a frame, "~ condition + age": numeric columns as they are, everything else treatment coded against its first (sorted) level and named <column><level>. Interactions and transformations are not parsed. coef takes a 0-based design column or its name, and the last column is tested if you give neither. Every index is 0-based, Milo's Nhood included. get_milor_abundances and meld raise on a stale embedding or kNN, so rerun those after the cell filter moves, and they warn and return None without a kNN. nebula costs milliseconds to seconds per gene: hand genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and a design with an intercept and at least one more column.

ScNebula dataclass

ScNebula(
    results: DataFrame,
    coefficients: DataFrame,
    se: DataFrame,
    params: dict[str, object],
)

NEBULA fits.

Attributes:

Name Type Description
results DataFrame

One row per gene that survived NEBULA's expression filter: gene_id, log_fc (natural log), effect_se, z, p_value, fdr, subject_overdispersion, cell_overdispersion, convergence, sigma_at_bound and, with shrinkage, cell_overdispersion_shrunk.

coefficients DataFrame

gene_id and one column per design column, the fixed effects.

se DataFrame

The matching standard errors.

params dict[str, object]

The parameters of the run.

nebula

nebula(
    sc: ScOrScSubset,
    subject_col: str,
    design: str,
    *,
    coef: int | str | None = None,
    contrast: ndarray | Sequence[float] | None = None,
    genes_to_use: Selection | None = None,
    cells_to_use: Sequence[str] | None = None,
    offset: ndarray | Sequence[float] | None = None,
    nebula_params: NebulaParams | None = None,
    verbose: Verbose = True,
) -> ScNebula

NEBULA's negative binomial gamma mixed model.

The variance splits into a subject-level random effect and a cell-level overdispersion, so the donor structure is modelled rather than ignored. Genes stream through in batches, which is exact. A fit takes milliseconds to seconds per gene, so restrict genes_to_use to the HVGs or a candidate set.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
subject_col str

obs column with the subject (donor), the random effect.

required
design str

Formula over obs, e.g. "~ condition + age".

required
coef int | str | None

The coefficient the Wald test reports, a 0-based design column or its name. None takes the last column.

None
contrast ndarray | Sequence[float] | None

One weight per design column. Exclusive with coef.

None
genes_to_use Selection | None

0-based gene indices or ids. None fits every gene.

None
cells_to_use Sequence[str] | None

Cell ids to fit. None takes the kept cells; ids that are not kept warn and drop.

None
offset ndarray | Sequence[float] | None

Strictly positive scaling per cell, aligned to the cells that survive the design. None uses the library sizes.

None
nebula_params NebulaParams | 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
ScNebula

The ScNebula.

Raises:

Type Description
ValueError

On missing columns, no cells left, both coef and contrast, or a bad offset.

References

He, et al., Commun Biol, 2021.

Examples:

>>> bv.pp.find_hvg(sc, hvg_no=200)
>>> hvgs = sc.gene_ids(sc.map.hvg)
>>> res = bv.de.nebula(sc, "sample_id", "~ condition", genes_to_use=hvgs)
>>> top = res.results.sort("p_value").head()

Milo

Marker genes, donor-aware differential expression and differential abundance.

Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=, the default on ATAC peaks) between two groups (find_markers), one-vs-rest for every group of a column (find_all_markers), or markers that hold up against every rival group separately (find_specific_markers). Expression with donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge, run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods (get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities. Start with find_all_markers to look at clusters, pseudobulk_dge or nebula to compare conditions across donors.

What lands where. Nothing here writes to obs, var or the cache. The marker tests and pseudobulk_dge return polars frames; find_specific_markers, nebula, get_milor_abundances and meld return frozen records (ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying nhoods_info.

Object types. The marker functions, get_pseudobulked, pseudobulk_dge and nebula take a SingleCells or a SingleCellsSubset, so a per cell type comparison is a subset away. get_milor_abundances and meld take a SingleCells only.

markers = bv.de.find_all_markers(sc, "cell_grp")
top = markers.filter(markers["fdr"] < 0.05)

Condition across donors, one pseudobulk sample per donor. cell_list maps the sample names to their cells and the rows of the design follow its order:

import polars as pl

obs = sc.obs(filtered=True)
cell_list = {
    s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
    for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
    {"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")

Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)

design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)

Gotchas. Designs are additive formulas over a frame, "~ condition + age": numeric columns as they are, everything else treatment coded against its first (sorted) level and named <column><level>. Interactions and transformations are not parsed. coef takes a 0-based design column or its name, and the last column is tested if you give neither. Every index is 0-based, Milo's Nhood included. get_milor_abundances and meld raise on a stale embedding or kNN, so rerun those after the cell filter moves, and they warn and return None without a kNN. nebula costs milliseconds to seconds per gene: hand genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and a design with an intercept and at least one more column.

MiloRParams dataclass

MiloRParams(
    *,
    prop: float = 0.2,
    k_refine: int = 20,
    refinement_strategy: Literal[
        "index", "approximate", "bruteforce"
    ] = "index",
    index_type: Literal[
        "nndescent", "hnsw", "annoy", "exhaustive"
    ] = "nndescent",
    ann_dist: Literal["euclidean", "cosine"] = "euclidean",
    n_trees: int = 50,
    search_budget: int | None = None,
    m: int = 16,
    ef_construction: int = 200,
    ef_search: int = 100,
    delta: float = 0.001,
    diversify_prob: float = 0.0,
)

Parameters for the Milo neighbourhoods.

It carries the kNN keys the neighbourhood refinement reads.

Attributes:

Name Type Description
prop float

Share of cells sampled as neighbourhood indices.

k_refine int

Neighbours whose median position an index is moved towards.

refinement_strategy Literal['index', 'approximate', 'bruteforce']

"index" queries a kNN index for the cell nearest the median, "approximate" searches the k_refine neighbours, "bruteforce" every cell.

index_type Literal['nndescent', 'hnsw', 'annoy', 'exhaustive']

The kNN index "index" builds. "exhaustive" returns the true nearest cell.

ann_dist Literal['euclidean', 'cosine']

Distance metric of the refinement.

n_trees int

Annoy: number of trees.

search_budget int | None

Annoy: search budget per query.

m int

HNSW: connections per layer.

ef_construction int

HNSW: construction budget.

ef_search int

HNSW: search budget.

delta float

NNDescent: early termination criterium.

diversify_prob float

NNDescent: diversification probability.

MiloR dataclass

MiloR(
    nhoods: CsrMatrix,
    sample_counts: ndarray,
    samples: tuple[str, ...],
    spatial_dist: ndarray,
    nhood_overlap: ndarray,
    params: dict[str, object],
    nhoods_info: DataFrame | None = None,
)

Milo neighbourhoods and their test.

Attributes:

Name Type Description
nhoods CsrMatrix

Membership, (n_cells, n_nhoods); rows are the kept cells in cells_to_keep order.

sample_counts ndarray

(n_nhoods, n_samples) cells per neighbourhood and sample.

samples tuple[str, ...]

The sample names, the columns of sample_counts.

spatial_dist ndarray

Squared distance of each index cell to its last kNN neighbour, the "k-distance" weighting.

nhood_overlap ndarray

Cells each neighbourhood shares with all the others, the "graph-overlap" weighting.

params dict[str, object]

The parameters, plus used_emb, no_embd_to_use and index_cell, the 0-based positions among the kept cells.

nhoods_info DataFrame | None

The differential abundance table once test_nhoods ran.

get_milor_abundances

get_milor_abundances(
    sc: SingleCells,
    sample_id_col: str,
    *,
    embd_to_use: str = "pca",
    no_embd_to_use: int | None = None,
    milor_params: MiloRParams | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> MiloR | None

Milo neighbourhoods and their cell counts per sample.

Samples a share of the cells, moves each towards the median of its kNN neighbourhood, and counts the cells of every sample in the neighbourhood of each refined index. Test them with test_nhoods.

Parameters:

Name Type Description Default
sc SingleCells

The experiment, with an embedding and the kNN built on it.

required
sample_id_col str

obs column with the sample per cell.

required
embd_to_use str

The embedding the kNN was built on.

'pca'
no_embd_to_use int | None

Leading embedding dimensions to use. None for all.

None
milor_params MiloRParams | None

The parameters. None uses the defaults; a k_refine above the embedding width is lowered to it with a warning.

None
seed int

Seed.

42
verbose Verbose

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

True

Returns:

Type Description
MiloR | None

The MiloR, or None with a warning if there is no kNN.

Raises:

Type Description
ValueError

If the embedding is missing, it or the kNN is stale, or a kept cell has no sample.

References

Dann, et al., Nat Biotechnol, 2022.

Examples:

>>> params = bv.de.MiloRParams(prop=0.1)
>>> milo = bv.de.get_milor_abundances(sc, "sample_id", milor_params=params)

test_nhoods

test_nhoods(
    x: MiloR,
    design: str,
    design_df: DataFrame,
    *,
    sample_col: str = "sample_id",
    coef: Coef | None = None,
    contrast: ndarray | Sequence[float] | None = None,
    norm_method: MiloNorm = "TMM",
    min_mean: float = 0.0,
    robust: bool = True,
    legacy: bool = True,
    fdr_weighting: FdrWeighting = "k-distance",
) -> MiloR

Differential abundance of the neighbourhoods.

edgeR's quasi-likelihood test on the neighbourhood counts, with Milo's spatial FDR on top. filterByExpr stays off, it means nothing for a neighbourhood; use min_mean to drop sparse ones.

Parameters:

Name Type Description Default
x MiloR

The MiloR.

required
design str

Formula over design_df, e.g. "~ condition".

required
design_df DataFrame

One row per sample.

required
sample_col str

The design_df column with the sample names.

'sample_id'
coef Coef | None

See run_edger_ql.

None
contrast ndarray | Sequence[float] | None

See run_edger_ql.

None
norm_method MiloNorm

Library size normalisation; Milo's "logMS" leaves every factor at one.

'TMM'
min_mean float

Neighbourhoods with a lower mean count are dropped.

0.0
robust bool

Robust estimation of the quasi-likelihood dispersion.

True
legacy bool

edgeR's pre-4.0 pipeline, which is what Milo itself runs.

True
fdr_weighting FdrWeighting

Spatial FDR weights: the k-th neighbour distance, the overlap with other neighbourhoods, or none.

'k-distance'

Returns:

Type Description
MiloR

A new MiloR with nhoods_info: Nhood (0-based), logFC,

MiloR

logCPM, F, PValue, FDR and SpatialFDR.

Raises:

Type Description
ValueError

If the design rows and the samples do not match.

References

Dann, et al., Nat Biotechnol, 2022; Chen, Lun and Smyth, F1000Research, 2016.

Examples:

>>> cols = sc.obs().select("sample_id", "condition")
>>> design_df = cols.unique().sort("sample_id")
>>> milo = bv.de.test_nhoods(milo, "~ condition", design_df)

add_nhoods_info

add_nhoods_info(
    x: MiloR, cell_info: Sequence[str] | ndarray | Series
) -> MiloR

The majority cell type of each neighbourhood.

Adds majority_celltype (ties go to the first label in sorted order) and majority_prop to nhoods_info.

Parameters:

Name Type Description Default
x MiloR

A tested MiloR.

required
cell_info Sequence[str] | ndarray | Series

One label per row of nhoods, i.e. per kept cell.

required

Returns:

Type Description
MiloR

A new MiloR, or x with a warning if it was not tested yet.

Raises:

Type Description
ValueError

If cell_info does not have one label per cell.

Examples:

>>> milo = bv.de.add_nhoods_info(milo, sc.obs(filtered=True)["cell_grp"])

get_differential_abundance_res

get_differential_abundance_res(
    x: MiloR,
) -> DataFrame | None

The differential abundance table; warns and returns None if untested.

Parameters:

Name Type Description Default
x MiloR

The Milo result.

required

Returns:

Type Description
DataFrame | None

The neighbourhood table, or None before test_nhoods().

get_index_cells

get_index_cells(x: MiloR) -> ndarray

The neighbourhood index cells, 0-based positions among the kept cells.

Parameters:

Name Type Description Default
x MiloR

The Milo result.

required

Returns:

Type Description
ndarray

The index cell positions.

get_params

get_params(x: MiloR | ScNebula) -> dict[str, object]

The parameters of the run.

Parameters:

Name Type Description Default
x MiloR | ScNebula

The Milo or NEBULA result.

required

Returns:

Type Description
dict[str, object]

A copy of the parameters.

MELD

Marker genes, donor-aware differential expression and differential abundance.

Three jobs. Markers: Wilcoxon or Seurat's logistic regression test (method=, the default on ATAC peaks) between two groups (find_markers), one-vs-rest for every group of a column (find_all_markers), or markers that hold up against every rival group separately (find_specific_markers). Expression with donor structure: pseudobulk edgeR (get_pseudobulked, pseudobulk_dge, run_edger_ql) or the mixed model nebula. Abundance: Milo neighbourhoods (get_milor_abundances, test_nhoods, add_nhoods_info) and meld densities. Start with find_all_markers to look at clusters, pseudobulk_dge or nebula to compare conditions across donors.

What lands where. Nothing here writes to obs, var or the cache. The marker tests and pseudobulk_dge return polars frames; find_specific_markers, nebula, get_milor_abundances and meld return frozen records (ScSpecificMarkers, ScNebula, MiloR, MeldRes) with getters for their tables. test_nhoods and add_nhoods_info hand back a new MiloR carrying nhoods_info.

Object types. The marker functions, get_pseudobulked, pseudobulk_dge and nebula take a SingleCells or a SingleCellsSubset, so a per cell type comparison is a subset away. get_milor_abundances and meld take a SingleCells only.

markers = bv.de.find_all_markers(sc, "cell_grp")
top = markers.filter(markers["fdr"] < 0.05)

Condition across donors, one pseudobulk sample per donor. cell_list maps the sample names to their cells and the rows of the design follow its order:

import polars as pl

obs = sc.obs(filtered=True)
cell_list = {
    s: obs.filter(obs["sample_id"] == s)["cell_id"].to_list()
    for s in obs["sample_id"].unique().sort()
}
design = pl.DataFrame(
    {"(Intercept)": [1.0] * 6, "stim": [0.0, 0.0, 0.0, 1.0, 1.0, 1.0]}
)
pb_res = bv.de.pseudobulk_dge(sc, cell_list, design, coef="stim")

Milo needs a PCA and the kNN over it, and the sample column of obs. The design frame has one row per sample:

bv.pp.find_hvg(sc, hvg_no=500)
bv.pp.calculate_pca(sc, no_pcs=20)
bv.graph.find_neighbours(sc)

design_df = sc.obs().select("sample_id", "condition").unique().sort("sample_id")
milo = bv.de.get_milor_abundances(sc, "sample_id")
milo = bv.de.test_nhoods(milo, "~ condition", design_df)
da = bv.de.get_differential_abundance_res(milo)

Gotchas. Designs are additive formulas over a frame, "~ condition + age": numeric columns as they are, everything else treatment coded against its first (sorted) level and named <column><level>. Interactions and transformations are not parsed. coef takes a 0-based design column or its name, and the last column is tested if you give neither. Every index is 0-based, Milo's Nhood included. get_milor_abundances and meld raise on a stale embedding or kNN, so rerun those after the cell filter moves, and they warn and return None without a kNN. nebula costs milliseconds to seconds per gene: hand genes_to_use the HVGs or a candidate set. run_edger_ql wants raw counts and a design with an intercept and at least one more column.

MeldRes dataclass

MeldRes(raw_scores: DataFrame, norm_scores: DataFrame)

MELD densities.

Attributes:

Name Type Description
raw_scores DataFrame

cell_id and one column per sample, the filtered indicators.

norm_scores DataFrame

The same with negatives clamped to 0 and every row L1 normalised, so probability-like.

meld

meld(
    sc: SingleCells,
    sample_id_col: str,
    *,
    embd_to_use: str = "pca",
    meld_params: MeldParams | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> MeldRes | None

MELD sample densities over the kNN graph.

Smooths the one-hot sample indicators over the kNN graph with a Chebyshev-approximated spectral filter, giving a per-cell likelihood for each sample.

Parameters:

Name Type Description Default
sc SingleCells

The experiment, with the kNN.

required
sample_id_col str

obs column with the sample per cell.

required
embd_to_use str

The embedding the kNN was built on; only checked for staleness, as the kNN is what MELD reads.

'pca'
meld_params MeldParams | None

The parameters. None uses the defaults; the kNN keys are unused, the cached kNN is taken as is.

None
seed int

Seed for the largest eigenvalue estimate.

42
verbose Verbose

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

True

Returns:

Type Description
MeldRes | None

The MeldRes over the kept cells, or None with a warning if there

MeldRes | None

is no kNN.

Raises:

Type Description
ValueError

If the embedding or the kNN is stale, or a kept cell has no sample.

References

Burkhardt, et al., Nat Biotechnol, 2021.

Examples:

>>> meld_res = bv.de.meld(sc, "condition")
>>> scores = meld_res.norm_scores