Skip to content

Batch correction

Batch correction and integration metrics.

Pick a correction, then check it. harmony (v2) and harmony_v1 (the original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca work from the counts of the batch-aware HVGs, so run bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn skips the embedding and builds a batch-balanced kNN instead. The calculate_* functions score the result, and calculate_integration_metrics runs the lot and returns one row.

What lands where. Harmony, fastMNN, CCA and rPCA write a corrected embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn", "cca" and "rpca". bbknn writes sc.cache.knn and sc.cache.connectivities, replacing what is there. All are stamped. The metrics return records (or a table) and leave the experiment alone. Everything takes a SingleCells or SingleCellsSubset except seurat_cca and seurat_rpca, which want a SingleCells. The batch labels are an obs column named by batch_column; its levels are sorted, an Enum keeps its own order.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
    sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)

Gotchas. The kNN metrics (calculate_kbet, calculate_lisi, calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours on the corrected embedding before scoring it; on a stale kNN they warn, on one that covers other cells they raise. The silhouette widths are O(n^2) and subsample to max_cells (5000). calculate_pcr compares a corrected embedding with the PCA, so it needs both. For bbknn there is no embedding: pass embd_to_use=None to calculate_integration_metrics, and the metrics that need one come back null. A single batch warns and returns without doing anything, bar fast_mnn, which raises. seurat_cca and seurat_rpca with use_precomputed_pca=True still need the gene loadings, so they save less than fastMNN does.

Worked through in Batch correction with bixverse.

Embedding corrections

Batch correction and integration metrics.

Pick a correction, then check it. harmony (v2) and harmony_v1 (the original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca work from the counts of the batch-aware HVGs, so run bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn skips the embedding and builds a batch-balanced kNN instead. The calculate_* functions score the result, and calculate_integration_metrics runs the lot and returns one row.

What lands where. Harmony, fastMNN, CCA and rPCA write a corrected embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn", "cca" and "rpca". bbknn writes sc.cache.knn and sc.cache.connectivities, replacing what is there. All are stamped. The metrics return records (or a table) and leave the experiment alone. Everything takes a SingleCells or SingleCellsSubset except seurat_cca and seurat_rpca, which want a SingleCells. The batch labels are an obs column named by batch_column; its levels are sorted, an Enum keeps its own order.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
    sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)

Gotchas. The kNN metrics (calculate_kbet, calculate_lisi, calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours on the corrected embedding before scoring it; on a stale kNN they warn, on one that covers other cells they raise. The silhouette widths are O(n^2) and subsample to max_cells (5000). calculate_pcr compares a corrected embedding with the PCA, so it needs both. For bbknn there is no embedding: pass embd_to_use=None to calculate_integration_metrics, and the metrics that need one come back null. A single batch warns and returns without doing anything, bar fast_mnn, which raises. seurat_cca and seurat_rpca with use_precomputed_pca=True still need the gene loadings, so they save less than fastMNN does.

harmony

harmony(
    sc: ScOrScSubset,
    batch_column: str,
    *,
    additional_batch_columns: Sequence[str] | None = None,
    embd_to_use: str = "pca",
    modality: CacheModality = "rna",
    harmony_params: HarmonyV2Params | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> None

Harmony (v2) on the PCA or another embedding.

The corrected embedding goes to the modality's embeddings["harmony"], stamped as derived from embd_to_use. The original algorithm is harmony_v1. On ATAC, correct the LSI with embd_to_use="lsi", modality="atac", then build the neighbours on "harmony" with the same modality.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment, with the embedding.

required
batch_column str

obs column with the primary batch.

required
additional_batch_columns Sequence[str] | None

Further obs columns to regress out.

None
embd_to_use str

The embedding to correct, "pca" or a name in the modality's embeddings ("lsi" for ATAC).

'pca'
modality CacheModality

The cache to read and write: "rna", or "adt" / "atac" on a SingleCellsMultiModal.

'rna'
harmony_params HarmonyV2Params | None

The parameters. None uses the defaults; a None k becomes min(round(n_cells / 30), 100).

None
seed int

Seed.

42
verbose Verbose

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

True

Raises:

Type Description
ValueError

If the embedding is stale, or a batch column is missing or incomplete.

References

Patikas, et al., bioRxiv, 2026.

Examples:

>>> bv.integrate.harmony(sc, "batch_index")
>>> bv.integrate.harmony(
...     sc,
...     "batch_index",
...     harmony_params=bv.params.HarmonyV2Params(theta=(4.0,)),
... )

harmony_v1

harmony_v1(
    sc: ScOrScSubset,
    batch_column: str,
    *,
    additional_batch_columns: Sequence[str] | None = None,
    embd_to_use: str = "pca",
    modality: CacheModality = "rna",
    harmony_params: HarmonyParams | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> None

The original Harmony (v1) on the PCA or another embedding.

The corrected embedding goes to the modality's embeddings["harmony_v1"], stamped as derived from embd_to_use.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment, with the embedding.

required
batch_column str

obs column with the primary batch.

required
additional_batch_columns Sequence[str] | None

Further obs columns to regress out.

None
embd_to_use str

The embedding to correct, "pca" or a name in the modality's embeddings ("lsi" for ATAC).

'pca'
modality CacheModality

The cache to read and write: "rna", or "adt" / "atac" on a SingleCellsMultiModal.

'rna'
harmony_params HarmonyParams | None

The parameters. None uses the defaults; a None k becomes min(round(n_cells / 30), 100).

None
seed int

Seed.

42
verbose Verbose

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

True

Raises:

Type Description
ValueError

If the embedding is stale, or a batch column is missing or incomplete.

References

Korsunsky, et al., Nat Methods, 2019.

fast_mnn

fast_mnn(
    sc: ScOrScSubset,
    batch_column: str,
    batch_hvg_genes: ndarray
    | Sequence[int]
    | Sequence[str],
    *,
    fastmnn_params: FastmnnParams | None = None,
    use_precomputed_pca: bool = False,
    seed: int = 42,
    verbose: Verbose = True,
) -> None

fastMNN on a PCA of the batch-aware HVGs.

The corrected embedding goes to sc.cache.embeddings["mnn"], stamped as derived from "pca" when the cached PCA was used, else unparented.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
batch_column str

obs column with the batch.

required
batch_hvg_genes ndarray | Sequence[int] | Sequence[str]

0-based gene indices or gene ids, ideally from find_hvg_batch_aware.

required
fastmnn_params FastmnnParams | None

The parameters. None uses the defaults.

None
use_precomputed_pca bool

Use the cached PCA instead of computing one on batch_hvg_genes.

False
seed int

Seed.

42
verbose Verbose

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

True

Raises:

Type Description
ValueError

If the batch column is missing or incomplete, or the cached PCA is stale with use_precomputed_pca.

BixverseError

With fewer than two batches.

References

Haghverdi, et al., Nat Biotechnol, 2018.

Examples:

>>> batch_hvg = bv.pp.find_hvg_batch_aware(sc, "batch_index", hvg_no=500)
>>> bv.integrate.fast_mnn(sc, "batch_index", batch_hvg.hvg_gene_idx)

seurat_cca

seurat_cca(
    sc: SingleCells,
    batch_column: str,
    batch_hvg_genes: ndarray
    | Sequence[int]
    | Sequence[str],
    *,
    cca_params: SeuratCcaParams | None = None,
    use_precomputed_pca: bool = False,
    seed: int = 42,
    verbose: Verbose = True,
) -> None

Seurat CCA anchor integration.

The corrected embedding goes to sc.cache.embeddings["cca"], stamped as derived from "pca" when the cached PCA was used, else unparented. One batch warns and leaves the experiment alone.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
batch_column str

obs column with the batch.

required
batch_hvg_genes ndarray | Sequence[int] | Sequence[str]

0-based gene indices or gene ids, ideally from find_hvg_batch_aware.

required
cca_params SeuratCcaParams | None

The parameters. None uses the defaults.

None
use_precomputed_pca bool

Correct the cached PCA instead of computing one. The gene-space filter still needs the loadings, so this saves less than it does for fastMNN.

False
seed int

Seed.

42
verbose Verbose

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

True

Raises:

Type Description
ValueError

If the batch column is missing or incomplete, or the cached PCA is stale with use_precomputed_pca.

References

Stuart, et al., Cell, 2019.

Examples:

>>> batch_hvg = bv.pp.find_hvg_batch_aware(sc, "batch_index", hvg_no=500)
>>> bv.integrate.seurat_cca(sc, "batch_index", batch_hvg.hvg_gene_idx)

seurat_rpca

seurat_rpca(
    sc: SingleCells,
    batch_column: str,
    batch_hvg_genes: ndarray
    | Sequence[int]
    | Sequence[str],
    *,
    rpca_params: SeuratRpcaParams | None = None,
    use_precomputed_pca: bool = False,
    seed: int = 42,
    verbose: Verbose = True,
) -> None

Seurat reciprocal PCA anchor integration.

The corrected embedding goes to sc.cache.embeddings["rpca"], stamped as derived from "pca" when the cached PCA was used, else unparented. One batch warns and leaves the experiment alone.

Parameters:

Name Type Description Default
sc SingleCells

The experiment.

required
batch_column str

obs column with the batch.

required
batch_hvg_genes ndarray | Sequence[int] | Sequence[str]

0-based gene indices or gene ids, ideally from find_hvg_batch_aware.

required
rpca_params SeuratRpcaParams | None

The parameters. None uses the defaults.

None
use_precomputed_pca bool

Correct the cached PCA instead of computing the union PCA; the per-batch PCAs are always computed.

False
seed int

Seed.

42
verbose Verbose

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

True

Raises:

Type Description
ValueError

If the batch column is missing or incomplete, or the cached PCA is stale with use_precomputed_pca.

References

Stuart, et al., Cell, 2019.

Examples:

>>> batch_hvg = bv.pp.find_hvg_batch_aware(sc, "batch_index", hvg_no=500)
>>> bv.integrate.seurat_rpca(sc, "batch_index", batch_hvg.hvg_gene_idx)

Batch-balanced neighbours

Batch correction and integration metrics.

Pick a correction, then check it. harmony (v2) and harmony_v1 (the original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca work from the counts of the batch-aware HVGs, so run bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn skips the embedding and builds a batch-balanced kNN instead. The calculate_* functions score the result, and calculate_integration_metrics runs the lot and returns one row.

What lands where. Harmony, fastMNN, CCA and rPCA write a corrected embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn", "cca" and "rpca". bbknn writes sc.cache.knn and sc.cache.connectivities, replacing what is there. All are stamped. The metrics return records (or a table) and leave the experiment alone. Everything takes a SingleCells or SingleCellsSubset except seurat_cca and seurat_rpca, which want a SingleCells. The batch labels are an obs column named by batch_column; its levels are sorted, an Enum keeps its own order.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
    sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)

Gotchas. The kNN metrics (calculate_kbet, calculate_lisi, calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours on the corrected embedding before scoring it; on a stale kNN they warn, on one that covers other cells they raise. The silhouette widths are O(n^2) and subsample to max_cells (5000). calculate_pcr compares a corrected embedding with the PCA, so it needs both. For bbknn there is no embedding: pass embd_to_use=None to calculate_integration_metrics, and the metrics that need one come back null. A single batch warns and returns without doing anything, bar fast_mnn, which raises. seurat_cca and seurat_rpca with use_precomputed_pca=True still need the gene loadings, so they save less than fastMNN does.

bbknn

bbknn(
    sc: ScOrScSubset,
    batch_column: str,
    *,
    no_neighbours_to_keep: int = 5,
    embd_to_use: Literal["pca"] = "pca",
    no_embd_to_use: int | None = None,
    bbknn_params: BbknnParams | None = None,
    seed: int = 42,
    verbose: Verbose = True,
) -> None

Batch-balanced kNN.

The kNN goes to sc.cache.knn, stamped as derived from the embedding, and the max-symmetrised BBKNN connectivities to sc.cache.connectivities, stamped as derived from "knn". The kNN keeps the no_neighbours_to_keep nearest of the per-batch neighbours of each cell, balanced across batches: each batch keeps its nearest ceil(no_neighbours_to_keep / n_batches), and slots a batch cannot fill go to the nearest of the rest. Rows are sorted by distance.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment, with a PCA.

required
batch_column str

obs column with the batch.

required
no_neighbours_to_keep int

Neighbours per cell in the stored kNN; capped at n_batches * neighbours_within_batch.

5
embd_to_use Literal['pca']

The embedding; only "pca".

'pca'
no_embd_to_use int | None

Number of leading dimensions to use. None for all.

None
bbknn_params BbknnParams | None

The parameters. None uses the defaults.

None
seed int

Seed.

42
verbose Verbose

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

True

Raises:

Type Description
ValueError

If the embedding is stale, or the batch column is missing or incomplete.

References

Polański, et al., Bioinformatics, 2020.

Examples:

>>> bv.integrate.bbknn(
...     sc,
...     "batch_index",
...     bbknn_params=bv.params.BbknnParams(neighbours_within_batch=5),
... )

All metrics in one table

Batch correction and integration metrics.

Pick a correction, then check it. harmony (v2) and harmony_v1 (the original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca work from the counts of the batch-aware HVGs, so run bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn skips the embedding and builds a batch-balanced kNN instead. The calculate_* functions score the result, and calculate_integration_metrics runs the lot and returns one row.

What lands where. Harmony, fastMNN, CCA and rPCA write a corrected embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn", "cca" and "rpca". bbknn writes sc.cache.knn and sc.cache.connectivities, replacing what is there. All are stamped. The metrics return records (or a table) and leave the experiment alone. Everything takes a SingleCells or SingleCellsSubset except seurat_cca and seurat_rpca, which want a SingleCells. The batch labels are an obs column named by batch_column; its levels are sorted, an Enum keeps its own order.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
    sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)

Gotchas. The kNN metrics (calculate_kbet, calculate_lisi, calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours on the corrected embedding before scoring it; on a stale kNN they warn, on one that covers other cells they raise. The silhouette widths are O(n^2) and subsample to max_cells (5000). calculate_pcr compares a corrected embedding with the PCA, so it needs both. For bbknn there is no embedding: pass embd_to_use=None to calculate_integration_metrics, and the metrics that need one come back null. A single batch warns and returns without doing anything, bar fast_mnn, which raises. seurat_cca and seurat_rpca with use_precomputed_pca=True still need the gene loadings, so they save less than fastMNN does.

calculate_integration_metrics

calculate_integration_metrics(
    sc: ScOrScSubset,
    batch_column: str,
    *,
    cell_type_column: str | None = None,
    embd_to_use: str | None = "pca",
    max_cells: int | None = 5000,
    seed: int = 42,
    verbose: Verbose = True,
) -> DataFrame

The batch mixing and biological conservation metrics in one row.

Every column is on [0, 1] (the PCR comparison can go negative), higher is better: kbet_accept (1 - rejection rate), batch_asw (mean(1 - |s|)), ilisi, pcr_comparison, clisi, cell_type_asw and graph_connectivity. The kNN metrics read the cached kNN, so rebuild the neighbours on the corrected embedding first. A metric that cannot run (no kNN, no embedding, embd_to_use=None as for BBKNN, no cell_type_column) is null.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
batch_column str

obs column with the batch.

required
cell_type_column str | None

obs column with the cell types; None skips the conservation metrics.

None
embd_to_use str | None

The embedding for the silhouettes and the PCR; None skips them.

'pca'
max_cells int | None

Subsampling for the silhouette widths.

5000
seed int

Seed for the subsampling.

42
verbose Verbose

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

True

Returns:

Type Description
DataFrame

One row: embedding, kbet_accept, batch_asw, ilisi,

DataFrame

pcr_comparison, clisi, cell_type_asw, graph_connectivity.

References

Luecken, et al., Nat Methods, 2022.

Examples:

>>> metrics = bv.integrate.calculate_integration_metrics(
...     sc, "batch_index", cell_type_column="cell_grp", embd_to_use="mnn"
... )

Batch mixing

Batch correction and integration metrics.

Pick a correction, then check it. harmony (v2) and harmony_v1 (the original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca work from the counts of the batch-aware HVGs, so run bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn skips the embedding and builds a batch-balanced kNN instead. The calculate_* functions score the result, and calculate_integration_metrics runs the lot and returns one row.

What lands where. Harmony, fastMNN, CCA and rPCA write a corrected embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn", "cca" and "rpca". bbknn writes sc.cache.knn and sc.cache.connectivities, replacing what is there. All are stamped. The metrics return records (or a table) and leave the experiment alone. Everything takes a SingleCells or SingleCellsSubset except seurat_cca and seurat_rpca, which want a SingleCells. The batch labels are an obs column named by batch_column; its levels are sorted, an Enum keeps its own order.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
    sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)

Gotchas. The kNN metrics (calculate_kbet, calculate_lisi, calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours on the corrected embedding before scoring it; on a stale kNN they warn, on one that covers other cells they raise. The silhouette widths are O(n^2) and subsample to max_cells (5000). calculate_pcr compares a corrected embedding with the PCA, so it needs both. For bbknn there is no embedding: pass embd_to_use=None to calculate_integration_metrics, and the metrics that need one come back null. A single batch warns and returns without doing anything, bar fast_mnn, which raises. seurat_cca and seurat_rpca with use_precomputed_pca=True still need the gene loadings, so they save less than fastMNN does.

KbetScores dataclass

KbetScores(
    kbet_score: float,
    significant_tests: ndarray,
    p_values: ndarray,
    chi_square_stats: ndarray,
    mean_chi_square: float,
    median_chi_square: float,
    threshold: float,
    n_batches: int,
)

kBET result.

Attributes:

Name Type Description
kbet_score float

Share of cells whose test is significant; 0 is perfect mixing, 1 none.

significant_tests ndarray

Per cell, whether the p-value is at or below threshold.

p_values ndarray

Per-cell chi-square p-values.

chi_square_stats ndarray

Per-cell chi-square statistics.

mean_chi_square float

Mean chi-square statistic.

median_chi_square float

Median chi-square statistic.

threshold float

The significance threshold.

n_batches int

Number of batches.

LisiScores dataclass

LisiScores(
    per_cell: ndarray,
    mean_lisi: float,
    median_lisi: float,
    lisi_norm: float,
    n_labels: int,
    type: LisiType,
)

iLISI or cLISI.

Attributes:

Name Type Description
per_cell ndarray

Per-cell LISI in [1, n_labels].

mean_lisi float

Mean LISI.

median_lisi float

Median LISI.

lisi_norm float

The scIB rescaling onto [0, 1], higher is better.

n_labels int

Number of distinct labels.

type LisiType

"batch" (iLISI) or "cell_type" (cLISI).

BatchSilhouetteScores dataclass

BatchSilhouetteScores(
    per_cell: ndarray,
    mean_asw: float,
    median_asw: float,
    n_batches: int,
    embedding_used: str,
)

Batch silhouette width.

Attributes:

Name Type Description
per_cell ndarray

Per-cell silhouettes in [-1, 1]; near 0 is mixed, near 1 separated, negative overcorrected.

mean_asw float

Mean silhouette width.

median_asw float

Median silhouette width.

n_batches int

Number of batches.

embedding_used str

The embedding.

PcrScores dataclass

PcrScores(
    pcr: float,
    pcr_pca: float,
    pcr_comparison: float | None,
    var_explained: ndarray,
    r_squared: ndarray,
    embedding_used: str,
)

Principal component regression on batch.

Attributes:

Name Type Description
pcr float

Variance-weighted R-squared of batch on the embedding.

pcr_pca float

The same on the uncorrected PCA.

pcr_comparison float | None

(pcr_pca - pcr) / pcr_pca; None on the PCA.

var_explained ndarray

Variance per embedding dimension.

r_squared ndarray

Batch R-squared per embedding dimension.

embedding_used str

The embedding.

calculate_kbet

calculate_kbet(
    sc: ScOrScSubset,
    batch_column: str,
    *,
    threshold: float = 0.05,
    verbose: Verbose = True,
) -> KbetScores | None

kBET on the cached kNN.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment, with a kNN.

required
batch_column str

obs column with the batch.

required
threshold float

p-values at or below it count as significant.

0.05
verbose Verbose

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

True

Returns:

Type Description
KbetScores | None

The scores; None (with a warning) for one batch or no kNN.

Raises:

Type Description
ValueError

On a threshold outside [0, 1], a missing batch column or a kNN over other cells.

References

Büttner, et al., Nat Methods, 2019.

Examples:

>>> bv.graph.find_neighbours(sc, embd_to_use="mnn")
>>> kbet = bv.integrate.calculate_kbet(sc, "batch_index")

calculate_lisi

calculate_lisi(
    sc: ScOrScSubset,
    label_column: str,
    *,
    type: LisiType = "batch",
    weighted: bool = False,
    perplexity: float = 30.0,
    verbose: Verbose = True,
) -> LisiScores | None

LISI on the cached kNN.

iLISI on batch labels, cLISI on cell type labels; lisi_norm is the scIB rescaling for the chosen type.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment, with a kNN.

required
label_column str

obs column with the batch or cell type labels.

required
type LisiType

"batch" (iLISI) or "cell_type" (cLISI).

'batch'
weighted bool

Weight the neighbours with a perplexity-calibrated Gaussian kernel on the kNN distances; else uniformly.

False
perplexity float

Perplexity of the weighted version; clamped to k.

30.0
verbose Verbose

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

True

Returns:

Type Description
LisiScores | None

The scores; None (with a warning) for one label or no kNN.

Raises:

Type Description
ValueError

On a non-positive perplexity, a missing label column or a kNN over other cells.

References

Korsunsky, et al., Nat Methods, 2019; Luecken, et al., Nat Methods, 2022.

Examples:

>>> ilisi = bv.integrate.calculate_lisi(sc, "batch_index")
>>> clisi = bv.integrate.calculate_lisi(sc, "cell_grp", type="cell_type")

calculate_batch_asw

calculate_batch_asw(
    sc: ScOrScSubset,
    batch_column: str,
    *,
    embd_to_use: str = "pca",
    max_cells: int | None = 5000,
    seed: int = 42,
    verbose: Verbose = True,
) -> BatchSilhouetteScores | None

Batch average silhouette width on an embedding.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
batch_column str

obs column with the batch.

required
embd_to_use str

The embedding, "pca" or a name in sc.cache.embeddings.

'pca'
max_cells int | None

Subsample to this many cells, the pass is O(n^2). None uses all.

5000
seed int

Seed for the subsampling.

42
verbose Verbose

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

True

Returns:

Type Description
BatchSilhouetteScores | None

The scores; None (with a warning) for one batch or a missing

BatchSilhouetteScores | None

embedding.

Raises:

Type Description
ValueError

If the batch column is missing or incomplete.

Examples:

>>> asw = bv.integrate.calculate_batch_asw(sc, "batch_index", embd_to_use="mnn")

calculate_pcr

calculate_pcr(
    sc: ScOrScSubset,
    batch_column: str,
    *,
    embd_to_use: str = "pca",
) -> PcrScores | None

Principal component regression on batch.

On a corrected embedding it also runs on the PCA and reports the scIB comparison (pre - post) / pre: 1 means the batch variance is gone.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment, with a PCA.

required
batch_column str

obs column with the batch.

required
embd_to_use str

The embedding, "pca" or a name in sc.cache.embeddings.

'pca'

Returns:

Type Description
PcrScores | None

The scores; None (with a warning) for one batch, or without the

PcrScores | None

PCA or the embedding.

Raises:

Type Description
ValueError

If the batch column is missing or incomplete.

References

Büttner, et al., Nat Methods, 2019; Luecken, et al., Nat Methods, 2022.

Examples:

>>> pcr = bv.integrate.calculate_pcr(sc, "batch_index", embd_to_use="mnn")

Biological conservation

Batch correction and integration metrics.

Pick a correction, then check it. harmony (v2) and harmony_v1 (the original) correct the cached PCA. fast_mnn, seurat_cca and seurat_rpca work from the counts of the batch-aware HVGs, so run bv.pp.find_hvg_batch_aware first and hand them its hvg_gene_idx. bbknn skips the embedding and builds a batch-balanced kNN instead. The calculate_* functions score the result, and calculate_integration_metrics runs the lot and returns one row.

What lands where. Harmony, fastMNN, CCA and rPCA write a corrected embedding to sc.cache.embeddings under "harmony", "harmony_v1", "mnn", "cca" and "rpca". bbknn writes sc.cache.knn and sc.cache.connectivities, replacing what is there. All are stamped. The metrics return records (or a table) and leave the experiment alone. Everything takes a SingleCells or SingleCellsSubset except seurat_cca and seurat_rpca, which want a SingleCells. The batch labels are an obs column named by batch_column; its levels are sorted, an Enum keeps its own order.

bv.pp.find_hvg(sc, hvg_no=2000)
bv.pp.calculate_pca(sc, no_pcs=30)
bv.integrate.harmony(sc, "batch_index")
bv.graph.find_neighbours(sc, embd_to_use="harmony")
metrics = bv.integrate.calculate_integration_metrics(
    sc, "batch_index", cell_type_column="cell_grp", embd_to_use="harmony"
)

Gotchas. The kNN metrics (calculate_kbet, calculate_lisi, calculate_graph_connectivity) read the cached kNN, so rebuild the neighbours on the corrected embedding before scoring it; on a stale kNN they warn, on one that covers other cells they raise. The silhouette widths are O(n^2) and subsample to max_cells (5000). calculate_pcr compares a corrected embedding with the PCA, so it needs both. For bbknn there is no embedding: pass embd_to_use=None to calculate_integration_metrics, and the metrics that need one come back null. A single batch warns and returns without doing anything, bar fast_mnn, which raises. seurat_cca and seurat_rpca with use_precomputed_pca=True still need the gene loadings, so they save less than fastMNN does.

CellTypeAswScores dataclass

CellTypeAswScores(
    per_cell: ndarray,
    mean_asw: float,
    median_asw: float,
    n_cell_types: int,
    embedding_used: str,
)

Cell type silhouette width rescaled to [0, 1].

Attributes:

Name Type Description
per_cell ndarray

Per-cell rescaled silhouettes.

mean_asw float

Mean rescaled silhouette width.

median_asw float

Median rescaled silhouette width.

n_cell_types int

Number of cell types.

embedding_used str

The embedding.

GraphConnectivityScores dataclass

GraphConnectivityScores(
    per_cell_type: DataFrame,
    mean_connectivity: float,
    median_connectivity: float,
)

Graph connectivity per cell type.

Attributes:

Name Type Description
per_cell_type DataFrame

cell_type and connectivity, the share of the cell type's cells in its largest connected component; in order of first appearance.

mean_connectivity float

Mean over cell types.

median_connectivity float

Median over cell types.

calculate_cell_type_asw

calculate_cell_type_asw(
    sc: ScOrScSubset,
    cell_type_column: str,
    *,
    embd_to_use: str = "pca",
    max_cells: int | None = 5000,
    seed: int = 42,
    verbose: Verbose = True,
) -> CellTypeAswScores | None

Cell type silhouette width on an embedding, rescaled to [0, 1].

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment.

required
cell_type_column str

obs column with the cell types.

required
embd_to_use str

The embedding, "pca" or a name in sc.cache.embeddings.

'pca'
max_cells int | None

Subsample to this many cells. None uses all.

5000
seed int

Seed for the subsampling.

42
verbose Verbose

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

True

Returns:

Type Description
CellTypeAswScores | None

The scores; None (with a warning) for one cell type or a missing

CellTypeAswScores | None

embedding.

Raises:

Type Description
ValueError

If the cell type column is missing or incomplete.

References

Luecken, et al., Nat Methods, 2022.

Examples:

>>> ct_asw = bv.integrate.calculate_cell_type_asw(
...     sc, "cell_grp", embd_to_use="mnn"
... )

calculate_graph_connectivity

calculate_graph_connectivity(
    sc: ScOrScSubset, cell_type_column: str
) -> GraphConnectivityScores | None

Graph connectivity per cell type on the cached kNN.

Parameters:

Name Type Description Default
sc ScOrScSubset

The experiment, with a kNN.

required
cell_type_column str

obs column with the cell types.

required

Returns:

Type Description
GraphConnectivityScores | None

The scores; None (with a warning) without a kNN or with a single

GraphConnectivityScores | None

cell type.

Raises:

Type Description
ValueError

If the cell type column is missing or incomplete, or the kNN covers other cells.

References

Luecken, et al., Nat Methods, 2022.

Examples:

>>> conn = bv.integrate.calculate_graph_connectivity(sc, "cell_grp")